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
jhch1995/UL-SLAM-Mono
3,410
Thirdparty/g2o/g2o/stuff/property.cpp
// g2o - General Graph Optimization // Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "property.h" #include <vector> #include <iostream> #include "macros.h" #include "string_tools.h" using namespace std; namespace g2o { BaseProperty::BaseProperty(const std::string name_) :_name(name_){ } BaseProperty::~BaseProperty(){} bool PropertyMap::addProperty(BaseProperty* p) { std::pair<PropertyMapIterator,bool> result = insert(make_pair(p->name(), p)); return result.second; } bool PropertyMap::eraseProperty(const std::string& name) { PropertyMapIterator it=find(name); if (it==end()) return false; delete it->second; erase(it); return true; } PropertyMap::~PropertyMap() { for (PropertyMapIterator it=begin(); it!=end(); it++){ if (it->second) delete it->second; } } bool PropertyMap::updatePropertyFromString(const std::string& name, const std::string& value) { PropertyMapIterator it = find(name); if (it == end()) return false; it->second->fromString(value); return true; } void PropertyMap::writeToCSV(std::ostream& os) const { for (PropertyMapConstIterator it=begin(); it!=end(); it++){ BaseProperty* p =it->second; os << p->name() << ", "; } os << std::endl; for (PropertyMapConstIterator it=begin(); it!=end(); it++){ BaseProperty* p =it->second; os << p->toString() << ", "; } os << std::endl; } bool PropertyMap::updateMapFromString(const std::string& values) { bool status = true; vector<string> valuesMap = strSplit(values, ","); for (size_t i = 0; i < valuesMap.size(); ++i) { vector<string> m = strSplit(valuesMap[i], "="); if (m.size() != 2) { cerr << __PRETTY_FUNCTION__ << ": unable to extract name=value pair from " << valuesMap[i] << endl; continue; } string name = trim(m[0]); string value = trim(m[1]); status = status && updatePropertyFromString(name, value); } return status; } } // end namespace
412
0.962679
1
0.962679
game-dev
MEDIA
0.251241
game-dev
0.94359
1
0.94359
PotRooms/StarResonanceData
4,840
lua/ui/view/personalzone_obtained_popup_view.lua
local UI = Z.UI local super = require("ui.ui_view_base") local Personalzone_obtained_popupView = class("Personalzone_obtained_popupView", super) local DEFINE = require("ui.model.personalzone_define") local PlayerPortraitHgr = require("ui.component.role_info.common_player_portrait_item_mgr") function Personalzone_obtained_popupView:ctor() self.uiBinder = nil self.viewData = nil super.ctor(self, "personalzone_obtained_popup") self.personalZoneVM_ = Z.VMMgr.GetVM("personal_zone") self.personalZoneData_ = Z.DataMgr.Get("personal_zone_data") end function Personalzone_obtained_popupView:OnActive() self.modelId_ = Z.EntityMgr.PlayerEnt:GetLuaAttr(Z.ModelAttr.EModelID).Value self.uiBinder.scenemask_bg:SetSceneMaskByKey(self.SceneMaskKey) self.uiBinder.presscheck:StartCheck() self:EventAddAsyncListener(self.uiBinder.presscheck.ContainGoEvent, function(isContain) if not isContain then Z.UIMgr:CloseView(self.viewConfigKey) end end, nil, nil) local functionId = 0 if Z.IsPCUI then self.uiBinder.lab_click_close.text = Lang("ClickOnBlankSpaceClosePC") else self.uiBinder.lab_click_close.text = Lang("ClickOnBlankSpaceClosePhone") end self.uiBinder.Ref:SetVisible(self.uiBinder.lab_title_name, false) self.uiBinder.com_head_51_item.Ref.UIComp:SetVisible(false) self.uiBinder.Ref:SetVisible(self.uiBinder.rimg_idcard, false) self.uiBinder.Ref:SetVisible(self.uiBinder.rimg_medal, false) self.uiBinder.Ref:SetVisible(self.uiBinder.rimg_personalzonebg, false) if self.viewData.type == DEFINE.ProfileImageType.Medal then self.uiBinder.Ref:SetVisible(self.uiBinder.rimg_medal, true) local medalConfig = Z.TableMgr.GetTable("MedalTableMgr").GetRow(self.viewData.id) self.uiBinder.rimg_medal:SetImage(medalConfig.Image) self.uiBinder.rimg_bg:SetHeight(360) self.uiBinder.lab_title.fontSize = 60 functionId = E.FunctionID.PersonalzoneMedal elseif self.viewData.type == DEFINE.ProfileImageType.Head then self.uiBinder.com_head_51_item.Ref.UIComp:SetVisible(true) local viewData = {} viewData.id = self.viewData.id viewData.modelId = self.modelId_ viewData.isShowCombinationIcon = false viewData.isShowTalentIcon = false viewData.token = self.cancelSource:CreateToken() PlayerPortraitHgr.InsertNewPortrait(self.uiBinder.com_head_51_item, viewData) self.uiBinder.rimg_bg:SetHeight(360) self.uiBinder.lab_title.fontSize = 60 functionId = E.FunctionID.PersonalzoneHead elseif self.viewData.type == DEFINE.ProfileImageType.HeadFrame then self.uiBinder.com_head_51_item.Ref.UIComp:SetVisible(true) local viewData = {} viewData.headFrameId = self.viewData.id viewData.token = self.cancelSource:CreateToken() PlayerPortraitHgr.InsertNewPortrait(self.uiBinder.com_head_51_item, viewData) self.uiBinder.rimg_bg:SetHeight(360) self.uiBinder.lab_title.fontSize = 60 functionId = E.FunctionID.PersonalzoneHeadFrame elseif self.viewData.type == DEFINE.ProfileImageType.Card then local profileImageConfig = Z.TableMgr.GetTable("ProfileImageTableMgr").GetRow(self.viewData.id) if profileImageConfig then self.uiBinder.Ref:SetVisible(self.uiBinder.rimg_idcard, true) self.uiBinder.rimg_idcard:SetImage(Z.ConstValue.PersonalZone.PersonalCardBg .. profileImageConfig.Image) end self.uiBinder.rimg_bg:SetHeight(360) self.uiBinder.lab_title.fontSize = 60 functionId = E.FunctionID.PersonalzoneCard elseif self.viewData.type == DEFINE.ProfileImageType.Title then local profileImageConfig = Z.TableMgr.GetTable("ProfileImageTableMgr").GetRow(self.viewData.id) if profileImageConfig then self.uiBinder.Ref:SetVisible(self.uiBinder.lab_title_name, true) self.uiBinder.lab_title_name.text = profileImageConfig.Name end self.uiBinder.rimg_bg:SetHeight(100) self.uiBinder.lab_title.fontSize = 30 functionId = E.FunctionID.PersonalzoneTitle elseif self.viewData.type == DEFINE.ProfileImageType.PersonalzoneBg then local profileImageConfig = Z.TableMgr.GetTable("ProfileImageTableMgr").GetRow(self.viewData.id) if profileImageConfig then self.uiBinder.Ref:SetVisible(self.uiBinder.rimg_personalzonebg, true) self.uiBinder.rimg_personalzonebg:SetImage(profileImageConfig.Image) end self.uiBinder.rimg_bg:SetHeight(360) self.uiBinder.lab_title.fontSize = 60 functionId = E.FunctionID.PersonalzoneBg end local funcRow = Z.TableMgr.GetTable("FunctionTableMgr").GetRow(functionId) if funcRow then self.uiBinder.lab_title.text = funcRow.Name else self.uiBinder.lab_title.text = "" end end function Personalzone_obtained_popupView:OnDeActive() self.uiBinder.presscheck:StopCheck() end function Personalzone_obtained_popupView:OnRefresh() end return Personalzone_obtained_popupView
412
0.641618
1
0.641618
game-dev
MEDIA
0.541716
game-dev,desktop-app
0.929022
1
0.929022
mcutree/Project-update-weekly
20,330
0045、贪吃蛇+俄罗斯方块+万年历/main.c
#include <at89x51.h> #include "18b20.h" #include "1302.h" #include "12864.h" #include "zifu.h" uchar k,direction; bit flag; bit flag5=0; //flag5ⲿж1ı־λ flag1Dz־ uchar p,dengji; //ʱ bit flag1=0; systemtime realtime; bit first=1; //жϴ void dingshi() interrupt 1 using 1 //ʱ.ʱ { if(p--) { TL0=0; TH0=0xa0; flag1=0; } else { flag1=1; TL0=0; TH0=0x00; p=20-(dengji>>1); } } /*ʼȷͣж*/ void zhongduan1() interrupt 2 using 2 { if(!flag5) { flag5=1; } else { flag5=0; } } void zhongduan() interrupt 0 using 0 { uchar i=0; if(first) //FIRST=1;򿪷򰴼жϱ־ { first=0; k=(P2>>6); k=k&0x03; if(flag) { if(k==1) direction=3;// if(k==2) direction=1;// } else { if(k==0) direction=4;// if(k==3) direction=2;// } } } /*ʾĸСķ*/ void playbuf(uchar buff,char offsetx,char offsety) { //i=(moxing+((dat&0xf0)|((dat&0x0f)<<2))); change1((((*(moxing+((buff&0xf0)+((buff&0x0f)<<2))))&0xf0)>>4)+offsetx,((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))))&0x0f)+offsety); change1((((*((moxing+((buff&0xf0)+((buff&0x0f)<<2))+1)))&0xf0)>>4)+offsetx,((*(((moxing+((buff&0xf0)|((buff&0x0f)<<2))))+1))&0x0f)+offsety); change1((((*(((moxing+((buff&0xf0)|((buff&0x0f)<<2))))+2))&0xf0)>>4)+offsetx,((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+2))&0x0f)+offsety); change1((((*(((moxing+((buff&0xf0)|((buff&0x0f)<<2))))+3))&0xf0)>>4)+offsetx,((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+3))&0x0f)+offsety); } /*жϷֹͣ˶*/ bit tingzhixia(uchar buff,char offsetx,char offsety) { char x0,y0,x1,y1,x2,y2,x3,y3; bit tz=0; x0=(((*(moxing+((buff&0xf0)|((buff&0x0f)<<2))))&0xf0)>>4)+offsetx; x1=(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2))+1)))&0xf0)>>4)+offsetx; x2=(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+2))&0xf0)>>4)+offsetx; x3=(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+3))&0xf0)>>4)+offsetx; y2=((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+2))&0x0f)+offsety; y3=((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+3))&0x0f)+offsety; y0=((*(moxing+((buff&0xf0)|((buff&0x0f)<<2))))&0x0f)+offsety; y1=((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+1))&0x0f)+offsety; if(readfk(x0+1,y0)) { if(!((((x0+1)==x1)&&(y0==y1))|(((x0+1)==x2)&&(y0==y2))|(((x0+1)==x3)&&(y0==y3)))) { tz=1; } } if(readfk(x1+1,y1)) { if(!((((x1+1)==x0)&&(y1==y0))|(((x1+1)==x2)&&(y1==y2))|(((x1+1)==x3)&&(y1==y3)))) { tz=1; } } if(readfk(x2+1,y2)) { if(!((((x2+1)==x0)&&(y2==y0))|(((x2+1)==x1)&&(y2==y1))|(((x2+1)==x3)&&(y2==y3)))) { tz=1; } } if(readfk(x3+1,y3)) { if(!((((x3+1)==x0)&&(y3==y0))|(((x3+1)==x1)&&(y3==y1))|(((x3+1)==x2)&&(y3==y2)))) { tz=1; } } return(tz); } /*жһǷ*/ bit hangman(uchar x) { uchar i; bit man=1; for(i=0;i<15;i++) { man=man&(readfk(x,i)); if(!man) break; } return(man); } /*һ*/ void xiaohang(uchar x) { uchar i,j; for(i=0;i<15;i++) { clear1(x,i); } for(i=1;i<=x;i++) { for(j=0;j<15;j++) { if(readfk(x-i,j)) { change1(x-i+1,j); clear1(x-i,j); } } } } /*жǷֹͣ*/ bit tingzhiyou(uchar buff,char offsetx,char offsety) { char x0,y0,x1,y1,x2,y2,x3,y3; bit tz=0; x0=(((*(moxing+((buff&0xf0)|((buff&0x0f)<<2))))&0xf0)>>4)+offsetx; x1=(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2))+1)))&0xf0)>>4)+offsetx; x2=(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+2))&0xf0)>>4)+offsetx; x3=(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+3))&0xf0)>>4)+offsetx; y2=((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+2))&0x0f)+offsety; y3=((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+3))&0x0f)+offsety; y0=((*(moxing+((buff&0xf0)|((buff&0x0f)<<2))))&0x0f)+offsety; y1=((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+1))&0x0f)+offsety; if(readfk(x0,y0-1)) { if(!(((x0==x1)&&((y0-1)==y1))|((x0==x2)&&((y0-1)==y2))|((x0==x3)&&((y0-1)==y3)))) { tz=1; } } if(readfk(x1,y1-1)) { if(!(((x1==x0)&&((y1-1)==y0))|((x1==x2)&&((y1-1)==y2))|((x1==x3)&&((y1-1)==y3)))) { tz=1; } } if(readfk(x2,y2-1)) { if(!(((x2==x0)&&((y2-1)==y0))|((x2==x1)&&((y2-1)==y1))|((x2==x3)&&((y2-1)==y3)))) { tz=1; } } if(readfk(x3,y3-1)) { if(!(((x3==x0)&&((y3-1)==y0))|((x3==x1)&&((y3-1)==y1))|((x3==x2)&&((y3-1)==y2)))) { tz=1; } } return(tz); } /*жǷֹͣ*/ bit tingzhizuo(uchar buff,char offsetx,char offsety) { char x0,y0,x1,y1,x2,y2,x3,y3; bit tz=0; x0=(((*(moxing+((buff&0xf0)|((buff&0x0f)<<2))))&0xf0)>>4)+offsetx; x1=(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2))+1)))&0xf0)>>4)+offsetx; x2=(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+2))&0xf0)>>4)+offsetx; x3=(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+3))&0xf0)>>4)+offsetx; y2=((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+2))&0x0f)+offsety; y3=((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+3))&0x0f)+offsety; y0=((*(moxing+((buff&0xf0)|((buff&0x0f)<<2))))&0x0f)+offsety; y1=((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+1))&0x0f)+offsety; if(readfk(x0,y0+1)) { if(!(((x0==x1)&&((y0+1)==y1))|((x0==x2)&&((y0+1)==y2))|((x0==x3)&&((y0+1)==y3)))) { tz=1; } } if(readfk(x1,y1+1)) { if(!(((x1==x0)&&((y1+1)==y0))|((x1==x2)&&((y1+1)==y2))|((x1==x3)&&((y1+1)==y3)))) { tz=1; } } if(readfk(x2,y2+1)) { if(!(((x2==x0)&&((y2+1)==y0))|((x2==x1)&&((y2+1)==y1))|((x2==x3)&&((y2+1)==y3)))) { tz=1; } } if(readfk(x3,y3+1)) { if(!(((x3==x0)&&((y3+1)==y0))|((x3==x1)&&((y3+1)==y1))|((x3==x2)&&((y3+1)==y2)))) { tz=1; } } return(tz); } /*һ*/ void clearbuf(uchar dat,char setx,char sety) { uchar *i; i=(moxing+((dat&0xf0)|((dat&0x0f)<<2))); clear1(((((*i)&0xf0)>>4)+setx),(((*i)&0x0f)+sety)); clear1(((((*(i+1))&0xf0)>>4)+setx),(((*(i+1))&0x0f)+sety)); clear1(((((*(i+2))&0xf0)>>4)+setx),(((*(i+2))&0x0f)+sety)); clear1(((((*(i+3))&0xf0)>>4)+setx),(((*(i+3))&0x0f)+sety)); } /*˹ӳ*/ void fangkuai(void) { uchar fenshu=0; char offsety,offsetx; char offsety_buff,offsetx_buff; uchar buff=0x10; bit ting=0; uchar i; //flag5=1; TMOD=1; //ʱʽ IT0=1; //Ч IT1=1; EA=1; //CPUж ET0=1; //ʱж EX0=1; //ⲿж EX1=1; TL0=0x00; TH0=0x00; //ʱֵ TR0=1; //ʱ k=5; choose12864(2); clear12864(); play16(0,0,0,els); play16(0,0,1,els+32); play16(0,0,2,els+64); play16(0,2,0,els+96); play16(0,2,1,els+128); play8(0,0,3,shu0); play8(0,1,3,shu0); vertical(1,60,30); vertical(1,60,127); for(i=0;i<98;i++) { dot(30+i,1); dot(30+i,62); } offsety=7; offsetx=-3; for(;;) { if(P3&0x04) first=1; if((k==0x02)&&((P3&0x04)==0x04)) { offsety_buff=offsety; ting=tingzhiyou(buff,offsetx,offsety); if(!ting) { if(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+2))&0x0f)+offsety) offsety--; clearbuf(buff,offsetx_buff,offsety_buff); playbuf(buff,offsetx,offsety); offsety_buff=offsety; } k=5; } if((k==0x01)&&((P3&0x04)==0x04)) { offsety_buff=offsety; ting=tingzhizuo(buff,offsetx,offsety); if(!ting) { if(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+3))&0x0f)+offsety<=13) offsety++; k=5; clearbuf(buff,offsetx_buff,offsety_buff); playbuf(buff,offsetx,offsety); offsety_buff=offsety; } } if((k==0x03)&&((P3&0x04)==0x04)) { dengji=36;///////////// k=5; } if((k==0x00)&&((P3&0x04)==0x04)) { uchar i; k=5; i=buff; buff++; if((buff&0x0f)>=4) buff=buff&0xf0; //change1(0,14); if(((*(((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+3))&0x0f)+offsety)>14) { do { offsety--; }while((((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+3))&0x0f)+offsety)>14); } if(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+2))&0x0f)+offsety<0) { do { offsety++; }while(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+2))&0x0f)+offsety); } clearbuf(i,offsetx_buff,offsety_buff); playbuf(buff,offsetx,offsety); } ting=tingzhixia(buff,offsetx,offsety); while(flag5); if(flag1) { offsetx_buff=offsetx; offsety_buff=offsety; offsetx++; clearbuf(buff,offsetx_buff,offsety_buff); playbuf(buff,offsetx,offsety); offsetx_buff=offsetx; flag1=0; } if((((((*((moxing+((buff&0xf0)+((buff&0x0f)<<2))+1)))&0xf0)>>4)+offsetx)>22)|ting) { uchar i=0; if(hangman((((*((moxing+((buff&0xf0)+((buff&0x0f)<<2))+1)))&0xf0)>>4)+offsetx)) {xiaohang((((*((moxing+((buff&0xf0)+((buff&0x0f)<<2))+1)))&0xf0)>>4)+offsetx);fenshu++;i++;} if((((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+2))&0xf0)>>4)+offsetx>=(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+3))&0xf0)>>4)+offsetx) //x2>=x3 { if((((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+2))&0xf0)>>4)+offsetx<(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2))+1)))&0xf0)>>4)+offsetx) //x2<x1 { if(hangman((((*((moxing+((buff&0xf0)+((buff&0x0f)<<2))+2)))&0xf0)>>4)+offsetx+i)) {xiaohang((((*((moxing+((buff&0xf0)+((buff&0x0f)<<2))+2)))&0xf0)>>4)+offsetx+i);fenshu++;i++;} } if((((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+3))&0xf0)>>4)+offsetx<(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+2))&0xf0)>>4)+offsetx) //x3<x2 { if(hangman((((*((moxing+((buff&0xf0)+((buff&0x0f)<<2))+3)))&0xf0)>>4)+offsetx+i)) {xiaohang((((*((moxing+((buff&0xf0)+((buff&0x0f)<<2))+3)))&0xf0)>>4)+offsetx+i);fenshu++;i++;} } if((((*(moxing+((buff&0xf0)|((buff&0x0f)<<2))))&0xf0)>>4)+offsetx<(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+3))&0xf0)>>4)+offsetx) //x0<x3 { if(hangman((((*(moxing+((buff&0xf0)+((buff&0x0f)<<2))))&0xf0)>>4)+offsetx+i)) {xiaohang((((*(moxing+((buff&0xf0)+((buff&0x0f)<<2))))&0xf0)>>4)+offsetx+i);fenshu++;i++;} } } if((((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+2))&0xf0)>>4)+offsetx<(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+3))&0xf0)>>4)+offsetx) //x2<x3 { if((((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+3))&0xf0)>>4)+offsetx<(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2))+1)))&0xf0)>>4)+offsetx) { if(hangman((((*((moxing+((buff&0xf0)+((buff&0x0f)<<2))+3)))&0xf0)>>4)+offsetx+i)) {xiaohang((((*((moxing+((buff&0xf0)+((buff&0x0f)<<2))+3)))&0xf0)>>4)+offsetx+i);fenshu++;i++;} } if(hangman((((*((moxing+((buff&0xf0)+((buff&0x0f)<<2))+2)))&0xf0)>>4)+offsetx+i)) {xiaohang((((*((moxing+((buff&0xf0)+((buff&0x0f)<<2))+2)))&0xf0)>>4)+offsetx+i);fenshu++;i++;} if((((*(moxing+((buff&0xf0)|((buff&0x0f)<<2))))&0xf0)>>4)+offsetx<(((*((moxing+((buff&0xf0)|((buff&0x0f)<<2)))+2))&0xf0)>>4)+offsetx) { if(hangman((((*(moxing+((buff&0xf0)+((buff&0x0f)<<2))))&0xf0)>>4)+offsetx+i)) {xiaohang((((*(moxing+((buff&0xf0)+((buff&0x0f)<<2))))&0xf0)>>4)+offsetx+i);fenshu++;i++;} } } play8(0,0,3,shu0+((fenshu/10)<<4)); play8(0,1,3,shu0+((fenshu%10)<<4)); dengji=fenshu/5; if(((((*(moxing+((buff&0xf0)+((buff&0x0f)<<2))))&0xf0)>>4)+offsetx)<1) { delay1ms(450); delay1ms(450); choose12864(2); clear12864(); play16(0,4,1,over); play16(0,6,1,over+32); play16(1,0,1,over+64); play16(1,2,1,over+96); delay1ms(450); delay1ms(450); break; } buff=(((TL0%7)<<4)|(TH0%4)); //buff=0x11; offsety=7; offsetx=-3; offsetx_buff=-9; offsety_buff=-9; } } } /*ӳ*/ void wannianli(void) { uchar i; uchar count1=0; k=0; choose12864(2); init12864(); clear12864(); play8(0,0,0,shu2); //Уҳַ play8(0,1,0,shu0); play16(0,4,0,nian); play16(1,0,0,yue); play16(1,4,0,ri); play16(0,2,1,shi); play16(0,6,1,fen); play16(1,2,1,miao); play16(1,0,2,xing); play16(1,2,2,qi); vertical(3,63,127); vertical(3,63,126); vertical(3,63,122); vertical(3,63,121); for(i=0;i<7;i++) { dot(121+i,3); dot(121+i,63); } for(i=0;i<12;i++) { dot(123,8+5*i); } for(i=0;i<7;i++) { if(i<4) { play16(0,i<<1,3,yanyu+(i<<5)); } if(i>=4) { play16(1,(i-4)<<1,3,yanyu+(i<<5)); } } init_ds1302(); init_time(); flag5=0; do { if(P3&0x04) first=1; init_ds1302(); gettime(&realtime); play8(0,2,0,(shu0+(datastring[0]<<4))); play8(0,3,0,(shu0+(datastring[1]<<4))); play8(0,6,0,(shu0+(datastring[2]<<4))); play8(0,7,0,(shu0+(datastring[3]<<4))); play8(1,2,0,(shu0+(datastring[4]<<4))); play8(1,3,0,(shu0+(datastring[5]<<4))); play8(0,0,1,(shu0+(datastring[6]<<4))); play8(0,1,1,(shu0+(datastring[7]<<4))); play8(0,4,1,(shu0+(datastring[8]<<4))); play8(0,5,1,(shu0+(datastring[9]<<4))); play8(1,0,1,(shu0+(datastring[10]<<4))); play8(1,1,1,(shu0+(datastring[11]<<4))); play16(1,4,2,(yi+((datastring[12]-2)<<5))); gettemperature(); if(flagg) { play8(0,0,2,fu); play8(1,6,3,fu); } else { clear8(6,4,0); play8(1,6,3,zheng); } play8(0,4+flagg,2,dian); play8(0,5+flagg,2,C); play8(0,0+flagg,2,(shu0+(temp[0]<<4))); play8(0,1+flagg,2,(shu0+(temp[1]<<4))); play8(0,2+flagg,2,xiao); play8(0,3+flagg,2,(shu0+(temp[2]<<4))); play(); dot(124,3); if((k==0x02)&&((P3&0x04)==0x04)) { count1++; if(count1==7) count1=0; switch (count1) { case 0: { play16(1,0,2,xing); play16(1,2,2,qi); k=0;break; } case 1: { play16_fb(0,4,0); k=0; break; } case 2: { play16(0,4,0,nian); play16_fb(1,0,0); k=0;break; } case 3: { play16(1,0,0,yue); play16_fb(1,4,0); k=0;break; } case 4: { play16(1,4,0,ri); play16_fb(0,2,1); k=0;break; } case 5: { play16(0,2,1,shi); play16_fb(0,6,1); k=0;break; } case 6: { play16(0,6,1,fen); play16_fb(1,0,2); play16_fb(1,2,2); k=0;break; } default:k=0;break; } } if((k==0x03)&&((P3&0x04)==0x04)) { switch(count1) { case 1: { setjia(ds1302_year);k=0;break; } case 2: { setjia(ds1302_month);k=0;break; } case 3: { setjia(ds1302_day);k=0;break; } case 4: { setjia(ds1302_hour);k=0;break; } case 5: { setjia(ds1302_minute);k=0;break; } case 6: { setjia(ds1302_week);k=0;break; } } } if((k==0x01)&&((P3&0x04)==0x04)) { switch(count1) { case 1: { setjian(ds1302_year);k=0;break; } case 2: { setjian(ds1302_month);k=0;break; } case 3: { setjian(ds1302_day);k=0;break; } case 4: { setjian(ds1302_hour);k=0;break; } case 5: { setjian(ds1302_minute);k=0;break; } case 6: { setjian(ds1302_week);k=0;break; } } } } while(!flag5); } /*̰ӳ*/ void tanchishe(void) { uchar xdata length[102]={0,8,1,8}; //; uchar food[2]={12,8}; uchar i,x,y; bit flag2,flag3,flag4; TMOD=1; //ʱʽ IT0=1; //Ч IT1=1; EA=1; //CPUж ET0=1; //ʱж EX0=1; //ⲿж EX1=1; TL0=0x00; TH0=0x00; //ʱֵ TR0=1; //ʱ dengji=2; p=20; direction=1; flag5=0; choose12864(2); clear12864(); vertical(1,61,30); vertical(1,61,127); for(i=0;i<98;i++) { dot(30+i,1); dot(30+i,62); } play16(0,0,0,tan); play16(0,0,1,chi); play16(0,0,2,she); change(length,(length+1)); change((length+2),(length+3)); change(food,food+1); for(;;) { do { first=1; while(flag5|!flag1); x=*(length); y=*(length+1); switch(direction) // { case 1: { for(i=0;i<dengji-1;i++) { *(length+(i<<1))=*(length+(i<<1)+2); *(length+(i<<1)+1)=*(length+(i<<1)+3); } (*(length+(dengji<<1)-2))++; flag=0; break; } case 2: // { for(i=0;i<dengji-1;i++) { *(length+(i<<1))=*(length+(i<<1)+2); *(length+(i<<1)+1)=*(length+(i<<1)+3); } (*(length+(dengji<<1)-1))++; flag=1; break; } case 3: // { for(i=0;i<dengji-1;i++) { *(length+(i<<1))=*(length+(i<<1)+2); *(length+(i<<1)+1)=*(length+(i<<1)+3); } (*(length+(dengji<<1)-2))--; flag=0; break; } case 4: { // for(i=0;i<dengji-1;i++) { *(length+(i<<1))=*(length+(i<<1)+2); *(length+(i<<1)+1)=*(length+(i<<1)+3); } (*(length+(dengji<<1)-1))--; flag=1; break; } } flag4=((*(length+(dengji<<1)-2))==food[0])&&((*(length+(dengji<<1)-1))==food[1]); if(flag4) // { for(i=dengji;i>0;i--) { *(length+(i<<1))=*(length+(i<<1)-2); *(length+(i<<1)+1)=*(length+(i<<1)-1); } *length=x; *(length+1)=y; dengji++; do { flag3=0; food[0]=TL0%24; food[1]=TL0%15; for(i=0;i<dengji-1;i++) //ʳǷ { if((*(length+(i<<1)))==food[0]&&((*(length+(i<<1)+1))==food[1])) { flag3=1; break; } } }while(flag3); change(food,food+1); } flag2=1; //ͷû for(i=0;i<dengji-1;i++) { if(*(length+(i<<1))==*(length+(dengji<<1)-2)&&(*(length+(i<<1)+1)==*(length+(dengji<<1)-1))) { flag2=0; break; } } flag2=flag2&&*(length+(dengji<<1)-2)>=0&&*(length+(dengji<<1)-2)<24;//ͷǷ߽ flag2=flag2&&*(length+(dengji<<1)-1)>=0&&*(length+(dengji<<1)-1)<15; if(flag2) { clear(&x,&y); { change(length+(dengji<<1)-2,length+(dengji<<1)-1); } if(flag4) { change(&x,&y); } flag1=0; play8(0,0,3,shu0+((dengji/10)<<4)); play8(0,1,3,shu0+(((dengji)%10)<<4)); } } while(flag2); delay1ms(450); delay1ms(450); choose12864(2); clear12864(); play16(0,4,1,over); play16(0,6,1,over+32); play16(1,0,1,over+64); play16(1,2,1,over+96); delay1ms(450); delay1ms(450); break; } } ////////////////////////////// main(void) { uchar i; uchar count=0; P2=0xff; EA=1; //CPUж //ET0=1; //ʱж EX0=1; //ⲿж EX1=1; choose12864(2); init12864(); clear12864(); //////////////////// play16(0,4,0,tan); play16(0,6,0,chi); play16(1,0,0,she); /////////////////// play16(0,4,1,els); play16(0,6,1,els+32); for(i=0;i<3;i++) { play16(1,i<<1,1,(els+64+(i<<5))); } ////////////////// play16(0,4,2,wnl); play16(0,6,2,wnl+32); play16(1,0,2,wnl+64); ////////////////// for(;;) { if((k==0x03)&&((P3&0x04)==0x04)) { count++; k=0; if(count==4) count=1; switch(count) { case 1: { play16(0,4,2,wnl); play16(0,6,2,wnl+32); play16(1,0,2,wnl+64); play16_fb(0,4,0); play16_fb(0,6,0); play16_fb(1,0,0); };break; case 2: { play16(0,4,0,tan); play16(0,6,0,chi); play16(1,0,0,she); play16_fb(0,4,1); play16_fb(0,6,1); for(i=0;i<3;i++) { play16_fb(1,i<<1,1); } };break; case 3: { play16(0,4,1,els); play16(0,6,1,els+32); for(i=0;i<3;i++) { play16(1,i<<1,1,(els+64+(i<<5))); } play16_fb(0,4,2); play16_fb(0,6,2); play16_fb(1,0,2); };break; default:break; } } if(P3&0x04) first=1; if(flag5) { switch(count) { case 1:flag5=0;tanchishe();count=0;flag5=0;k=0;break; case 2:flag5=0;fangkuai();count=0;flag5=0; k=0;break; case 3:flag5=0;wannianli();count=0;flag5=0;k=0;break; default:count=0;k=3;flag5=0;break; } choose12864(2); init12864(); clear12864(); //////////////////// play16(0,4,0,tan); play16(0,6,0,chi); play16(1,0,0,she); /////////////////// play16(0,4,1,els); play16(0,6,1,els+32); for(i=0;i<3;i++) { play16(1,i<<1,1,(els+64+(i<<5))); } ////////////////// play16(0,4,2,wnl); play16(0,6,2,wnl+32); play16(1,0,2,wnl+64); ////////////////// } } }
412
0.797779
1
0.797779
game-dev
MEDIA
0.310092
game-dev
0.902525
1
0.902525
SapphireServer/Sapphire
10,898
src/scripts/quest/subquest/blackshroud_central/SubFst033.cpp
// This is an automatically generated C++ script template // Content needs to be added by hand to make it function // In order for this script to be loaded, move it to the correct folder in <root>/scripts/ #include "Manager/EventMgr.h" #include <Actor/Player.h> #include <ScriptObject.h> #include <Service.h> #include "Actor/BNpc.h" #include "Manager/TerritoryMgr.h" #include "Territory/Territory.h" // Quest Script: SubFst033_00127 // Quest Name: Parasite Cleave // Quest ID: 65663 // Start NPC: 1000461 // End NPC: 1000461 using namespace Sapphire; class SubFst033 : public Sapphire::ScriptAPI::QuestScript { private: // Basic quest information // Quest vars / flags used // BitFlag8 // UI8AH // UI8AL // UI8BH // UI8BL // UI8CH // UI8CL // UI8DH // UI8DL /// Countable Num: 3 Seq: 1 Event: 1 Listener: 2000016 /// Countable Num: 1 Seq: 255 Event: 8 Listener: 2000016 // Steps in this quest ( 0 is before accepting, // 1 is first, 255 means ready for turning it in enum Sequence : uint8_t { Seq0 = 0, Seq1 = 1, SeqFinish = 255, }; // Entities found in the script data of the quest static constexpr auto Actor0 = 1000461;//Gabineaux static constexpr auto Enemy0 = 2114368; static constexpr auto Enemy1 = 2114369; static constexpr auto Enemy2 = 2114370; static constexpr auto Eobject0 = 2000016;//Decaying Tree (West) static constexpr auto Eobject1 = 2000017;//Decaying Tree (South) static constexpr auto Eobject2 = 2000018;//Decaying Tree (East) static constexpr auto Item0 = 2000061; static constexpr auto Item0Icon = 20661; static constexpr auto Seq0Actor0 = 0; static constexpr auto Seq1Eobject0 = 1; static constexpr auto Seq1Eobject0Useitemno = 99; static constexpr auto Seq1Eobject0Useitemok = 100; static constexpr auto Seq1Eobject1 = 2; static constexpr auto Seq1Eobject1Useitemno = 97; static constexpr auto Seq1Eobject1Useitemok = 98; static constexpr auto Seq1Eobject2 = 3; static constexpr auto Seq1Eobject2Useitemno = 95; static constexpr auto Seq1Eobject2Useitemok = 96; static constexpr auto Seq2Actor0 = 4; public: SubFst033() : Sapphire::ScriptAPI::QuestScript( 65663 ){}; ~SubFst033() = default; ////////////////////////////////////////////////////////////////////// // Event Handlers void onTalk( World::Quest& quest, Entity::Player& player, uint64_t actorId ) override { switch( actorId ) { case Actor0: { if( quest.getSeq() == Seq0 ) Scene00000( quest, player ); else if( quest.getSeq() == SeqFinish ) Scene00004( quest, player ); break; } case Eobject0: { if( quest.getSeq() == Seq1 ) Scene00001( quest, player ); break; } case Eobject1: { if( quest.getSeq() == Seq1 ) Scene00002( quest, player ); break; } case Eobject2: { if( quest.getSeq() == Seq1 ) Scene00003( quest, player ); break; } } } void onEventItem(World::Quest& quest, Entity::Player& player, uint64_t actorId) override { if( quest.getSeq() != Seq1 ) return; switch( actorId ) { case Eobject0: { Scene00100( quest, player ); break; } case Eobject1: { Scene00098( quest, player ); break; } case Eobject2: { Scene00096( quest, player ); break; } } } void onBNpcKill( World::Quest& quest, Sapphire::Entity::BNpc& bnpc, Sapphire::Entity::Player& player ) override { switch( bnpc.getLayoutId() ) { case Enemy0: { quest.setUI8AH( quest.getUI8AH() + 1 ); quest.setUI8AL( 1 ); checkQuestCompletion( quest, player ); break; } case Enemy1: { quest.setUI8AH( quest.getUI8AH() + 1 ); quest.setUI8BL( 1 ); checkQuestCompletion( quest, player ); break; } case Enemy2: { quest.setUI8AH( quest.getUI8AH() + 1 ); quest.setUI8CL( 1 ); checkQuestCompletion( quest, player ); break; } } } void onPlayerDeath(World::Quest& quest, Sapphire::Entity::Player& player) override { auto instance = teriMgr().getTerritoryByGuId( player.getTerritoryId() ); auto enem0 = instance->getActiveBNpcByLayoutIdAndTriggerOwner( Enemy0, player.getId() ); auto enem1 = instance->getActiveBNpcByLayoutIdAndTriggerOwner( Enemy1, player.getId() ); auto enem2 = instance->getActiveBNpcByLayoutIdAndTriggerOwner( Enemy2, player.getId() ); if (enem0 != nullptr) { instance->removeActor( enem0 ); quest.setBitFlag8( 1, false ); } if( enem1 != nullptr ) { instance->removeActor( enem1 ); quest.setBitFlag8( 2, false ); } if( enem2 != nullptr ) { instance->removeActor( enem2 ); quest.setBitFlag8( 3, false ); } } private: void checkQuestCompletion( World::Quest& quest, Entity::Player& player ) { eventMgr().sendNotice( player, getId(), 0, { quest.getUI8AH(), 3, Item0Icon } ); if( quest.getUI8AH() >= 3 ) { quest.setSeq( SeqFinish ); quest.setUI8AH( 0 ); quest.setUI8AL( 0 ); quest.setUI8BH( 0 ); quest.setUI8BL( 0 ); quest.setUI8CH( 0 ); quest.setUI8CL( 0 ); quest.setUI8DH( 0 ); quest.setBitFlag8( 1, false ); quest.setBitFlag8( 2, false ); quest.setBitFlag8( 3, false ); } } ////////////////////////////////////////////////////////////////////// // Available Scenes in this quest, not necessarly all are used ////////////////////////////////////////////////////////////////////// void Scene00000( World::Quest& quest, Entity::Player& player ) { eventMgr().playQuestScene( player, getId(), 0, NONE, bindSceneReturn( &SubFst033::Scene00000Return ) ); } void Scene00000Return( World::Quest& quest, Entity::Player& player, const Event::SceneResult& result ) { if( result.getResult( 0 ) == 1 )// accept quest { quest.setUI8DL( 1 ); quest.setSeq( Seq1 ); } } ////////////////////////////////////////////////////////////////////// void Scene00001( World::Quest& quest, Entity::Player& player ) { eventMgr().playQuestScene( player, getId(), 1, NONE, bindSceneReturn( &SubFst033::Scene00001Return ) ); } void Scene00001Return( World::Quest& quest, Entity::Player& player, const Event::SceneResult& result ) { } ////////////////////////////////////////////////////////////////////// void Scene00002( World::Quest& quest, Entity::Player& player ) { eventMgr().playQuestScene( player, getId(), 2, NONE, bindSceneReturn( &SubFst033::Scene00002Return ) ); } void Scene00002Return( World::Quest& quest, Entity::Player& player, const Event::SceneResult& result ) { } ////////////////////////////////////////////////////////////////////// void Scene00003( World::Quest& quest, Entity::Player& player ) { eventMgr().playQuestScene( player, getId(), 3, NONE, bindSceneReturn( &SubFst033::Scene00003Return ) ); } void Scene00003Return( World::Quest& quest, Entity::Player& player, const Event::SceneResult& result ) { } ////////////////////////////////////////////////////////////////////// void Scene00004( World::Quest& quest, Entity::Player& player ) { eventMgr().playQuestScene( player, getId(), 4, NONE, bindSceneReturn( &SubFst033::Scene00004Return ) ); } void Scene00004Return( World::Quest& quest, Entity::Player& player, const Event::SceneResult& result ) { if( result.getResult( 0 ) == 1 ) { player.finishQuest( getId(), result.getResult(1) ); } } ////////////////////////////////////////////////////////////////////// void Scene00095( World::Quest& quest, Entity::Player& player ) { eventMgr().playQuestScene( player, getId(), 95, NONE, bindSceneReturn( &SubFst033::Scene00095Return ) ); } void Scene00095Return( World::Quest& quest, Entity::Player& player, const Event::SceneResult& result ) { } ////////////////////////////////////////////////////////////////////// void Scene00096( World::Quest& quest, Entity::Player& player ) { eventMgr().playQuestScene( player, getId(), 96, NONE, bindSceneReturn( &SubFst033::Scene00096Return ) ); } void Scene00096Return( World::Quest& quest, Entity::Player& player, const Event::SceneResult& result ) { auto instance = teriMgr().getTerritoryByGuId( player.getTerritoryId() ); auto enemy = instance->createBNpcFromLayoutId( Enemy2, 1220 /*Find the right value*/, Common::BNpcType::Enemy, player.getId() ); enemy->hateListAddDelayed( player.getAsPlayer(), 1 ); quest.setBitFlag8( 3, true ); } ////////////////////////////////////////////////////////////////////// void Scene00097( World::Quest& quest, Entity::Player& player ) { eventMgr().playQuestScene( player, getId(), 97, NONE, bindSceneReturn( &SubFst033::Scene00097Return ) ); } void Scene00097Return( World::Quest& quest, Entity::Player& player, const Event::SceneResult& result ) { } ////////////////////////////////////////////////////////////////////// void Scene00098( World::Quest& quest, Entity::Player& player ) { eventMgr().playQuestScene( player, getId(), 98, NONE, bindSceneReturn( &SubFst033::Scene00098Return ) ); } void Scene00098Return( World::Quest& quest, Entity::Player& player, const Event::SceneResult& result ) { auto instance = teriMgr().getTerritoryByGuId( player.getTerritoryId() ); auto enemy = instance->createBNpcFromLayoutId( Enemy1, 1220 /*Find the right value*/, Common::BNpcType::Enemy, player.getId() ); enemy->hateListAddDelayed( player.getAsPlayer(), 1 ); quest.setBitFlag8( 2, true ); } ////////////////////////////////////////////////////////////////////// void Scene00099( World::Quest& quest, Entity::Player& player ) { eventMgr().playQuestScene( player, getId(), 99, NONE, bindSceneReturn( &SubFst033::Scene00099Return ) ); } void Scene00099Return( World::Quest& quest, Entity::Player& player, const Event::SceneResult& result ) { } ////////////////////////////////////////////////////////////////////// void Scene00100( World::Quest& quest, Entity::Player& player ) { eventMgr().playQuestScene( player, getId(), 100, NONE, bindSceneReturn( &SubFst033::Scene00100Return ) ); } void Scene00100Return( World::Quest& quest, Entity::Player& player, const Event::SceneResult& result ) { auto instance = teriMgr().getTerritoryByGuId( player.getTerritoryId() ); auto enemy = instance->createBNpcFromLayoutId( Enemy0, 1220 /*Find the right value*/, Common::BNpcType::Enemy, player.getId() ); enemy->hateListAddDelayed( player.getAsPlayer(), 1 ); quest.setBitFlag8( 1, true ); } }; EXPOSE_SCRIPT( SubFst033 );
412
0.925243
1
0.925243
game-dev
MEDIA
0.993965
game-dev
0.915893
1
0.915893
Demigiant/dotween
1,308
UnityTests.Unity4/Assets/_Tests/Shortcuts.cs
using DG.Tweening; using UnityEngine; public class Shortcuts : MonoBehaviour { public GameObject prefab; void Start() { //////////////////////////////////////////// // Transform shortcuts ///////////////////// // Position NewTransform().DOMove(RandomVector3(), 1).SetLoops(-1, LoopType.Yoyo); // X Position NewTransform().DOMoveX(Random.Range(-10f, 10f), 1).SetLoops(-1, LoopType.Yoyo); // Local position NewTransform().DOLocalMove(RandomVector3(), 1).SetLoops(-1, LoopType.Yoyo); // Rotation NewTransform().DORotate(RandomVector3(720), 1).SetLoops(-1, LoopType.Yoyo); // Local rotation NewTransform().DOLocalRotate(RandomVector3(720), 1).SetLoops(-1, LoopType.Yoyo); // Scale NewTransform().DOScale(RandomVector3(3), 1).SetLoops(-1, LoopType.Yoyo); // Color NewTransform().renderer.material.DOColor(Color.green, 1).SetLoops(-1, LoopType.Yoyo); // Alpha NewTransform().renderer.material.DOFade(0, 1).SetLoops(-1, LoopType.Yoyo); } Transform NewTransform(bool randomPos = true) { Transform t = ((GameObject)Instantiate(prefab)).transform; if (randomPos) t.position = RandomVector3(); return t; } Vector3 RandomVector3(float limit = 10f) { return new Vector3(Random.Range(-limit, limit), Random.Range(-limit, limit), Random.Range(-limit, limit)); } }
412
0.6323
1
0.6323
game-dev
MEDIA
0.669579
game-dev
0.965907
1
0.965907
lzk228/space-axolotl-14
3,621
Content.Client/Actions/UI/ActionAlertTooltip.cs
using Content.Client.Stylesheets; using Robust.Client.UserInterface.Controls; using Robust.Shared.Timing; using Robust.Shared.Utility; using static Robust.Client.UserInterface.Controls.BoxContainer; namespace Content.Client.Actions.UI { /// <summary> /// Tooltip for actions or alerts because they are very similar. /// </summary> public sealed class ActionAlertTooltip : PanelContainer { private const float TooltipTextMaxWidth = 350; private readonly RichTextLabel _cooldownLabel; private readonly IGameTiming _gameTiming; /// <summary> /// Current cooldown displayed in this tooltip. Set to null to show no cooldown. /// </summary> public (TimeSpan Start, TimeSpan End)? Cooldown { get; set; } public ActionAlertTooltip(FormattedMessage name, FormattedMessage? desc, string? requires = null) { _gameTiming = IoCManager.Resolve<IGameTiming>(); SetOnlyStyleClass(StyleNano.StyleClassTooltipPanel); BoxContainer vbox; AddChild(vbox = new BoxContainer { Orientation = LayoutOrientation.Vertical, RectClipContent = true }); var nameLabel = new RichTextLabel { MaxWidth = TooltipTextMaxWidth, StyleClasses = {StyleNano.StyleClassTooltipActionTitle} }; nameLabel.SetMessage(name); vbox.AddChild(nameLabel); if (desc != null && !string.IsNullOrWhiteSpace(desc.ToString())) { var description = new RichTextLabel { MaxWidth = TooltipTextMaxWidth, StyleClasses = {StyleNano.StyleClassTooltipActionDescription} }; description.SetMessage(desc); vbox.AddChild(description); } vbox.AddChild(_cooldownLabel = new RichTextLabel { MaxWidth = TooltipTextMaxWidth, StyleClasses = {StyleNano.StyleClassTooltipActionCooldown}, Visible = false }); if (!string.IsNullOrWhiteSpace(requires)) { var requiresLabel = new RichTextLabel { MaxWidth = TooltipTextMaxWidth, StyleClasses = {StyleNano.StyleClassTooltipActionRequirements} }; if (!FormattedMessage.TryFromMarkup("[color=#635c5c]" + requires + "[/color]", out var markup)) return; requiresLabel.SetMessage(markup); vbox.AddChild(requiresLabel); } } protected override void FrameUpdate(FrameEventArgs args) { base.FrameUpdate(args); if (!Cooldown.HasValue) { _cooldownLabel.Visible = false; return; } var timeLeft = Cooldown.Value.End - _gameTiming.CurTime; if (timeLeft > TimeSpan.Zero) { var duration = Cooldown.Value.End - Cooldown.Value.Start; if (!FormattedMessage.TryFromMarkup(Loc.GetString("ui-actionslot-duration", ("duration", (int)duration.TotalSeconds), ("timeLeft", (int)timeLeft.TotalSeconds + 1)), out var markup)) return; _cooldownLabel.SetMessage(markup); _cooldownLabel.Visible = true; } else { _cooldownLabel.Visible = false; } } } }
412
0.896645
1
0.896645
game-dev
MEDIA
0.640322
game-dev,desktop-app
0.981521
1
0.981521
microsoft/vsminecraft
1,058
minecraftpkg/MekanismModSample/src/main/java/mekanism/api/TabProxy.java
package mekanism.api; import net.minecraft.creativetab.CreativeTabs; /** * Class used to indirectly reference the Mekanism creative tab. * @author AidanBrady * */ public final class TabProxy { /** The 'Mekanism' class where the tab instance is stored. */ public static Class Mekanism; /** * Attempts to get the Mekanism creative tab instance from the 'Mekanism' class. Will return * the tab if the mod is loaded, but otherwise will return the defined 'preferred' creative tab. This way * you don't need to worry about NPEs! * @return Mekanism creative tab if can, otherwise preferred tab */ public static CreativeTabs tabMekanism(CreativeTabs preferred) { try { if(Mekanism == null) { Mekanism = Class.forName("mekanism.common.Mekanism"); } Object ret = Mekanism.getField("tabMekanism").get(null); if(ret instanceof CreativeTabs) { return (CreativeTabs)ret; } return preferred; } catch(Exception e) { System.err.println("Error retrieving Mekanism creative tab."); return preferred; } } }
412
0.79833
1
0.79833
game-dev
MEDIA
0.655888
game-dev
0.535412
1
0.535412
ismail0234/Subnautica-Below-Zero-Multiplayer
2,237
Subnautica.Client/Synchronizations/InitialSync/CustomDoorways.cs
namespace Subnautica.Client.Synchronizations.InitialSync { using System.Collections; using Subnautica.API.Extensions; using Subnautica.API.Features; using Subnautica.Network.Models.Storage.Story.Components; using UWE; public class CustomDoorways { /** * * Geçidin sınıf idsini barındırır. * * @author Ismail <ismaiil_0234@hotmail.com> * */ private const string DoorwayClassId = "d9d5c46d-32ab-492f-af43-830d72656dcf"; /** * * Kapıları başlatır. * * @author Ismail <ismaiil_0234@hotmail.com> * */ public static IEnumerator OnDoorwaysInitialized() { if (Network.Session.Current != null) { foreach (var door in Network.Session.Current.Story.CustomDoorways) { if (door.IsActive) { yield return SpawnDoorway(door); } } } } /** * * Kapıları yumurtlar. * * @author Ismail <ismaiil_0234@hotmail.com> * */ private static IEnumerator SpawnDoorway(CustomDoorwayComponent door) { var request = PrefabDatabase.GetPrefabAsync(DoorwayClassId); yield return request; if (request.TryGetPrefab(out var prefab)) { var gameObject = global::Utils.SpawnFromPrefab(prefab, null); if (gameObject) { Network.Identifier.SetIdentityId(gameObject, door.UniqueId); gameObject.transform.position = door.Position.ToVector3(); gameObject.transform.rotation = door.Rotation.ToQuaternion(); gameObject.transform.localScale = door.Scale.ToVector3(); yield return CoroutineUtils.waitForNextFrame; if (gameObject.TryGetComponent<PrecursorDoorway>(out var component)) { component.EnableField(); } } } } } }
412
0.594266
1
0.594266
game-dev
MEDIA
0.898635
game-dev
0.808309
1
0.808309
jval1972/DelphiDoom
14,038
SCRIPT/ps_events.pas
//------------------------------------------------------------------------------ // // DelphiDoom is a source port of the game Doom and it is // based on original Linux Doom as published by "id Software" // Copyright (C) 1993-1996 by id Software, Inc. // Copyright (C) 2004-2022 by Jim Valavanis // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. // // DESCRIPTION: // Pascal Script Events // //------------------------------------------------------------------------------ // Site : https://sourceforge.net/projects/delphidoom/ //------------------------------------------------------------------------------ {$I Doom32.inc} unit ps_events; interface uses ps_import, ps_compiler, ps_utils; const EventExportedProcs: array [0..9] of record Name: AnsiString; ParamCount: Byte; Typ: array [0..4] of Byte; Dir: array [0..3] of TPSParameterMode; {$IFDEF DLL} Template: AnsiString; {$ENDIF} end = // Must be in sync with TScriptEvents ( ( Name: 'ONACTORDIED'; ParamCount: 2; Typ: (0, btU32, btU32, 0, 0 ); Dir: (pmIn, pmIn, pmIn, pmIn){$IFDEF DLL}; Template: 'event OnActorDied(const actorKEY: LongWord; const killer: LongWord);|' + 'begin|' + '// Executes every time an actor dies, before dropping the dropitem|' + ' |' + 'end;||'{$ENDIF} ), ( Name: 'ONPLAYERENTER'; ParamCount: 1; Typ: (0, btS32, 0, 0, 0 ); Dir: (pmIn, pmIn, pmIn, pmIn){$IFDEF DLL}; Template: 'event OnPlayerEnter(const playerNO: integer);|' + 'begin|' + '// Executes the first time a player spawns to the map, just after OnMapStart Event|' + ' |' + 'end;||'{$ENDIF} ), ( Name: 'ONPLAYERDIED'; ParamCount: 2; Typ: (0, btS32, btU32, 0, 0 ); Dir: (pmIn, pmIn, pmIn, pmIn){$IFDEF DLL}; Template: 'event OnPlayerDied(const playerNO: integer; const killer: LongWord);|' + 'begin|' + '// Executes every time a player dies, before OnActorDied event|' + ' |' + 'end;||'{$ENDIF} ), ( Name: 'ONCROSSLINE'; ParamCount: 3; Typ: (0, btU32, btS32, btS32, 0 ); Dir: (pmIn, pmIn, pmIn, pmIn){$IFDEF DLL}; Template: 'event OnCrossLine(const actorKEY: LongWord; const lineNO: Integer;|' + ' const oldside: Integer);|' + 'begin|' + '// Executes when the actor "actorKEY" crosses the line "lineNO"|' + '// line must have the "Trigger PascalScript" setting enabled|' + '// actor must not have the MF2_EX_DONTRUNSCRIPTS flag|' + ' |' + 'end;||'{$ENDIF} ), ( Name: 'ONSHOOTLINE'; ParamCount: 3; Typ: (0, btU32, btS32, btS32, 0 ); Dir: (pmIn, pmIn, pmIn, pmIn){$IFDEF DLL}; Template: 'event OnShootLine(const actorKEY: LongWord; const lineNO: Integer;|' + ' const side: Integer);|' + 'begin|' + '// Executes when the actor "actorKEY" shoots the line "lineNO"|' + '// line must have the "Trigger PascalScript" setting enabled|' + '// actor must not have the MF2_EX_DONTRUNSCRIPTS flag|' + ' |' + 'end;||'{$ENDIF} ), ( Name: 'ONUSELINE'; ParamCount: 3; Typ: (0, btU32, btS32, btS32, 0 ); Dir: (pmIn, pmIn, pmIn, pmIn){$IFDEF DLL}; Template: 'event OnUseLine(const actorKEY: LongWord; const lineNO: Integer;|' + ' const side: Integer);|' + 'begin|' + '// Executes when the actor "actorKEY" uses the line "lineNO"|' + '// line must have the "Trigger PascalScript" setting enabled|' + '// actor must not have the MF2_EX_DONTRUNSCRIPTS flag|' + ' |' + 'end;||'{$ENDIF} ), ( Name: 'ONTICK'; ParamCount: 1; Typ: (0, btS32, 0, 0, 0 ); Dir: (pmIn, pmIn, pmIn, pmIn){$IFDEF DLL}; Template: 'event OnTick(const tick: Integer);|' + 'begin|' + '// Executes in every tick (35 times/second), after running all thinkers|' + ' |' + 'end;||'{$ENDIF} ), ( Name: 'ONTIMEREVERYSECOND'; ParamCount: 1; Typ: (0, btS32, 0, 0, 0 ); Dir: (pmIn, pmIn, pmIn, pmIn){$IFDEF DLL}; Template: 'event OnTimerEverySecond(const second: Integer);|' + 'begin|' + '// Executes every second (35 ticks), after OnTick Event|' + ' |' + 'end;||'{$ENDIF} ), ( Name: 'ONTIMEREVERYMINUTE'; ParamCount: 1; Typ: (0, btS32, 0, 0, 0 ); Dir: (pmIn, pmIn, pmIn, pmIn){$IFDEF DLL}; Template: 'event OnTimerEveryMinute(const minute: integer);|' + 'begin|' + '// Executes every minute (35 * 60 ticks), after OnTimerEverySecond Event|' + ' |' + 'end;||'{$ENDIF} ), ( Name: 'ONMAPSTART'; ParamCount: 0; Typ: (0, 0, 0, 0, 0 ); Dir: (pmIn, pmIn, pmIn, pmIn){$IFDEF DLL}; Template: 'event OnMapStart;|' + 'begin|' + '// Executes the first time the map loads, before running thinkers|' + ' |' + 'end;||'{$ENDIF} ) ); type TScriptEvents = class(TObject) private fExec: TDoomExec; fProcActorDied: TMethod; fProcPlayerEnter: TMethod; fProcPlayerDied: TMethod; fProcCrossLine: TMethod; fProcShootLine: TMethod; fProcUseLine: TMethod; fProcTick: TMethod; fProcTimerEverySecond: TMethod; fProcTimerEveryMinute: TMethod; fProcMapStart: TMethod; procedure RunProc(const aProc: TMethod; const aParams: array of Integer); public constructor Create(const aExec: TDoomExec); procedure Clear; procedure LinkEvents; // Must be in sync with ScriptOnExportCheck and ps_main events procedure ProcActorDied(actor: LongWord; killer: LongWord); procedure ProcPlayerEnter(playerNO: Integer); procedure ProcPlayerDied(playerNO: Integer; killer: LongWord); procedure ProcCrossLine(actor: LongWord; line: Integer; oldside: Integer); procedure ProcShootLine(actor: LongWord; line: Integer; oldside: Integer); procedure ProcUseLine(actor: LongWord; line: Integer; oldside: Integer); procedure ProcTick(tick: Integer); procedure ProcTimerEverySecond(second: Integer); procedure ProcTimerEveryMinute(minute: Integer); procedure ProcMapStart; end; implementation uses i_system, SysUtils, ps_runtime; type TScriptEvent = procedure of object; TScriptEvent1I = procedure (aParam1: Integer) of object; TScriptEvent2I = procedure (aParam1, aParam2: Integer) of object; TScriptEvent3I = procedure (aParam1, aParam2, aParam3: Integer) of object; TScriptEvent4I = procedure (aParam1, aParam2, aParam3, aParam4: Integer) of object; //============================================================================== // // TScriptEvents.Create // //============================================================================== constructor TScriptEvents.Create(const aExec: TDoomExec); begin fExec := aExec; Clear; inherited Create; end; //============================================================================== // // TScriptEvents.Clear // //============================================================================== procedure TScriptEvents.Clear; begin fProcActorDied.Code := nil; fProcPlayerEnter.Code := nil; fProcPlayerDied.Code := nil; fProcCrossLine.Code := nil; fProcShootLine.Code := nil; fProcUseLine.Code := nil; fProcTick.Code := nil; fProcTimerEverySecond.Code := nil; fProcTimerEveryMinute.Code := nil; fProcMapStart.Code := nil; end; //============================================================================== // // TScriptEvents.LinkEvents // //============================================================================== procedure TScriptEvents.LinkEvents; begin fProcActorDied := fExec.GetProcAsMethodN('ONACTORDIED'); fProcPlayerEnter := fExec.GetProcAsMethodN('ONPLAYERENTER'); fProcPlayerDied := fExec.GetProcAsMethodN('ONPLAYERDIED'); fProcCrossLine := fExec.GetProcAsMethodN('ONCROSSLINE'); fProcShootLine := fExec.GetProcAsMethodN('ONSHOOTLINE'); fProcUseLine := fExec.GetProcAsMethodN('ONUSELINE'); fProcTick := fExec.GetProcAsMethodN('ONTICK'); fProcTimerEverySecond := fExec.GetProcAsMethodN('ONTIMEREVERYSECOND'); fProcTimerEveryMinute := fExec.GetProcAsMethodN('ONTIMEREVERYMINUTE'); fProcMapStart := fExec.GetProcAsMethodN('ONMAPSTART'); end; //============================================================================== // // TScriptEvents.RunProc // //============================================================================== procedure TScriptEvents.RunProc(const aProc: TMethod; const aParams: array of Integer); var ExceptionProc: TPSProcRec; s: string; begin if aProc.Code = nil then Exit; try case Length(aParams) of 0: TScriptEvent(aProc); 1: TScriptEvent1I(aProc)(aParams[0]); 2: TScriptEvent2I(aProc)(aParams[0], aParams[1]); 3: TScriptEvent3I(aProc)(aParams[0], aParams[1], aParams[2]); 4: TScriptEvent4I(aProc)(aParams[0], aParams[1], aParams[2], aParams[3]); else I_Warning('TScriptEvents.RunProc(): Invalid number of parameters %d'#13#10, [Length(aParams)]); Exit; end; except on E: Exception do begin s := 'Exception in script: ''' + E.Message + ''''; ExceptionProc := fExec.GetProcNo(fExec.ExceptionProcNo); if ExceptionProc is TPSInternalProcRec then s := s + ' in procedure ''' + TPSInternalProcRec(ExceptionProc).ExportName + ''''; I_Warning('TScriptEvents.RunProc():' + S); end; end; end; //============================================================================== // // TScriptEvents.ProcActorDied // //============================================================================== procedure TScriptEvents.ProcActorDied(actor: LongWord; killer: LongWord); begin RunProc(fProcActorDied, [actor, killer]); end; //============================================================================== // // TScriptEvents.ProcPlayerEnter // //============================================================================== procedure TScriptEvents.ProcPlayerEnter(playerNO: Integer); begin RunProc(fProcPlayerEnter, [playerNO]); end; //============================================================================== // // TScriptEvents.ProcPlayerDied // //============================================================================== procedure TScriptEvents.ProcPlayerDied(playerNO: Integer; killer: LongWord); begin RunProc(fProcPlayerDied, [playerNO, killer]); end; //============================================================================== // // TScriptEvents.ProcCrossLine // //============================================================================== procedure TScriptEvents.ProcCrossLine(actor: LongWord; line: Integer; oldside: Integer); begin RunProc(fProcCrossLine, [actor, line, oldside]); end; //============================================================================== // // TScriptEvents.ProcShootLine // //============================================================================== procedure TScriptEvents.ProcShootLine(actor: LongWord; line: Integer; oldside: Integer); begin RunProc(fProcShootLine, [actor, line, oldside]); end; //============================================================================== // // TScriptEvents.ProcUseLine // //============================================================================== procedure TScriptEvents.ProcUseLine(actor: LongWord; line: Integer; oldside: Integer); begin RunProc(fProcUseLine, [actor, line, oldside]); end; //============================================================================== // // TScriptEvents.ProcTick // //============================================================================== procedure TScriptEvents.ProcTick(tick: Integer); begin RunProc(fProcTick, [tick]); end; //============================================================================== // // TScriptEvents.ProcTimerEverySecond // //============================================================================== procedure TScriptEvents.ProcTimerEverySecond(second: Integer); begin RunProc(fProcTimerEverySecond, [second]); end; //============================================================================== // // TScriptEvents.ProcTimerEveryMinute // //============================================================================== procedure TScriptEvents.ProcTimerEveryMinute(minute: Integer); begin RunProc(fProcTimerEveryMinute, [minute]); end; //============================================================================== // // TScriptEvents.ProcMapStart // //============================================================================== procedure TScriptEvents.ProcMapStart; begin RunProc(fProcMapStart, []); end; end.
412
0.852209
1
0.852209
game-dev
MEDIA
0.623548
game-dev
0.96117
1
0.96117
PetteriM1/NukkitPetteriM1Edition
2,022
src/main/java/cn/nukkit/event/player/PlayerTeleportEvent.java
package cn.nukkit.event.player; import cn.nukkit.Player; import cn.nukkit.event.Cancellable; import cn.nukkit.event.HandlerList; import cn.nukkit.level.Level; import cn.nukkit.level.Location; import cn.nukkit.level.Position; import cn.nukkit.math.Vector3; public class PlayerTeleportEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); public static HandlerList getHandlers() { return handlers; } private TeleportCause cause; private Location from; private Location to; private PlayerTeleportEvent(Player player) { this.player = player; } public PlayerTeleportEvent(Player player, Location from, Location to, TeleportCause cause) { this(player); this.from = from; this.to = to; this.cause = cause; } public PlayerTeleportEvent(Player player, Vector3 from, Vector3 to, TeleportCause cause) { this(player); this.from = vectorToLocation(player.getLevel(), from); this.from = vectorToLocation(player.getLevel(), to); this.cause = cause; } public Location getFrom() { return from; } public Location getTo() { return to; } public TeleportCause getCause() { return cause; } private static Location vectorToLocation(Level baseLevel, Vector3 vector) { if (vector instanceof Location) return (Location) vector; if (vector instanceof Position) return ((Position) vector).getLocation(); return new Location(vector.getX(), vector.getY(), vector.getZ(), 0, 0, baseLevel); } public enum TeleportCause { COMMAND, // For Nukkit tp command only PLUGIN, // Every plugin NETHER_PORTAL, // Teleport using nether portal END_PORTAL, // Teleport using end portal ENDER_PEARL, // Teleport by ender pearl CHORUS_FRUIT, // Teleport by chorus fruit UNKNOWN // Unknown cause } }
412
0.918704
1
0.918704
game-dev
MEDIA
0.858547
game-dev
0.939041
1
0.939041
jondgoodwin/cone
5,237
test/test.cone
// A test program in Cone that does nothing interesting import stdio::* import submod::* macro one[p]: p fn max[T](x T, y T) T: if x > y {x} else {y} // Define a custom type that supports an array-like API struct List: mut arr [4; i32] fn `[]`(self, index usize) i32: arr[index] fn `&[]`(self &mut) &[]mut i32: &mut arr fn listops(): mut list = List[arr: [1, 5, 2, 8]] // imm r = &mut list[3] //imm q = *r imm x = "πabcdefghijklmnopqrstuvwxyz" fn matching(x i32) i32: mut result = Ok[i32, i32][5] mut some = if x==0 {Some[5]} else {None[i32][]} mut n = one[if x==0 {5} else {6}] imm r = max(2, 6) imm r3 = max[f32](3.6, 6.2) match x: case ==1: {imm r = 8; n = 4} else: n = 7 n union Extense: fld i32 fn incr(self &mut) struct Variant1: nbr i32 fn incr(self &mut) {nbr += 1} struct Variant2: x f32 y f32 fn incr(self &mut) {x += 1.; y+=1.} fn inliner(x i32) inline: varcheck(x) fn testinliner(): inliner(2) inliner(3) fn varsum(n Extense) i32: glo2 + n.fld fn varcheck(n i32): mut var = Variant1[n, 100] mut var2 = Variant2[15, 33., 50.] imm var3 = if n == 0 {var} else {var2} // supertype inference imm var4 = if n == 0 {&var} else {&var2} imm refvar &Extense = &var mut vref &<mut Extense = &mut var mut varxx Extense = var vref = &mut varxx vref.fld = 26 vref.incr() if imm v1 &Variant1 = vref: imm ss = 5 match refvar: case imm v2 &Variant2: {v2.x + v2.y} case imm v1 &Variant1: {f32[v1.nbr]} glo2 = varsum(var) struct Drops: n i32 dro2 Drop2 fn final(self &uni): while n > 0: --n struct Drop2: n f32 fn final(self &uni): n-- fn dropper(): mut n = Drops[0, Drop2[1.2]] mut glowy = 34u32 mut glo2 i32 = 7 struct refstruct {ref +rc-mut i32} fn rcmret() u32, +rc-mut i32: 24u, +rc-mut 32 fn rcstruct(): if &cone != &cone: imm x = &cone mut str = refstruct[ref: +rc-mut 2] mut s +so i32 rcmret() str.ref, s = +rc-mut 3, +so 2 imm newstr = +so str return struct Opaque fn rcpass(ref +rc-mut u32) +rc-mut u32: ref fn rcx(ref +rc-mut u32) +rc-mut u32: imm rcref +rc-mut u32 = if (*ref == 10u) {ref} else {+rc-mut 16u} rcref fn rctest(): mut rcref = +rc-mut 32u32 mut r2 = rcref rcref = r2 = rcx(r2) rcpass(rcref) mut rcref2 = +rc-mut 4u32 rcref2 = rcref *rcref = *rcref + 1 fn ptrs(mut a *i32, b *i32) Bool: b[*a] = a[0] --a mut r i32 = 4 if !a: r = *a++ a = a + 2 a = a - 1 imm z = b - a a += 4 a -= 4 a <= b fn cone() u32: imm x = if true {5f} else {7d} imm mum = 'a: while: if glowy: break 'a 4 if glowy > 0: break 5 /*submod::*/incr() rctest() print <- "hello" points() mut unsy = 23u unsy = unsy++ //imm newval = &unsy + 4u // auto-deref imm factptr = &fact factptr(3u) imm anonfn = &fn(x i32) i32 {x*x} anonfn(3) '\t' 2.3e1 glowy = unsy glo2 = i32[2.3e1] bitfn(0x1au, 0x42u) array(2) mut z1 i32; mut z2 i32; z1,z2=swap(-2, 5) mut tup (i32, i32) = swap(5, -2) mut tup1 = tup.1 fact(6) calc(&mut glo2, 10) glowy // Implicit return of global var's value // Structure handling test struct Point: x f32 y f32 z f32 = 2. fn decr(self &) f32: x - 1. fn add(self &) f32: x + self.y fn add(self) f32: x + `()`() fn add(self, other) f32: self.x + other.x fn `+=`(self &mut, other Point) Point: x = x + other.x*x y = y + other.x*x z = z + other.x*x *self fn `()`(self) f32: x - z fn xset(self &mut, xx f32): imm m = Point[1., 2., 3.] x = xx imm pp = Point[2., 3., 1.] fn points(): imm fval = 3f mut pt Point = Point[y: 1f, x: fval] mut xpt Point xpt.x = 3f with &mut xpt: .y = .x { xpt.y = 3f } (&pt).add() &pt.decr pt += pt pt.add() pt() xpt = pt imm rpt = &mut pt imm a = rpt.x rpt.x = (pt.x).sqrt() fn bitfn(a u32, b u32) u32: mut bin = a==0x1au bin = b > 100u32 if a>4u: return b (a & u32[bin] | a ^ ~u32[b]) << 1 fn fact(mut nbr u32) u32: mut result = 1u each nbrx in 1u < 10u by 2: result += nbrx while nbr > 1 and !nbr>50: result = result * nbr if result > 10000u: break nbr = nbr - 1 result // if nbr { nbr*fact(nbr-1) } else { 1 } fn calc(aa &mut i32, b = 1) i32: imm a = *aa *aa = 5 *aa -= 2 a + (a+a)*b % b fn array(index u32) u8: mut a [4; u8] = [4u8, 10u8, 12u8, 40u8] imm r = &a[1] mut b = a imm slice = &[]mut b imm ptr *u8 = slice imm len = slice.len imm refelem = &mut slice[0] b[0] = a[2] slice[1] = b[3] slice[index] fn swap(mut x i32, mut y i32) i32,i32: x, y = y, x x,y fn refs(): mut a = 3 mut b = &a if true: mut c = 5 // b = &c // Uncomment for lifetime error imm π = 3.1415926535 fn summer(): print <- ∑(1, 10, &fn(n f32) f32 {π * n * n}) fn ∑(low i32, high i32, lam &fn(n f32) f32) f32: mut sum = 0. each i in low <= high: sum += lam(f32[i]) sum
412
0.802627
1
0.802627
game-dev
MEDIA
0.302852
game-dev
0.946801
1
0.946801
microsoft/ParrotServe
3,884
parrot/serve/session/native_executor.py
# Copyright (c) 2023 by Microsoft Corporation. # Licensed under the MIT license. import asyncio from typing import Optional, Dict, Any from types import FunctionType from parrot.utils import get_logger, create_task_in_loop from parrot.exceptions import parrot_assert from parrot.serve.graph import NativeFuncNode, ComputeGraph logger = get_logger("NativeExecutor") class OutputProxy: def __init__(self) -> None: self.content: Optional[str] = None def set(self, content: str) -> None: self.content = content class PyNativeExecutor: """ PyNativeExecutor in a session directly executes a Python native function in the server side. """ def __init__(self, session_id: int, graph: ComputeGraph) -> None: # ---------- Basic Info ---------- self.session_id = session_id self.graph = graph # ---------- Execution ---------- self.func_cache: Dict[str, FunctionType] = {} # ---------- Runtime ---------- self.bad_exception: Optional[Exception] = None async def _execute_coroutine(self, func_node: NativeFuncNode) -> None: """Coroutine for executing a PyNativeCallRequest.""" # Block until it's activated by at least 1 SV. await func_node.wait_activated() # Block until all inputs are ready. await func_node.wait_ready() native_request = func_node.native_func try: await asyncio.wait_for( self.execute(func_node), native_request.metadata.timeout, ) except Exception as e: logger.error( f"Error when executing Python native function. (func_name={func_node.native_func.func_name}, session_id={self.session_id}): {e}" ) self.exception_interrupt(e) def exception_interrupt(self, exception: BaseException): self.bad_exception = exception def add_native_func(self, func_node: NativeFuncNode) -> None: """Add a native function to the graph and assign a coroutine to the request.""" logger.debug( f"Add NativeFunc(request_id={func_node.native_func.request_id}) to executor of Session(session_id={self.session_id})." ) # Insert the request chain into the graph. self.graph.insert_native_func_node(func_node) # Create execution coroutines for the request chain. create_task_in_loop(self._execute_coroutine(func_node)) async def execute(self, func_node: NativeFuncNode) -> None: """Execute a NativeFunc.""" kwargs: Dict[str, Any] = {} # Preparing parameters for key, var in func_node.input_vars.items(): parrot_assert(var.is_ready(), f"Input var {var} is not ready.") content = var.get() kwargs[key] = content for key, value in func_node.input_values.items(): kwargs[key] = value # Create output proxies pystring_proxies: Dict[str, OutputProxy] = {} for key, var in func_node.output_vars.items(): pystring_proxies[key] = OutputProxy() kwargs[key] = pystring_proxies[key] # Execute the native function if func_node.native_func.executable_func is not None: func_node.native_func.executable_func(**kwargs) self.func_cache[func_node.native_func.func_name] = ( func_node.native_func.executable_func ) else: func = self.func_cache.get(func_node.native_func.func_name) if func is None: raise ValueError( f"Function {func_node.native_func.func_name} not found in Cache." ) func(**kwargs) # Write back the output for key, var in func_node.output_vars.items(): var.set(pystring_proxies[key].content)
412
0.774255
1
0.774255
game-dev
MEDIA
0.452178
game-dev
0.665598
1
0.665598
bdovaz/UnityNuGet
7,486
src/UnityNuGet/UnityMeta.cs
using System; using System.Collections.Generic; using System.Linq; using Scriban; namespace UnityNuGet { /// <summary> /// Helper methods to create Unity .meta files /// </summary> internal static class UnityMeta { public static string? GetMetaForExtension(Guid guid, string extension) { switch (extension) { case ".pdb": break; case ".asmdef": case ".cs": case ".json": case ".md": case ".txt": case ".xml": return GetMetaForText(guid); } return null; } public static string GetMetaForDll( Guid guid, PlatformDefinition platformDef, IEnumerable<string> labels, IEnumerable<string> defineConstraints) { const string text = @"fileFormatVersion: 2 guid: {{ guid }} {{ labels }}PluginImporter: externalObjects: {} serializedVersion: 2 iconMap: {} executionOrder: {} {{ constraints }} isPreloaded: 0 isOverridable: 0 isExplicitlyReferenced: 0 validateReferences: 1 platformData:{{exclude_platforms}} - first: Any: second: enabled: {{ all_enabled }} settings: {}{{ per_platform_settings }} - first: Windows Store Apps: WindowsStoreApps second: enabled: 0 settings: CPU: AnyCPU userData: assetBundleName: assetBundleVariant: "; var allLabels = labels.ToList(); var allConstraints = defineConstraints.ToList(); static string FormatList(IEnumerable<string> items) => string.Join( string.Empty, items.Select(d => $" - {d}\n")); string excludePlatforms = string.Empty; string perPlatformSettings = @" - first: Editor: Editor second: enabled: 0 settings: DefaultValueInitialized: true"; // Render the per-platform settings if (platformDef.Os != UnityOs.AnyOs) { // Determine which configurations are enabled PlatformDefinition? platWin = platformDef.Find(UnityOs.Windows, UnityCpu.X86); PlatformDefinition? platWin64 = platformDef.Find(UnityOs.Windows, UnityCpu.X64); PlatformDefinition? platLinux64 = platformDef.Find(UnityOs.Linux, UnityCpu.X64); PlatformDefinition? platOsx = platformDef.Find(UnityOs.OSX); PlatformDefinition? platAndroid = platformDef.Find(UnityOs.Android); PlatformDefinition? platWasm = platformDef.Find(UnityOs.WebGL); PlatformDefinition? platIos = platformDef.Find(UnityOs.iOS); PlatformDefinition? platEditor = platformDef.FindEditor(); var dict = new { enablesWin = (platWin != null) ? 1 : 0, enablesWin64 = (platWin64 != null) ? 1 : 0, enablesLinux64 = (platLinux64 != null) ? 1 : 0, enablesOsx = (platOsx != null) ? 1 : 0, enablesAndroid = (platAndroid != null) ? 1 : 0, enablesWasm = (platWasm != null) ? 1 : 0, enablesIos = (platIos != null) ? 1 : 0, enablesEditor = (platEditor != null) ? 1 : 0, cpuWin = (platWin?.Cpu ?? UnityCpu.None).GetName(), cpuWin64 = (platWin64?.Cpu ?? UnityCpu.None).GetName(), cpuLinux64 = (platLinux64?.Cpu ?? UnityCpu.None).GetName(), cpuOsx = (platOsx?.Cpu ?? UnityCpu.None).GetName(), cpuAndroid = (platAndroid?.Cpu ?? UnityCpu.None).GetName(), cpuIos = (platIos?.Cpu ?? UnityCpu.None).GetName(), cpuEditor = (platEditor?.Cpu ?? UnityCpu.None).GetName(), osEditor = (platEditor?.Os ?? UnityOs.AnyOs).GetName(), }; const string excludePlatformsText = @" - first: : Any second: enabled: 0 settings: Exclude Android: {{ 1 - enables_android }} Exclude Editor: {{ 1 - enables_editor }} Exclude Linux64: {{ 1 - enables_linux64 }} Exclude OSXUniversal: {{ 1 - enables_osx }} Exclude WebGL: {{ 1 - enables_wasm }} Exclude Win: {{ 1 - enables_win }} Exclude Win64: {{ 1 - enables_win64 }} Exclude iOS: {{ 1 - enables_ios }}"; const string perPlatformSettingsText = @" - first: Android: Android second: enabled: {{ enables_android }} settings: CPU: {{ cpu_android }} - first: Editor: Editor second: enabled: {{ enables_editor }} settings: CPU: {{ cpu_editor }} DefaultValueInitialized: true OS: {{ os_editor }} - first: Standalone: Linux64 second: enabled: {{ enables_linux64 }} settings: CPU: {{ cpu_linux64 }} - first: Standalone: OSXUniversal second: enabled: {{ enables_osx }} settings: CPU: {{ cpu_osx }} - first: Standalone: Win second: enabled: {{ enables_win }} settings: CPU: {{ cpu_win }} - first: Standalone: Win64 second: enabled: {{ enables_win64 }} settings: CPU: {{ cpu_win64 }} - first: WebGL: WebGL second: enabled: {{ enables_wasm }} settings: {} - first: iPhone: iOS second: enabled: {{ enables_ios }} settings: AddToEmbeddedBinaries: false CPU: {{ cpu_ios }} CompileFlags: FrameworkDependencies: "; excludePlatforms = Template .Parse(excludePlatformsText) .Render(dict); perPlatformSettings = Template .Parse(perPlatformSettingsText) .Render(dict); } bool allPlatformsEnabled = (platformDef.Os == UnityOs.AnyOs) && (platformDef.Cpu == UnityCpu.AnyCpu); return Template .Parse(text) .Render(new { excludePlatforms, perPlatformSettings, guid = guid.ToString("N"), allEnabled = allPlatformsEnabled ? "1" : "0", labels = allLabels.Count == 0 ? string.Empty : $"labels:\n{FormatList(allLabels)}", constraints = allConstraints.Count == 0 ? string.Empty : $" defineConstraints:\n{FormatList(allConstraints)}" }) .StripWindowsNewlines(); } public static string GetMetaForFolder(Guid guid) { return $@"fileFormatVersion: 2 guid: {guid:N} folderAsset: yes DefaultImporter: externalObjects: {{}} userData: assetBundleName: assetBundleVariant: ".StripWindowsNewlines(); } private static string GetMetaForText(Guid guid) { return $@"fileFormatVersion: 2 guid: {guid:N} TextScriptImporter: externalObjects: {{}} userData: assetBundleName: assetBundleVariant: ".StripWindowsNewlines(); } private static string StripWindowsNewlines(this string input) => input.Replace("\r\n", "\n"); } }
412
0.853893
1
0.853893
game-dev
MEDIA
0.385341
game-dev
0.732012
1
0.732012
TheAnswer/Core3
2,418
MMOCoreORB/src/server/zone/objects/ship/components/ShipReactorComponentImplementation.cpp
#include "server/zone/objects/ship/components/ShipReactorComponent.h" #include "server/zone/objects/ship/ShipObject.h" #include "server/zone/packets/DeltaMessage.h" void ShipReactorComponentImplementation::loadTemplateData(SharedObjectTemplate* templateData) { ShipComponentImplementation::loadTemplateData(templateData); auto shot = dynamic_cast<ShipComponentTemplate*>(templateData); if (shot != nullptr) { const auto& attributeMap = shot->getAttributeMap(); for (int i = 0; i < attributeMap.size(); ++i) { const auto& attribute = attributeMap.elementAt(i).getKey(); float value = attributeMap.elementAt(i).getValue(); if (attribute == "energyGeneration") { reactorGenerationRate = value; } } } } void ShipReactorComponentImplementation::updateCraftingValues(CraftingValues* values, bool firstUpdate) { ShipComponentImplementation::updateCraftingValues(values, firstUpdate); if (values->hasExperimentalAttribute("ship_component_reactor_generation_rate")) { reactorGenerationRate = values->getCurrentValue("ship_component_reactor_generation_rate"); } } void ShipReactorComponentImplementation::fillAttributeList(AttributeListMessage* alm, CreatureObject* object) { ShipComponentImplementation::fillAttributeList(alm, object); alm->insertAttribute("@obj_attr_n:ship_component.ship_component_reactor_generation_rate", String::valueOf(Math::getPrecision(reactorGenerationRate, 1))); if (reverseEngineeringLevel != 0) { alm->insertAttribute("@obj_attr_n:reverseengineeringlevel", reverseEngineeringLevel); } } void ShipReactorComponentImplementation::install(CreatureObject* pilot, ShipObject* ship, int slot, bool notifyClient) { ShipComponentImplementation::install(pilot, ship, slot, notifyClient); DeltaMessage* ship1 = notifyClient ? new DeltaMessage(ship->getObjectID(), 'SHIP', 1) : nullptr; ship->setReactorGenerationRate(reactorGenerationRate, false, ship1); if (notifyClient) { ship1->close(); pilot->sendMessage(ship1); } } void ShipReactorComponentImplementation::uninstall(CreatureObject* pilot, ShipObject* ship, int slot, bool notifyClient) { ShipComponentImplementation::uninstall(pilot, ship, slot, notifyClient); DeltaMessage* ship1 = notifyClient ? new DeltaMessage(ship->getObjectID(), 'SHIP', 1) : nullptr; ship->setReactorGenerationRate(0.f, false, ship1); if (notifyClient) { ship1->close(); pilot->sendMessage(ship1); } }
412
0.838695
1
0.838695
game-dev
MEDIA
0.53699
game-dev,networking
0.857089
1
0.857089
AU-Master-Thesis/magics
54,221
crates/magics/src/environment/map_generator.rs
use std::sync::Arc; use bevy::prelude::*; use bevy_mod_picking::prelude::*; use gbp_config::{Config, DrawSetting}; use gbp_environment::{ Circle, Environment, PlaceableShape, Rectangle, RegularPolygon, TileCoordinates, Triangle, }; use gbp_global_planner::Colliders; use parry2d::{ na::{self, Isometry2, Vector2}, shape, }; use crate::{ asset_loader::Materials, bevy_utils::run_conditions::event_exists, input::DrawSettingsEvent, simulation_loader::LoadSimulation, }; pub struct GenMapPlugin; impl Plugin for GenMapPlugin { fn build(&self, app: &mut App) { app .add_event::<events::ObstacleClickedOn>() // .init_resource::<Colliders>() // .add_systems(Startup, (build_tile_grid, build_obstacles)) // .add_systems(PostStartup, create_static_colliders) .add_systems( Update, (build_tile_grid.pipe(build_obstacles.pipe(insert_colliders_resource))).chain().run_if(on_event::<LoadSimulation>()), ) .add_systems( Update, show_or_hide_generated_map.run_if(event_exists::<DrawSettingsEvent>), ); } } pub mod events { use super::*; #[derive(Debug, Event)] pub struct ObstacleClickedOn(pub Entity); impl From<ListenerInput<Pointer<Click>>> for ObstacleClickedOn { #[inline] fn from(value: ListenerInput<Pointer<Click>>) -> Self { Self(value.target) } } } #[derive(Debug, Component)] pub struct ObstacleMarker; // #[derive(Clone)] // pub struct Collider { // pub associated_mesh: Option<Entity>, // pub isometry: Isometry2<f32>, // pub shape: Arc<dyn shape::Shape>, // } // impl Collider { // #[inline] // pub fn aabb(&self) -> parry2d::bounding_volume::Aabb { // self.shape.compute_aabb(&self.isometry) // } // } // #[derive(Resource, Default, Clone)] // pub struct Colliders(Vec<Collider>); // impl Colliders { // delegate! { // to self.0 { // #[call(iter)] // pub fn iter(&self) -> impl Iterator<Item = &Collider>; // #[call(len)] // pub fn len(&self) -> usize; // #[call(is_empty)] // pub fn is_empty(&self) -> bool; // #[call(clear)] // pub fn clear(&mut self); // } // } // pub fn push( // &mut self, // associated_mesh: Option<Entity>, // position: Isometry2<f32>, // shape: Arc<dyn shape::Shape>, // ) { // self.0.push(Collider { // associated_mesh, // isometry: position, // shape, // }); // } // } fn insert_colliders_resource(In(colliders): In<Colliders>, mut commands: Commands) { commands.insert_resource(colliders); } /// **Bevy** [`Startup`] _system_. /// Takes the [`Environment`] configuration and generates all specified /// [`Obstacles`]. /// /// [`Obstacles`] example: /// ```rust /// Obstacles(vec![ /// Obstacle::new( /// (0, 0), /// PlaceableShape::circle(0.1, (0.5, 0.5)), /// Angle::new(0.0).unwrap(), /// ), /// Obstacle::new( /// (0, 0), /// PlaceableShape::triangle(0.1, 0.1, 0.5), /// Angle::new(0.0).unwrap(), /// ), /// Obstacle::new( /// (0, 0), /// PlaceableShape::square(0.1, (0.75, 0.5)), /// Angle::new(0.0).unwrap(), /// ), /// ]), /// ``` /// /// Placement of all shapes is given as a `(x, y)` percentage local to a /// specific tile #[allow( clippy::too_many_lines, clippy::cast_precision_loss, clippy::cast_possible_truncation )] fn build_obstacles( In(mut colliders): In<Colliders>, mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, env_config: Res<Environment>, config: Res<Config>, // scene_assets: Res<SceneAssets>, materials: Res<Materials>, ) -> Colliders { let tile_grid = &env_config.tiles.grid; let tile_size = env_config.tile_size(); let obstacle_height = -env_config.obstacle_height(); let grid_offset_x = tile_grid.ncols() as f32 / 2.0 - 0.5; let grid_offset_z = tile_grid.nrows() as f32 / 2.0 - 0.5; info!("Spawning obstacles"); info!("{:?}", env_config.obstacles); info!( "env_config.obstacles.iter().count() = {:?}", env_config.obstacles.iter().count() ); let obstacles_to_spawn = env_config.obstacles.iter().map(|obstacle| { let TileCoordinates { row, col } = obstacle.tile_coordinates; info!("Spawning obstacle at {:?}", (row, col)); let tile_offset_x = col as f32; let tile_offset_z = row as f32; let offset_x = (tile_offset_x - grid_offset_x) * tile_size; let offset_z = (tile_offset_z - grid_offset_z) * tile_size; let pos_offset = tile_size / 2.0; let translation = obstacle.translation; // Construct the correct shape match &obstacle.shape { PlaceableShape::Circle(Circle { radius }) => { let center = Vec3::new( (translation.x.get() as f32).mul_add(tile_size, offset_x) - pos_offset, obstacle_height / 2.0, (1.0 - translation.y.get() as f32).mul_add(tile_size, offset_z) - pos_offset, ); info!("Spawning circle: r = {}, at {:?}", radius, center); let radius = radius.get() as f32 * tile_size; let mesh = meshes.add(Cylinder::new(radius, obstacle_height)); let transform = Transform::from_translation(center); info!( "Spawning cylinder: r = {}, h = {}, at {:?}", radius, obstacle_height, transform ); let shape = parry2d::shape::Ball::new(radius); let shape: Arc<dyn shape::Shape> = Arc::new(shape); let isometry = Isometry2::new( parry2d::na::Vector2::new(transform.translation.x, transform.translation.z), na::zero(), ); Some((mesh, transform, isometry, shape)) } PlaceableShape::Triangle( triangle_shape @ Triangle { angles: _, radius: _, }, ) => { let center = Vec3::new( (translation.x.get() as f32).mul_add(tile_size, offset_x) - pos_offset, // obstacle_height / 2.0, obstacle_height, -((translation.y.get() as f32).mul_add(tile_size, offset_z) - pos_offset), ); // Example triangle // |\ // | \ // |__\ // In this case the `base_length` is 1.0, `height` is 3.0, and the `mid_point` // is 0.0, the 3.0 height is placed at the very left of the triangle. // This creates a right-angled triangle. // One could also have a negative `mid_point`, which would make the current // right-angle more obtuse, or a positive `mid_point`, which // would make the current right-angle more acute. let [p1, p2, p3] = triangle_shape.points().map(|point| { Vec2::new(-point.x as f32 * tile_size, point.y as f32 * tile_size) }); // reflect around the x-axis // let p1 = Vec2::new(p1.x, -p1.y); // let p2 = Vec2::new(p2.x, -p2.y); // let p3 = Vec2::new(p3.x, -p3.y); // println!("bottom-left = {:?}", center.xz() + p1); // println!("bottom-right = {:?}", center.xz() + p2); // println!("top = {:?}", center.xz() + p3); // info!( // "Spawning triangle: base_length = {}, height = {}, at {:?}", // base_length, height, center // ); let mesh = meshes.add( Mesh::try_from(bevy_more_shapes::Prism::new( -obstacle_height, [p1, p2, p3].to_vec(), )) .expect("Failed to create triangle mesh"), ); let rotation_angle: f32 = std::f32::consts::FRAC_PI_2 - obstacle.rotation.as_radians() as f32; let rotation = Quat::from_rotation_y(rotation_angle); let isometry = Isometry2::new( parry2d::na::Vector2::new(center.x, center.z), rotation_angle - std::f32::consts::FRAC_PI_2, ); let transform = Transform::from_translation(center).with_rotation(rotation); let rotate = |p: Vec2| { rotation .mul_vec3(p.extend(0.0).xzy()) .xz() .to_array() .into() }; let shape = parry2d::shape::Triangle::new(rotate(p1), rotate(p2), rotate(p3)); let shape: Arc<dyn shape::Shape> = Arc::new(shape); Some((mesh, transform, isometry, shape)) } PlaceableShape::RegularPolygon(polygon @ RegularPolygon { sides, radius }) => { let center = Vec3::new( (translation.x.get() as f32).mul_add(tile_size, offset_x) - pos_offset, obstacle_height / 2.0, -((translation.y.get() as f32).mul_add(tile_size, offset_z) - pos_offset), ); info!( "Spawning regular polygon: sides = {}, radius = {}, at {:?}", sides, radius, center ); let mesh = meshes.add(Mesh::from(bevy_more_shapes::Cylinder { height: -obstacle_height, radius_bottom: radius.get() as f32 * tile_size / 2.0, radius_top: radius.get() as f32 * tile_size / 2.0, radial_segments: *sides as u32, height_segments: 1, })); // info!( // "obstacle.rotation.as_radians() = {:?}, std::f32::consts::FRAC_PI_4 = // {:?}", obstacle.rotation.as_radians() as f32, // std::f32::consts::FRAC_PI_4 // ); let rotation_angle = std::f32::consts::FRAC_PI_4 + obstacle.rotation.as_radians() as f32; let rotation = Quat::from_rotation_y( rotation_angle, /* std::f32::consts::FRAC_PI_4 + * obstacle.rotation.as_radians() as f32, */ ); let transform = Transform::from_translation(center).with_rotation(rotation); // let rotation_offset = match obstacle.shape { // PlaceableShape::RegularPolygon(RegularPolygon { sides, radius }) // => { std::f32::consts::PI // + if sides % 2 != 0 { std::f32::consts::PI / sides as f32 // } else { // 0.0 // } // } // _ => std::f32::consts::FRAC_PI_2, // }; use std::f32::consts::{FRAC_PI_2, PI}; let rotation_offset = PI + match polygon.sides { 4 => 0.0, n if n % 2 != 0 => FRAC_PI_2, _ => -FRAC_PI_2, }; // let rotation_offset = PI // + match polygon.sides { n if n % 2 != 0 => PI / n as f32, _ => 0.0, // n // => FRAC_PI_2 / n as f32, // }; // + if polygon.sides % 2 != 0 { PI / polygon.sides as f32 // } else { // 0.0 // }; // let rotation2 = Quat::from_rotation_y(std::f32::consts::PI / polygon.sides as // f32); let rotation_angle = obstacle.rotation.as_radians() as f32 + rotation_offset; let rotation2 = Quat::from_rotation_z(obstacle.rotation.as_radians() as f32 + rotation_offset); // let rotation2 = Quat::from_rotation_z(rotation_offset); // let points: Vec<parry2d::math::Point<parry2d::math::Real>> = polygon let scale = tile_size / 2.0; let points: Vec<_> = polygon .points() .iter() .map(|[x, y]| { let p = Vec3::new(*x as f32, *y as f32, 0.0); // let p = Vec3::new(*x as f32, 0.0, *y as f32); // let p_rotated = rotation.mul_vec3(p); let p_rotated = rotation2.mul_vec3(p); //dbg!((&p, &p_rotated)); // let p_rotated = p; parry2d::math::Point::new( p_rotated.x * scale, p_rotated.y * scale, // *x as f32 * (tile_size / 2.0), // *y as f32 * (tile_size / 2.0), ) }) // .inspect(|p| println!("p = {:?}", p)) .collect(); let shape = parry2d::shape::ConvexPolygon::from_convex_hull(points.as_slice()) .expect("polygon is always convex"); let shape: Arc<dyn shape::Shape> = Arc::new(shape); let isometry = Isometry2::new( parry2d::na::Vector2::new(transform.translation.x, transform.translation.z), rotation_angle, ); Some((mesh, transform, isometry, shape)) } PlaceableShape::Polygon(gbp_environment::Polygon { points }) => { let center = Vec3::new( (translation.x.get() as f32).mul_add(tile_size, offset_x) - pos_offset, obstacle_height / 2.0, (translation.y.get() as f32).mul_add(tile_size, offset_z) - pos_offset, ); // let center = Vec3::new(0.0, 0.0, 0.0); info!("Spawning polygon: at {:?}", center); let mesh = meshes.add( Mesh::try_from(bevy_more_shapes::Polygon { points: points .iter() .map(|point| { Vec2::new( (point.x as f32) * tile_size, (point.y as f32) * tile_size, ) }) .rev() .collect(), }) .expect("Failed to create irregular polygon mesh"), ); let rotation = Quat::from_rotation_y(obstacle.rotation.as_radians() as f32); let transform = Transform::from_translation(center).with_rotation(rotation); let points: Vec<parry2d::math::Point<parry2d::math::Real>> = points .iter() .map(|point| { parry2d::math::Point::new( (point.x as f32) * tile_size, (point.y as f32) * tile_size, ) }) .collect(); let shape = parry2d::shape::ConvexPolygon::from_convex_hull(points.as_slice()) .expect("polygon is always convex"); let shape: Arc<dyn shape::Shape> = Arc::new(shape); let isometry = Isometry2::new( parry2d::na::Vector2::new(transform.translation.x, transform.translation.z), na::zero(), ); Some((mesh, transform, isometry, shape)) } PlaceableShape::Rectangle(Rectangle { width, height }) => { // dbg!(( // "Rectangle", // translation.y.get() as f32, // tile_size, // -offset_z, // pos_offset, // width, // height, // )); let center = Vec3::new( (translation.x.get() as f32).mul_add(tile_size, offset_x) - pos_offset, obstacle_height / 2.0, -((translation.y.get() as f32).mul_add(tile_size, offset_z) - pos_offset), ); info!( "Spawning rectangle: width = {}, height = {}, at {:?}", width, height, center ); let mesh = meshes.add(Cuboid::new( width.get() as f32 * tile_size / 2.0, obstacle_height, height.get() as f32 * tile_size / 2.0, )); // let rotation = Quat::from_rotation_y(obstacle.rotation.as_radians() as f32); // let transform = Transform::from_translation(center).with_rotation(rotation); let transform = Transform::from_translation(center); let half_extents: parry2d::na::Vector2<parry2d::math::Real> = parry2d::na::Vector2::from_vec(vec![ width.get() as f32 * tile_size / 4.0, height.get() as f32 * tile_size / 4.0, ]); let shape = parry2d::shape::Cuboid::new(half_extents); let shape: Arc<dyn shape::Shape> = Arc::new(shape); let isometry = Isometry2::new( parry2d::na::Vector2::new(transform.translation.x, transform.translation.z), na::zero(), ); Some((mesh, transform, isometry, shape)) } } }); obstacles_to_spawn .flatten() // filter out None .for_each(|(mesh, transform, isometry, shape)| { // TODO: remember to get rotation of obstacle, i.e. for triangles let entity = commands.spawn(( PbrBundle { mesh, material: materials.obstacle.clone(), transform, visibility: if config.visualisation.draw.generated_map { Visibility::Visible } else { Visibility::Hidden }, ..Default::default() }, ObstacleMarker, bevy_mod_picking::PickableBundle::default(), On::<Pointer<Click>>::send_event::<events::ObstacleClickedOn>(), )).id(); colliders.push( Some(entity), isometry, //Isometry2::new(parry2d::na::Vector2::new( // transform.translation.x, // transform.translation.z, //), na::zero()), // FIXME: add rotation shape ); }); colliders } /// **Bevy** [`Startup`] _system_. /// Takes the [`Environment`] configuration and generates a map. /// /// Transforms an input like: /// ```text /// ┌┬┐ /// ┘└┼┬ /// └┘ /// ``` /// Into visual meshes, defining the physical boundaries of the map /// - The lines are not walls, but paths /// - Where the empty space are walls/obstacles /// /// Each tile e.g. tile (0,0) in the above grid "┌" or (3,1) "┬" /// - Transforms into a 1x1 section of the map - later to be scaled /// - Each tile's world position is calculated from the tile's position in the /// grid /// - Such that the map is centered /// - Uses the `Environment.width` to determine the width of the paths, /// - Otherwise, the empty space is filled with solid meshes #[allow(clippy::too_many_lines, clippy::cast_precision_loss)] fn build_tile_grid( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, // mut colliders: ResMut<Colliders>, env_config: Res<Environment>, config: Res<Config>, materials: Res<Materials>, obstacles: Query<Entity, With<ObstacleMarker>>, ) -> Colliders { for entity in &obstacles { commands.entity(entity).despawn(); info!("despawn obstacle entity: {:?}", entity); } let tile_grid = &env_config.tiles.grid; let obstacle_height = env_config.obstacle_height(); let obstacle_y = -obstacle_height / 2.0; let tile_size = env_config.tile_size(); let path_width = env_config.path_width(); let base_dim = tile_size * (1.0 - path_width) / 2.0; // offset caused by the size of the grid // - this centers the map let grid_offset_x = tile_grid.ncols() as f32 / 2.0 - 0.5; let grid_offset_z = -(tile_grid.nrows() as f32 / 2.0 - 0.5); let pos_offset = path_width.mul_add(tile_size, base_dim) / 2.0; let mut colliders = Colliders::default(); for (y, row) in tile_grid.iter().enumerate() { for (x, tile) in row.chars().enumerate() { // offset of the individual tile in the grid // used in all match cases let tile_offset_x = x as f32; let tile_offset_z = -(y as f32); // total offset caused by grid and tile let offset_x = (tile_offset_x - grid_offset_x) * tile_size; let offset_z = (tile_offset_z - grid_offset_z) * tile_size; // Vec<(Handle<Mesh>, Transform, parry2d::shape::Cuboid)> if let Some(obstacle_information) = match tile { '─' | '-' => { // Horizontal straight path // - 2 equal-sized larger cuboid on either side, spanning the entire width of // the tile // let cuboid = Cuboid::new(base_dim, obstacle_height, tile_size); let cuboid = Cuboid::new(tile_size, obstacle_height, base_dim); // let parry_cuboid: parry2d::shape::Cuboid = cuboid.into(); // let mesh_handle = meshes.add(cuboid); Some(vec![ ( // left side cuboid, // left side transform Transform::from_translation(Vec3::new( offset_x, obstacle_y, offset_z - pos_offset, )), ), ( // right side cuboid, // right side transform Transform::from_translation(Vec3::new( offset_x, obstacle_y, offset_z + pos_offset, )), ), ]) } '│' | '|' => { // Vertical straight path // - 2 equal-sized larger cuboid on either side, spanning the entire height of // the tile let cuboid = Cuboid::new(base_dim, obstacle_height, tile_size); // let parry_cuboid: parry2d::shape::Cuboid = cuboid.into(); // let mesh_handle = meshes.add(cuboid); Some(vec![ ( // left side // mesh_handle.clone(), cuboid, // left side transform Transform::from_translation(Vec3::new( offset_x - pos_offset, obstacle_y, offset_z, )), ), ( // right side // mesh_handle.clone(), cuboid, // right side transform Transform::from_translation(Vec3::new( offset_x + pos_offset, obstacle_y, offset_z, )), ), ]) } '╴' => { // Termination from the left // - 2 larger cuboids on the top and bottom, spanning the entire width of the // tile // - 1 smaller 'plug' cuboid on the right, to terminate the path // Top and bottom let cuboid = Cuboid::new(tile_size, obstacle_height, base_dim); // let parry_cuboid: parry2d::shape::Cuboid = cuboid.into(); // let mesh_handle = meshes.add(cuboid); // Plug at the right // let cuboid_plug = // Cuboid::new(base_dim, obstacle_height, path_width * tile_size); let cuboid_plug = Cuboid::new(tile_size / 2.0, obstacle_height, path_width * tile_size); // let parry_cuboid_plug: parry2d::shape::Cuboid = cuboid_plug.into(); Some(vec![ ( // top cuboid, // top transform Transform::from_translation(Vec3::new( offset_x, obstacle_y, offset_z - pos_offset, )), ), ( // bottom cuboid, // bottom transform Transform::from_translation(Vec3::new( offset_x, obstacle_y, offset_z + pos_offset, )), ), ( // right plug cuboid_plug, // right plug transform Transform::from_translation(Vec3::new( offset_x + tile_size / 4.0, obstacle_y, offset_z, )), ), ]) } '╶' => { // Termination from the right // - 2 larger cuboids on the top and bottom, spanning the entire width of the // tile // - 1 smaller 'plug' cuboid on the left, to terminate the path // Top and bottom let cuboid = Cuboid::new(tile_size, obstacle_height, base_dim); // let parry_cuboid: parry2d::shape::Cuboid = cuboid.into(); // let mesh_handle = meshes.add(cuboid); // Plug at the left // let cuboid_plug = // Cuboid::new(base_dim, obstacle_height, path_width * tile_size); let cuboid_plug = Cuboid::new(tile_size / 2.0, obstacle_height, path_width * tile_size); // let parry_cuboid_plug: parry2d::shape::Cuboid = cuboid_plug.into(); Some(vec![ ( // top cuboid, // top transform Transform::from_translation(Vec3::new( offset_x, obstacle_y, offset_z - pos_offset, )), ), ( // bottom cuboid, // bottom transform Transform::from_translation(Vec3::new( offset_x, obstacle_y, offset_z + pos_offset, )), ), ( // left plug cuboid_plug, // left plug transform Transform::from_translation(Vec3::new( offset_x - tile_size / 4.0, obstacle_y, offset_z, )), ), ]) } '╷' => { // Termination from the top // - 2 larger cuboids on the left and right, spanning the entire height of the // tile // - 1 smaller 'plug' cuboid on the bottom, to terminate the path // Left and right let cuboid = Cuboid::new(base_dim, obstacle_height, tile_size); // let parry_cuboid: parry2d::shape::Cuboid = cuboid.into(); // let mesh_handle = meshes.add(cuboid); // Plug at the bottom // let cuboid_plug = // Cuboid::new(path_width * tile_size, obstacle_height, base_dim); let cuboid_plug = Cuboid::new(path_width * tile_size, obstacle_height, tile_size / 2.0); // let parry_cuboid_plug: parry2d::shape::Cuboid = cuboid_plug.into(); Some(vec![ ( // left cuboid, // left transform Transform::from_translation(Vec3::new( offset_x - pos_offset, obstacle_y, offset_z, )), ), ( // right cuboid, // right transform Transform::from_translation(Vec3::new( offset_x + pos_offset, obstacle_y, offset_z, )), ), ( // bottom plug cuboid_plug, // bottom plug transform Transform::from_translation(Vec3::new( offset_x, obstacle_y, offset_z + tile_size / 4.0, )), ), ]) } '╵' => { // Termination from the bottom // - 2 larger cuboids on the left and right, spanning the entire height of the // tile // - 1 smaller 'plug' cuboid on the top, to terminate the path // Left and right let cuboid = Cuboid::new(base_dim, obstacle_height, tile_size); // let parry_cuboid: parry2d::shape::Cuboid = cuboid.into(); // let mesh_handle = meshes.add(cuboid); // Plug at the top // let cuboid_plug = // Cuboid::new(path_width * tile_size, obstacle_height, base_dim); let cuboid_plug = Cuboid::new(path_width * tile_size, obstacle_height, tile_size / 2.0); // let parry_cuboid_plug: parry2d::shape::Cuboid = cuboid_plug.into(); Some(vec![ ( // left cuboid, // left transform Transform::from_translation(Vec3::new( offset_x - pos_offset, obstacle_y, offset_z, )), ), ( // right cuboid, // right transform Transform::from_translation(Vec3::new( offset_x + pos_offset, obstacle_y, offset_z, )), ), ( // top plug cuboid_plug, // top plug transform Transform::from_translation(Vec3::new( offset_x, obstacle_y, offset_z - tile_size / 4.0, )), ), ]) } '┌' => { // Top right hand turn // - 1 cube in the bottom right corner // - 1 larger cuboid on the left hand side, spanning the entire height of the // tile // - 1 larger cuboid on the top side, spanning from the right to the above // cuboid let cuboid_bottom_right = Cuboid::new(base_dim, obstacle_height, base_dim); let cuboid_left = Cuboid::new(base_dim, obstacle_height, tile_size); let cuboid_top = Cuboid::new(tile_size, obstacle_height, base_dim); Some(vec![ ( // bottom right cube cuboid_bottom_right, // bottom right cube transform Transform::from_translation(Vec3::new( offset_x + pos_offset, obstacle_y, offset_z - pos_offset, )), ), ( // left side cuboid_left, // left side transform Transform::from_translation(Vec3::new( offset_x - pos_offset, obstacle_y, offset_z, )), ), ( // top cuboid_top, // top transform Transform::from_translation(Vec3::new( offset_x, obstacle_y, offset_z + pos_offset, )), ), ]) } '┐' => { // Top left hand turn // - 1 cube in the bottom left corner // - 1 larger cuboid on the right hand side, spanning the entire height of the // tile // - 1 larger cuboid on the top side, spanning from the left to the above cuboid let cuboid_bottom_left = Cuboid::new(base_dim, obstacle_height, base_dim); let cuboid_right = Cuboid::new(base_dim, obstacle_height, tile_size); let cuboid_top = Cuboid::new(tile_size, obstacle_height, base_dim); Some(vec![ ( // bottom left cube cuboid_bottom_left, // bottom left cube transform Transform::from_translation(Vec3::new( offset_x - pos_offset, obstacle_y, offset_z - pos_offset, )), ), ( // right side cuboid_right, // right side transform Transform::from_translation(Vec3::new( offset_x + pos_offset, obstacle_y, offset_z, )), ), ( // top cuboid_top, // top transform Transform::from_translation(Vec3::new( offset_x, obstacle_y, offset_z + pos_offset, )), ), ]) } '└' => { // Bottom right hand turn // - 1 cube in the top right corner // - 1 larger cuboid on the left hand side, spanning the entire height of the // tile // - 1 larger cuboid on the bottom side, spanning from the right to the above // cuboid let cuboid_top_right = Cuboid::new(base_dim, obstacle_height, base_dim); let cuboid_left = Cuboid::new(base_dim, obstacle_height, tile_size); let cuboid_bottom = Cuboid::new(tile_size, obstacle_height, base_dim); Some(vec![ ( // top right cube cuboid_top_right, // top right cube transform Transform::from_translation(Vec3::new( offset_x + pos_offset, obstacle_y, offset_z + pos_offset, )), ), ( // left side cuboid_left, // left side transform Transform::from_translation(Vec3::new( offset_x - pos_offset, obstacle_y, offset_z, )), ), ( // bottom cuboid_bottom, // bottom transform Transform::from_translation(Vec3::new( offset_x, obstacle_y, offset_z - pos_offset, )), ), ]) } '┘' => { // Bottom left hand turn // - 1 cube in the top left corner // - 1 larger cuboid on the right hand side, spannding the entire height of the // tile // - 1 larger cuboid on the bottom side, spanning from the left to the above // cuboid let cuboid_top_left = Cuboid::new(base_dim, obstacle_height, base_dim); let cuboid_right = Cuboid::new(base_dim, obstacle_height, tile_size); let cuboid_bottom = Cuboid::new(tile_size, obstacle_height, base_dim); Some(vec![ ( // top left cube cuboid_top_left, // top left cube transform Transform::from_translation(Vec3::new( offset_x - pos_offset, obstacle_y, offset_z + pos_offset, )), ), ( // right side cuboid_right, // right side transform Transform::from_translation(Vec3::new( offset_x + pos_offset, obstacle_y, offset_z, )), ), ( // bottom cuboid_bottom, // bottom transform Transform::from_translation(Vec3::new( offset_x, obstacle_y, offset_z - pos_offset, )), ), ]) } '┬' => { // Top T-junction // - 2 equal-sized cubes, one in each bottom corner // - 1 larger cuboid in the top center, spanning the entire width of the tile let cube = Cuboid::new(base_dim, obstacle_height, base_dim); let top = Cuboid::new(tile_size, obstacle_height, base_dim); Some(vec![ ( // bottom left cube cube, // bottom left cube transform Transform::from_translation(Vec3::new( offset_x - pos_offset, obstacle_y, offset_z - pos_offset, )), ), ( // bottom right cube cube, // bottom right cube transform Transform::from_translation(Vec3::new( offset_x + pos_offset, obstacle_y, offset_z - pos_offset, )), ), ( // top center cuboid top, // top center cuboid transform Transform::from_translation(Vec3::new( offset_x, obstacle_y, offset_z + pos_offset, )), ), ]) } '┴' => { // Bottom T-junction // - 2 equal-sized cubes, one in each top corner // - 1 larger cuboid in the bottom center, spanning the entire width of the tile let cube = Cuboid::new(base_dim, obstacle_height, base_dim); let bottom = Cuboid::new(tile_size, obstacle_height, base_dim); Some(vec![ ( // top left cube cube, // top left cube transform Transform::from_translation(Vec3::new( offset_x - pos_offset, obstacle_y, offset_z + pos_offset, )), ), ( // top right cube cube, // top right cube transform Transform::from_translation(Vec3::new( offset_x + pos_offset, obstacle_y, offset_z + pos_offset, )), ), ( // bottom center cuboid bottom, // bottom center cuboid transform Transform::from_translation(Vec3::new( offset_x, obstacle_y, offset_z - pos_offset, )), ), ]) } '├' => { // Right T-junction // - 2 equal-sized cubes, one in each right corner // - 1 larger cuboid in the left center, spanning the entire height of the tile let cube = Cuboid::new(base_dim, obstacle_height, base_dim); let left = Cuboid::new(base_dim, obstacle_height, tile_size); Some(vec![ ( // top right cube cube, // top right cube transform Transform::from_translation(Vec3::new( offset_x + pos_offset, obstacle_y, offset_z - pos_offset, )), ), ( // bottom right cube cube, // bottom right cube transform Transform::from_translation(Vec3::new( offset_x + pos_offset, obstacle_y, offset_z + pos_offset, )), ), ( // left center cuboid left, // left center cuboid transform Transform::from_translation(Vec3::new( offset_x - pos_offset, obstacle_y, offset_z, )), ), ]) } '┤' => { // Left T-junction // - 2 equal-sized cubes, one in each left corner // - 1 larger cuboid in the right center, spanning the entire height of the tile let cube = Cuboid::new(base_dim, obstacle_height, base_dim); let right = Cuboid::new(base_dim, obstacle_height, tile_size); Some(vec![ ( // top left cube cube, // top left cube transform Transform::from_translation(Vec3::new( offset_x - pos_offset, obstacle_y, offset_z - pos_offset, )), ), ( // bottom left cube cube, // bottom left cube transform Transform::from_translation(Vec3::new( offset_x - pos_offset, obstacle_y, offset_z + pos_offset, )), ), ( // right center cuboid right, // right center cuboid transform Transform::from_translation(Vec3::new( offset_x + pos_offset, obstacle_y, offset_z, )), ), ]) } '┼' => { // 4-way intersection // - 4 equal-sized cubes, one in each corner let cube = Cuboid::new(base_dim, obstacle_height, base_dim); Some(vec![ ( // top left cube, // top left transform Transform::from_translation(Vec3::new( offset_x - pos_offset, obstacle_y, offset_z - pos_offset, )), ), ( // top right cube, // top right transform Transform::from_translation(Vec3::new( offset_x + pos_offset, obstacle_y, offset_z - pos_offset, )), ), ( // bottom left cube, // bottom left transform Transform::from_translation(Vec3::new( offset_x - pos_offset, obstacle_y, offset_z + pos_offset, )), ), ( // bottom right cube, // bottom right transform Transform::from_translation(Vec3::new( offset_x + pos_offset, obstacle_y, offset_z + pos_offset, )), ), ]) } ' ' => { // Filled space // - 1 larger cuboid, spanning the entire tile let cuboid = Cuboid::new(tile_size, obstacle_height, tile_size); Some(vec![( cuboid, Transform::from_translation(Vec3::new(offset_x, obstacle_y, offset_z)), )]) } _ => None, } { for (cuboid, transform) in &obstacle_information { let entity = commands .spawn(( PbrBundle { mesh: meshes.add(*cuboid), transform: *transform, material: materials.obstacle.clone(), visibility: if config.visualisation.draw.generated_map { Visibility::Visible } else { Visibility::Hidden }, ..Default::default() }, TileCoordinates::new(x, y), ObstacleMarker, bevy_mod_picking::PickableBundle::default(), On::<Pointer<Click>>::send_event::<events::ObstacleClickedOn>(), // TODO: add on click handler )) .id(); colliders.push( Some(entity), Isometry2::new( Vector2::new(transform.translation.x, transform.translation.z), na::zero(), ), Arc::new(Into::<shape::Cuboid>::into(*cuboid)), ); } } } } colliders } /// **Bevy** [`Update`] _system_. /// Shows or hides the generated map based on event from [`DrawSettingsEvent`]. /// - If `DrawSettingsEvent` is `ShowGeneratedMap`, all generated map entities' /// visibility is changed according to the `DrawSettingsEvent.draw` boolean /// field fn show_or_hide_generated_map( mut evr_draw_settings: EventReader<DrawSettingsEvent>, mut query: Query<&mut Visibility, With<ObstacleMarker>>, ) { for event in evr_draw_settings.read() { if matches!(event.setting, DrawSetting::GeneratedMap) { for mut visibility in &mut query { *visibility = if event.draw { Visibility::Visible } else { Visibility::Hidden }; } } } }
412
0.954181
1
0.954181
game-dev
MEDIA
0.514981
game-dev,graphics-rendering
0.96052
1
0.96052
moai/moai-beta
1,017
samples/android/app-backbutton/main.lua
---------------------------------------------------------------- -- Copyright (c) 2010-2011 Zipline Games, Inc. -- All Rights Reserved. -- http://getmoai.com ---------------------------------------------------------------- print ( "hello, Android!" ) function onBackButtonPressed () print ( "onBackButtonPressed: " ) -- Return true if you want to override the back button press and prevent the system from handling it. return true end MOAIApp.setListener ( MOAIApp.BACK_BUTTON_PRESSED, onBackButtonPressed ) ---------------------------------------------------------------- MOAISim.openWindow ( "test", 320, 480 ) viewport = MOAIViewport.new () viewport:setSize ( 320, 480 ) viewport:setScale ( 320, 480 ) layer = MOAILayer2D.new () layer:setViewport ( viewport ) MOAISim.pushRenderPass ( layer ) gfxQuad = MOAIGfxQuad2D.new () gfxQuad:setTexture ( "moai.png" ) gfxQuad:setRect ( -64, -64, 64, 64 ) prop = MOAIProp2D.new () prop:setDeck ( gfxQuad ) layer:insertProp ( prop ) prop:moveRot ( 180, 1.0 )
412
0.697991
1
0.697991
game-dev
MEDIA
0.673584
game-dev,graphics-rendering
0.675052
1
0.675052
Keriils/NH-Utilities
1,187
src/main/java/com/xir/NHUtilities/common/recipes/TCRecipes/ArcaneCraftingRecipes.java
package com.xir.NHUtilities.common.recipes.TCRecipes; import java.util.HashMap; import net.minecraft.item.ItemStack; import com.xir.NHUtilities.common.api.enums.NHUItemList; import com.xir.NHUtilities.utils.TcText; import gregtech.api.enums.ItemList; import gregtech.api.enums.Materials; import gregtech.api.enums.OrePrefixes; import gregtech.api.util.GTOreDictUnificator; import thaumcraft.api.ThaumcraftApi; import thaumcraft.common.config.ConfigItems; public class ArcaneCraftingRecipes { public static HashMap<String, Object> ArcaneCraftingRecipes = new HashMap<>(); public static void run() { ArcaneCraftingRecipes.put( TcText.thaumicEBF, ThaumcraftApi.addArcaneCraftingRecipe( TcText.thaumicEBF.toUpperCase(), NHUItemList.TCBlastFurnace.get(1), TcText.aThaumicEbf, new Object[] { "aaa", "bcb", "dbd", 'a', ItemList.Machine_Multi_BlastFurnace.get(1L), 'b', ItemList.Field_Generator_LV.get(1L), 'c', new ItemStack(ConfigItems.itemFocusFire, 1), 'd', GTOreDictUnificator.get(OrePrefixes.wireGt16, Materials.Kanthal, 1L) })); } }
412
0.909269
1
0.909269
game-dev
MEDIA
0.967255
game-dev
0.921121
1
0.921121
Battledrake/SyntyEditorTools
10,122
Assets/BattleDrakeStudios/ModularCharacterEditor/Editor/ModularSetupWizard.cs
using UnityEngine; using UnityEditor; namespace BattleDrakeStudios.ModularCharacters { public class ModularSetupWizard : EditorWindow { private enum SetupState { SelectGameObject, SelectExisting, SelectGenderOption, SelectMaterialOption, SetupDuplicateMaterial, SetupExistingMaterial, Ready } private ModularCharacterManager characterManager; private SetupState currentState = SetupState.SelectGameObject; private bool isExistingCharacter; private Gender characterGender; private Material characterMat; private string materialName; private bool isNewMaterial; [MenuItem("BattleDrakeStudios/ModularCharacter/SetupWizard")] public static void ShowWizard() { ModularSetupWizard wizardWindow = GetWindow<ModularSetupWizard>(); wizardWindow.titleContent = new GUIContent("Setup Wizard"); wizardWindow.maxSize = new Vector2(400.0f, 200.0f); wizardWindow.minSize = wizardWindow.maxSize; wizardWindow.autoRepaintOnSceneChange = true; wizardWindow.Show(); } private void OnSelectionChange() { if (Selection.activeGameObject != null) { characterManager = Selection.activeGameObject.GetComponent<ModularCharacterManager>(); if (characterManager != null) { isExistingCharacter = false; isNewMaterial = false; currentState = SetupState.SelectExisting; } else currentState = SetupState.SelectGameObject; } Repaint(); } private void OnInspectorUpdate() { if (Selection.activeGameObject != null) { if (characterManager == null) { characterManager = Selection.activeGameObject.GetComponent<ModularCharacterManager>(); if (characterManager != null) currentState = SetupState.SelectExisting; else currentState = SetupState.SelectGameObject; Repaint(); } if (currentState == SetupState.SelectGameObject) { characterManager = Selection.activeGameObject.GetComponent<ModularCharacterManager>(); if (characterManager != null) currentState = SetupState.SelectExisting; Repaint(); } } } private void OnGUI() { if (Selection.activeGameObject == null) return; if (characterManager != null) if (characterManager.IsInitialized) { GUILayout.Label("Character is initialized!"); return; } switch (currentState) { case SetupState.SelectGameObject: if (characterManager == null) { GUILayout.BeginVertical(); GUILayout.Label("Please select a gameobject with the ModularManager script attached."); GUILayout.Label("Add one to selected gameobject?"); if (GUILayout.Button("Add ModularManager Component")) { Selection.activeGameObject.AddComponent<ModularCharacterManager>(); currentState = SetupState.SelectExisting; } GUILayout.EndVertical(); } break; case SetupState.SelectExisting: GUILayout.BeginVertical(); GUILayout.Label("Is this a new or existing character?"); GUILayout.BeginHorizontal(); SetIsExisting(); GUILayout.EndHorizontal(); GUILayout.EndVertical(); break; case SetupState.SelectGenderOption: GUILayout.BeginVertical(); GUILayout.Label("Is it a male or female? (You can change this in the editor later)"); GUILayout.BeginHorizontal(); SetCharacterGender(); GUILayout.EndHorizontal(); GUILayout.EndVertical(); break; case SetupState.SelectMaterialOption: GUILayout.BeginVertical(); GUILayout.Label("Use existing material or create duplicate?"); GUILayout.BeginHorizontal(); if (GUILayout.Button("Create Duplicate")) currentState = SetupState.SetupDuplicateMaterial; else if (GUILayout.Button("Use Existing")) { currentState = SetupState.SetupExistingMaterial; } GUILayout.EndHorizontal(); GUILayout.EndVertical(); break; case SetupState.SetupDuplicateMaterial: GUILayout.BeginVertical(); GUILayout.Label("Please insert the material to dupliate"); characterMat = EditorGUILayout.ObjectField(characterMat, typeof(Material), false) as Material; GUILayout.Label("Please enter a name for the duplicate material."); GUILayout.Label("(saves to: BattleDrakeStudios/ModularCharacterEditor/Materials"); materialName = GUILayout.TextField(materialName); if (!string.IsNullOrEmpty(materialName) && characterMat != null) { if (GUILayout.Button("Continue")) { characterMat = new Material(characterMat); characterMat.name = materialName; isNewMaterial = true; currentState = SetupState.Ready; } } GUILayout.EndVertical(); break; case SetupState.SetupExistingMaterial: GUILayout.BeginVertical(); GUILayout.Label("Please insert the desired material"); characterMat = EditorGUILayout.ObjectField(characterMat, typeof(Material), false) as Material; if (characterMat != null) { if (GUILayout.Button("Continue")) { currentState = SetupState.Ready; } } if (GUILayout.Button("Return")) currentState = SetupState.SelectMaterialOption; break; case SetupState.Ready: GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); GUILayout.Label("Character: "); if (isExistingCharacter) GUILayout.Label("Existing"); else GUILayout.Label("New"); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Gender: "); if (characterGender == Gender.Male) GUILayout.Label("Male"); else GUILayout.Label("Female"); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Material: "); GUILayout.Label(characterMat.name); GUILayout.EndHorizontal(); if (GUILayout.Button("Commit")) { CommitChanges(false); } if (GUILayout.Button("Commit and Show Editor")) { CommitChanges(true); } if (GUILayout.Button("Reset")) { currentState = SetupState.SelectExisting; isExistingCharacter = false; isNewMaterial = false; } GUILayout.EndVertical(); break; } } private void SetIsExisting() { if (GUILayout.Button("New")) { isExistingCharacter = false; currentState = SetupState.SelectGenderOption; } else if (GUILayout.Button("Existing")) { isExistingCharacter = true; currentState = SetupState.SelectGenderOption; } } private void SetCharacterGender() { if (GUILayout.Button("Male")) { characterGender = Gender.Male; currentState = SetupState.SelectMaterialOption; } else if (GUILayout.Button("Female")) { characterGender = Gender.Female; currentState = SetupState.SelectMaterialOption; } } private void CommitChanges(bool openEditor) { if (isNewMaterial) { if(!AssetDatabase.IsValidFolder("Assets/BattleDrakeStudios/ModularCharacterEditor/Materials")) { AssetDatabase.CreateFolder("Assets/BattleDrakeStudios/ModularCharacterEditor", "Materials"); } AssetDatabase.CreateAsset(characterMat, "Assets/BattleDrakeStudios/ModularCharacterEditor/Materials/" + materialName + ".mat"); } if (isExistingCharacter) { characterManager.SetupExistingCharacter(characterGender, characterMat); } else { characterManager.SetupNewCharacter(characterGender, characterMat); } if (openEditor) { ModularCharacterEditor.ShowWindow(); } isExistingCharacter = false; isNewMaterial = false; } } }
412
0.704143
1
0.704143
game-dev
MEDIA
0.926247
game-dev
0.790668
1
0.790668
AmProsius/gothic-1-community-patch
1,810
scriptbase/_work/Data/Scripts/System/Menu/Menu_Misc.d
// ********************************************************************* // leave game menu // ********************************************************************* INSTANCE MENU_LEAVE_GAME(C_MENU_DEF) { backpic = MENU_BACK_PIC; items[0] = "MENUITEM_LEAVE_GAME_HEADLINE"; items[1] = "MENUITEM_LEAVE_GAME_YES"; items[2] = "MENUITEM_LEAVE_GAME_NO"; defaultOutGame = 2; // NEWGAME defaultInGame = 2; // SAVEGAME flags = flags | MENU_SHOW_INFO; }; INSTANCE MENUITEM_LEAVE_GAME_HEADLINE(C_MENU_ITEM_DEF) { text[0] = "Really quit Gothic?"; type = MENU_ITEM_TEXT; // Position und Dimension posx = 0; posy = 3400; dimx = 8100; dimy = 500; // Weitere Eigenschaften flags = IT_CHROMAKEYED|IT_TRANSPARENT|IT_MOVEABLE|IT_TXT_CENTER; }; INSTANCE MENUITEM_LEAVE_GAME_YES(C_MENU_ITEM_DEF) { backpic = MENU_ITEM_BACK_PIC; text[0] = "Yes"; text[1] = "Yes, I want to quit Gothic."; // Kommentar // Position und Dimension posx = 0; posy = 4400; dimx = 8100; dimy = 500; // Aktionen onSelAction[0] = SEL_ACTION_CLOSE; onSelAction_S[0]= "LEAVE_GAME"; // Weitere Eigenschaften flags = IT_CHROMAKEYED|IT_TRANSPARENT|IT_MOVEABLE|IT_SELECTABLE|IT_TXT_CENTER; }; INSTANCE MENUITEM_LEAVE_GAME_NO(C_MENU_ITEM_DEF) { backpic = MENU_ITEM_BACK_PIC; text[0] = "No"; text[1] = "No, I want to play on."; // Kommentar // Position und Dimension posx = 0; posy = 5000; dimx = 8100; dimy = 500; // Weitere Eigenschaften flags = IT_CHROMAKEYED|IT_TRANSPARENT|IT_MOVEABLE|IT_SELECTABLE|IT_TXT_CENTER; };
412
0.728985
1
0.728985
game-dev
MEDIA
0.947706
game-dev
0.681069
1
0.681069
reverseengineeringer/com.estrongs.android.pop
4,189
src/com/dianxinos/library/b/b/b/d.java
package com.dianxinos.library.b.b.b; import com.dianxinos.library.b.c.i; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; public class d extends a { private char[] d; private final com.dianxinos.library.b.b.c.a e; private String f; public d(String paramString, com.dianxinos.library.b.b.c.a parama, char[] paramArrayOfChar) { f = paramString; d = paramArrayOfChar; e = parama; } private SecretKey a(byte[] paramArrayOfByte) { return new SecretKeySpec(paramArrayOfByte, "AES"); } private static SecretKey a(char[] paramArrayOfChar, byte[] paramArrayOfByte) { try { paramArrayOfChar = new PBEKeySpec(paramArrayOfChar, paramArrayOfByte, 37, 128); paramArrayOfChar = new SecretKeySpec(SecretKeyFactory.getInstance("PBEWITHSHAAND256BITAES-CBC-BC").generateSecret(paramArrayOfChar).getEncoded(), "AES"); return paramArrayOfChar; } catch (Exception paramArrayOfChar) { paramArrayOfChar.printStackTrace(); } return null; } private SecretKey c() { try { Object localObject = KeyGenerator.getInstance("AES"); ((KeyGenerator)localObject).init(128); localObject = ((KeyGenerator)localObject).generateKey(); return (SecretKey)localObject; } catch (Exception localException) {} return null; } public boolean a() { Object localObject3 = b.a(f + "tb295d117135a9763da282e7dae73a5ca7d3e5b11"); Object localObject1 = e.a((String)localObject3); if (localObject1 == null) {} for (int i = 1; i != 0; i = 0) { localObject2 = b.a(32); localObject1 = localObject2; if (e.a((String)localObject3, (byte[])localObject2) > 0L) { break; } return false; } localObject1 = a(d, (byte[])localObject1); if (localObject1 == null) { return false; } Object localObject2 = a("AES/CBC/PKCS5Padding"); localObject3 = a("AES/CBC/PKCS5Padding"); if ((localObject2 == null) || (localObject3 == null)) { return false; } a((SecretKey)localObject1, (Cipher)localObject2, (Cipher)localObject3); c.a(d); d = null; return true; } public e b(String paramString) { i.a(); Object localObject = b.a(paramString + "ta727348c8aa7823aa5f18dc02a066498bfd8b132"); paramString = e.a((String)localObject); if (paramString == null) { paramString = c(); if (paramString == null) { return null; } byte[] arrayOfByte = a(paramString.getEncoded(), b.a((String)localObject, 16)); if (arrayOfByte == null) { return null; } if (e.a((String)localObject, arrayOfByte) <= 0L) { return null; } } else { paramString = b(paramString, b.a((String)localObject, 16)); if (paramString == null) { return null; } localObject = a(paramString); paramString = (String)localObject; if (localObject == null) { return null; } } paramString = new e(paramString); if (!paramString.a()) { return null; } return paramString; } public boolean b() { Object localObject = b.a(f + "t26a26ebfab9b4e5f9f39784402706fd6efdf7081"); byte[] arrayOfByte = e.a((String)localObject); int i; if (arrayOfByte == null) { i = 1; if (i == 0) { break label83; } arrayOfByte = a(com.dianxinos.library.b.b.c.c.a(1), b.a((String)localObject, 16)); if (e.a((String)localObject, arrayOfByte) <= 0L) { break label81; } } label81: label83: do { return true; i = 0; break; return false; localObject = b(arrayOfByte, b.a((String)localObject, 16)); if (localObject == null) { return false; } } while (com.dianxinos.library.b.b.c.c.a((byte[])localObject) == 1); return false; } } /* Location: * Qualified Name: com.dianxinos.library.b.b.b.d * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
412
0.917873
1
0.917873
game-dev
MEDIA
0.447146
game-dev
0.900041
1
0.900041
Joshua-F/osrs-dumps
10,968
script/[proc,toplevel_redraw].cs2
// 907 [proc,toplevel_redraw](component $component0, enum $enum1) if (%hotkey_cannot_close_sidepanel = 1) { if_setonkey("toplevel_keypress(event_keycode, $enum1, false)", $component0); } else { if_setonkey("toplevel_keypress(event_keycode, $enum1, true)", $component0); } ~toplevel_resize($component0, $enum1); def_component $component2 = enum(component, component, $enum1, toplevel_osrs_stretch:map_container); if ($component2 ! null) { if_sethide(~int_to_bool(%cutscene_status), $component2); } $component2 = enum(component, component, $enum1, toplevel_osrs_stretch:compassclick); if ($component2 ! null) { if (%cutscene_status = 1 | %fov_clamp ! 0) { if_sethide(true, $component2); } else { if_sethide(false, $component2); } } def_component $component3 = enum(component, component, $enum1, toplevel_osrs_stretch:overlay_atmosphere); def_int $int4 = 0; def_int $int5 = 0; $int5, $int4 = viewport_getfov; if (%camera_zoom_small > 0 & %camera_zoom_big > 0 & ($int5 ! %camera_zoom_small | $int4 ! %camera_zoom_big)) { ~camera_do_zoom(%camera_zoom_small, %camera_zoom_big); } if_setonscrollwheel("camera_zoom(event_mousey)", $component3); if_setpinch(true, $component3); def_int $int6 = calc(%flashside - 1); def_component $component7 = enum(int, component, enum_1139, $int6); def_component $component8 = enum(int, component, enum_1138, $int6); if ($component7 ! null & $component8 ! null) { $component7 = enum(component, component, $enum1, $component7); $component8 = enum(component, component, $enum1, $component8); if ($component7 ! null & $component8 ! null) { if_setontimer("toplevel_timer($component7, $component8, enum(component, int, enum_5619, $component7))", $component0); } else { if_setontimer(null, $component0); } } else { if_setontimer(null, $component0); } ~toplevel_sidebuttons_enable($enum1); def_component $component9 = enum(int, component, enum_1138, 2); $component7 = enum(int, component, enum_1139, 2); $component9, $component7 = enum(component, component, $enum1, $component9), enum(component, component, $enum1, $component7); def_struct $struct10 = null; if ($component9 ! null & $component7 ! null) { switch_int (%side_journal_tab) { case default : if_setop(1, "Character Summary", $component9); if_setgraphic("sideicons_interface,30", $component7); case 1 : if_setop(1, "Quest List", $component9); if_setgraphic("sideicons_interface,2", $component7); case 2 : if_setop(1, "Achievement Diaries", $component9); if_setgraphic("sideicons_interface,16", $component7); case 3 : if_setop(1, "Adventure Paths", $component9); if_setgraphic("sideicons_interface,23", $component7); case 4 : $struct10 = enum(int, struct, enum_2670, %league_type); if_setop(1, "Leagues", $component9); if ($struct10 ! null) { if_setgraphic(struct_param($struct10, param_149), $component7); } else { if_setgraphic("sideicons_interface,66", $component7); } } } $component7 = enum(int, component, enum_1139, 5); $component7 = enum(component, component, $enum1, $component7); if ($component7 ! null) { switch_int (%prayerbook) { case 0 : if_setgraphic("sideicons_interface,5", $component7); case 1 : if_setgraphic("sideicons_interface,56", $component7); case default : if_setgraphic("sideicons_interface,5", $component7); } } $component9 = enum(int, component, enum_1138, 5); $component9 = enum(component, component, $enum1, $component9); if ($component9 ! null) { if (~on_mobile = true) { if_setop(2, "", $component9); } else if (%prayer_hidefilterbutton = 1) { if_setop(2, "Enable prayer filtering", $component9); } else { if_setop(2, "Disable prayer filtering", $component9); } } $component7 = enum(int, component, enum_1139, 6); $component7 = enum(component, component, $enum1, $component7); if ($component7 ! null) { switch_int (%spellbook) { case 1 : if_setgraphic("sideicons_interface,19", $component7); case 2 : if_setgraphic("sideicons_interface,20", $component7); case 3 : if_setgraphic("sideicons_interface,21", $component7); case default : if_setgraphic("sideicons_interface,6", $component7); } } $component9 = enum(int, component, enum_1138, 6); $component9 = enum(component, component, $enum1, $component9); if ($component9 ! null) { if (~on_mobile = true) { if_setop(2, "", $component9); } else if (%magic_spellbook_hidefilterbutton = 1) { if_setop(2, "Enable spell filtering", $component9); } else { if_setop(2, "Disable spell filtering", $component9); } } $component9 = enum(int, component, enum_1138, 9); $component7 = enum(int, component, enum_1139, 9); $component9, $component7 = enum(component, component, $enum1, $component9), enum(component, component, $enum1, $component7); if ($component9 ! null & $component7 ! null) { if (%friends_panel = 0) { if_setop(1, "Friends List", $component9); if_setgraphic("sideicons_interface,8", $component7); } else { if_setop(1, "Ignore List", $component9); if_setgraphic("sideicons_interface,9", $component7); } } $component9, $component7 = enum(int, component, enum_1138, 7), enum(int, component, enum_1139, 7); $component9, $component7 = enum(component, component, $enum1, $component9), enum(component, component, $enum1, $component7); if ($component9 ! null) { if_setop(1, enum(int, string, enum_3839, %side_channels_tab_selected), $component9); } if ($component7 ! null) { if_setgraphic(enum(int, graphic, enum_3841, %side_channels_tab_selected), $component7); if_setonvartransmit("script5303($component7, $component9){magic_carpet_var}", $component7); } $component7 = enum(component, component, $enum1, toplevel_osrs_stretch:side_background); if ($component7 ! null) { if (%side_transparency = 1) { if_setgraphic(tradebacking_dark, $component7); if_settrans(0, $component7); } else { if_setgraphic(tradebacking_light, $component7); if_settrans(150, $component7); } } $component7 = enum(component, component, $enum1, toplevel_osrs_stretch:multiway_icon); if ($component7 ! null) { if ($enum1 = enum_1745) { ~script3506($component7); } else if ($enum1 = enum_1129) { if (%gravestone_duration > 0) { if_setposition(15, 17, ^setpos_abs_right, ^setpos_abs_bottom, $component7); } else { if_setposition(15, 13, ^setpos_abs_right, ^setpos_abs_bottom, $component7); } } if (%multiway_indicator = 1 & %cutscene_status = 0) { if_setgraphic(overlay_multiway, $component7); if_sethide(false, $component7); } else if (%singleway_plus_indicator = 1 & %cutscene_status = 0) { if_setgraphic(overlay_singleway_plus, $component7); if_sethide(false, $component7); } else if (%td_multiway_indicator > 0 & %cutscene_status = 0) { switch_int (%td_multiway_indicator) { case 1 : if_setgraphic("overlay_td_multiway,0", $component7); case 2 : if_setgraphic("overlay_td_multiway,1", $component7); case 3 : if_setgraphic("overlay_td_multiway,2", $component7); } if_sethide(false, $component7); } else { if_sethide(true, $component7); } } $component2 = enum(component, component, $enum1, toplevel_osrs_stretch:buff_bar); if (%buff_bar_hidden = 0 & %cutscene_status = 0) { if_sethide(false, $component2); } else { if_sethide(true, $component2); } %buff_bar_dodger_update = clientclock; $component2 = enum(component, component, $enum1, toplevel_osrs_stretch:pm_container); if (%cutscene_status = 0) { if_sethide(false, $component2); } else { if_sethide(true, $component2); } $component2 = enum(component, component, $enum1, toplevel_osrs_stretch:chat_container); if ($enum1 = enum_1745) { if (%cutscene_status = 1 & %fov_clamp = 3) { if_setposition(0, 5, ^setpos_abs_centre, ^setpos_abs_bottom, $component2); } else { if_setposition(0, 0, ^setpos_abs_left, ^setpos_abs_top, $component2); } } else if ($enum1 = enum_1130 | $enum1 = enum_1131) { if (%cutscene_status = 1) { if (%fov_clamp = 3) { if_setposition(0, 0, ^setpos_abs_centre, ^setpos_abs_bottom, $component2); } else { if_setposition(0, calc(23 * -1), ^setpos_abs_left, ^setpos_abs_bottom, $component2); } } else { if_setposition(0, 0, ^setpos_abs_left, ^setpos_abs_bottom, $component2); } } if ($enum1 ! enum_1129) { if (~script4138 = true) { ~script4135($enum1, true); } else { ~script4135($enum1, false); } } if ($enum1 = enum_1745) { if (%cutscene_status = 0) { if_sethide(false, toplevel_osm:wifi); if_sethide(false, toplevel_osm:battery); } else { if_sethide(true, toplevel_osm:wifi); if_sethide(true, toplevel_osm:battery); } } $component2 = enum(component, component, $enum1, toplevel_osrs_stretch:stat_boosts_hud); if (%cutscene_status = 0) { if_sethide(false, $component2); } else { if_sethide(true, $component2); } $component2 = enum(component, component, $enum1, toplevel_osrs_stretch:helper); if (%cutscene_status = 0) { if_sethide(false, $component2); } else { if_sethide(true, $component2); } $component2 = enum(component, component, $enum1, toplevel_osrs_stretch:hpbar_hud); if (%cutscene_status = 0) { if_sethide(false, $component2); } else { if_sethide(true, $component2); } if (%mousecam_disabled = 1) { setmousecam(false); } else { setmousecam(true); } ~shiftclick_toggle; if (%followerops_deprioritised = 1) { setfolloweropslowpriority(true); } else { setfolloweropslowpriority(false); } ~mouseover_ops; $component2 = enum(component, component, $enum1, toplevel_osrs_stretch:mouseover); if (%cutscene_status = 0) { if_sethide(false, $component2); } else { if_sethide(true, $component2); } if (%option_audio_override = 0) { ~script7109; ~script2475; ~script3643; ~script3644; } ~logout_timer_notifier; ~script6682($enum1); ~script5355($enum1); $component2 = enum(component, component, $enum1, toplevel_osm:side_left_chat); if ($component2 ! null) { if (%cutscene_status = 0) { if_sethide(false, $component2); } else { if_sethide(true, $component2); } } $component2 = enum(component, component, $enum1, toplevel_osm:hotkeys); if ($component2 ! null) { if (%cutscene_status = 0) { if_sethide(false, $component2); } else { if_sethide(true, $component2); } } ~script7572;
412
0.92583
1
0.92583
game-dev
MEDIA
0.656631
game-dev
0.958011
1
0.958011
MohistMC/Youer
6,581
src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartMobSpawner.java
package org.bukkit.craftbukkit.entity; import com.google.common.base.Preconditions; import java.util.Collection; import java.util.List; import java.util.Optional; import net.minecraft.util.RandomSource; import net.minecraft.util.random.SimpleWeightedRandomList; import net.minecraft.world.entity.vehicle.MinecartSpawner; import net.minecraft.world.level.SpawnData; import org.bukkit.block.spawner.SpawnRule; import org.bukkit.block.spawner.SpawnerEntry; import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.block.CraftCreatureSpawner; import org.bukkit.entity.EntitySnapshot; import org.bukkit.entity.EntityType; import org.bukkit.entity.minecart.SpawnerMinecart; public final class CraftMinecartMobSpawner extends CraftMinecart implements SpawnerMinecart, org.bukkit.craftbukkit.spawner.PaperSharedSpawnerLogic { // Paper - more spawner API CraftMinecartMobSpawner(CraftServer server, MinecartSpawner entity) { super(server, entity); } @Override public EntityType getSpawnedType() { SpawnData spawnData = getHandle().getSpawner().nextSpawnData; if (spawnData == null) { return null; } Optional<net.minecraft.world.entity.EntityType<?>> type = net.minecraft.world.entity.EntityType.by(spawnData.getEntityToSpawn()); return type.map(CraftEntityType::minecraftToBukkit).orElse(null); } @Override public void setSpawnedType(EntityType entityType) { if (entityType == null) { getHandle().getSpawner().spawnPotentials = SimpleWeightedRandomList.empty(); // need clear the spawnPotentials to avoid nextSpawnData being replaced later getHandle().getSpawner().nextSpawnData = new SpawnData(); return; } Preconditions.checkArgument(entityType != EntityType.UNKNOWN, "Can't spawn EntityType %s from mob spawners!", entityType); RandomSource rand = getHandle().level().getRandom(); getHandle().getSpawner().setEntityId(CraftEntityType.bukkitToMinecraft(entityType), getHandle().level(), rand, getHandle().blockPosition()); } @Override public EntitySnapshot getSpawnedEntity() { SpawnData spawnData = getHandle().getSpawner().nextSpawnData; if (spawnData == null) { return null; } return CraftEntitySnapshot.create(spawnData.getEntityToSpawn()); } @Override public void setSpawnedEntity(EntitySnapshot snapshot) { CraftCreatureSpawner.setSpawnedEntity(getHandle().getSpawner(), snapshot, null, null); } @Override public void setSpawnedEntity(SpawnerEntry spawnerEntry) { Preconditions.checkArgument(spawnerEntry != null, "Entry cannot be null"); CraftCreatureSpawner.setSpawnedEntity(getHandle().getSpawner(), spawnerEntry.getSnapshot(), spawnerEntry.getSpawnRule(), spawnerEntry.getEquipment()); } @Override public void addPotentialSpawn(EntitySnapshot snapshot, int weight, SpawnRule spawnRule) { CraftCreatureSpawner.addPotentialSpawn(getHandle().getSpawner(), snapshot, weight, spawnRule, null); } @Override public void addPotentialSpawn(SpawnerEntry spawnerEntry) { Preconditions.checkArgument(spawnerEntry != null, "Entry cannot be null"); CraftCreatureSpawner.addPotentialSpawn(getHandle().getSpawner(), spawnerEntry.getSnapshot(), spawnerEntry.getSpawnWeight(), spawnerEntry.getSpawnRule(), spawnerEntry.getEquipment()); } @Override public void setPotentialSpawns(Collection<SpawnerEntry> entries) { CraftCreatureSpawner.setPotentialSpawns(getHandle().getSpawner(), entries); } @Override public List<SpawnerEntry> getPotentialSpawns() { return CraftCreatureSpawner.getPotentialSpawns(getHandle().getSpawner()); } @Override public int getDelay() { return getHandle().getSpawner().spawnDelay; } @Override public void setDelay(int delay) { getHandle().getSpawner().spawnDelay = delay; } @Override public int getMinSpawnDelay() { return getHandle().getSpawner().minSpawnDelay; } @Override public void setMinSpawnDelay(int spawnDelay) { Preconditions.checkArgument(spawnDelay <= getMaxSpawnDelay(), "Minimum Spawn Delay must be less than or equal to Maximum Spawn Delay"); getHandle().getSpawner().minSpawnDelay = spawnDelay; } @Override public int getMaxSpawnDelay() { return getHandle().getSpawner().maxSpawnDelay; } @Override public void setMaxSpawnDelay(int spawnDelay) { Preconditions.checkArgument(spawnDelay > 0, "Maximum Spawn Delay must be greater than 0."); Preconditions.checkArgument(spawnDelay >= getMinSpawnDelay(), "Maximum Spawn Delay must be greater than or equal to Minimum Spawn Delay"); getHandle().getSpawner().maxSpawnDelay = spawnDelay; } @Override public int getMaxNearbyEntities() { return getHandle().getSpawner().maxNearbyEntities; } @Override public void setMaxNearbyEntities(int maxNearbyEntities) { getHandle().getSpawner().maxNearbyEntities = maxNearbyEntities; } @Override public int getSpawnCount() { return getHandle().getSpawner().spawnCount; } @Override public void setSpawnCount(int count) { getHandle().getSpawner().spawnCount = count; } @Override public int getRequiredPlayerRange() { return getHandle().getSpawner().requiredPlayerRange; } @Override public void setRequiredPlayerRange(int requiredPlayerRange) { getHandle().getSpawner().requiredPlayerRange = requiredPlayerRange; } @Override public int getSpawnRange() { return getHandle().getSpawner().spawnRange; } @Override public void setSpawnRange(int spawnRange) { getHandle().getSpawner().spawnRange = spawnRange; } @Override public MinecartSpawner getHandle() { return (MinecartSpawner) entity; } @Override public String toString() { return "CraftMinecartMobSpawner"; } // Paper start - more spawner API @Override public net.minecraft.world.level.BaseSpawner getSpawner() { return this.getHandle().getSpawner(); } @Override public net.minecraft.world.level.Level getInternalWorld() { return this.getHandle().level(); } @Override public net.minecraft.core.BlockPos getInternalPosition() { return this.getHandle().blockPosition(); } // Paper end - more spawner API }
412
0.901486
1
0.901486
game-dev
MEDIA
0.981502
game-dev
0.78818
1
0.78818
reeseschultz/ReeseUnityDemos
5,972
Packages/com.reese.spatial/README.md
# Reese's DOTS Spatial Events [![Discord Shield](https://discordapp.com/api/guilds/732665868521177117/widget.png?style=shield)](https://discord.gg/CZ85mguYjK) Reactive entry, overlap and exit events in Burst-capable jobs. ## Import This requires Unity editor `2019.3` or greater. Copy one of the below Git URLs: * **HTTPS:** `https://github.com/reeseschultz/ReeseUnityDemos.git#spatial` * **SSH:** `git@github.com:reeseschultz/ReeseUnityDemos.git#spatial` Then go to `Window ⇒ Package Manager` in the editor. Press the `+` symbol in the top-left corner, and then click on `Add package from git URL`. Paste the text you copied and finally click `Add`. ## Concepts This package uses these concepts: 1. **Triggers** - Triggers react to overlapping activators. Entities with the `SpatialTrigger` component are processed as triggers. `SpatialTriggerAuthoring` is provided for convenience. 2. **Activators** - Activators activate overlapping triggers. Any activator that is currently overlapping a trigger is an **overlap**. Activators that enter a trigger are **entries**. Activators that exit a trigger are **exits**. Entities with the `SpatialActivator` component are processed as activators. `SpatialActivatorAuthoring` is provided for convenience. 3. **Tags** - Grouping of triggers and activators. Triggers and tags should both have a `DynamicBuffer` of the type `SpatialTag`. It's comprised of `FixedString128`s—these are the tags. When at least one tag of an activator matches that of a trigger, that trigger is considered activated (as long as collision filters permit)! A `DynamicBuffer` of type `SpatialEntry` is populated upon entry, and a `DynamicBuffer` of type `SpatialExit` is populated upon exit. Current overlaps are in a `DynamicBuffer` of type `SpatialOverlap`. Entries, exits and overlaps contain a value of `SpatialEvent`, including the activating entity and its associated tag. Be aware that `Unity.Physics` is used behind the scenes for efficiency. It uses a [bounding volume hierarchy](https://en.wikipedia.org/wiki/Bounding_volume_hierarchy) (BVH) to quickly detect collisions between collidable objects. What this means for you, the user, is that your activators and triggers **must** have colliders attached to them! This package will not work otherwise. ## Usage For the sake of example, we'll start by creating a `CatSystem` that handles spatial events for entities with a `Cat` component, a `SpatialTrigger` component, and, finally, a `PhysicsCollider` component (since that's the only way the spatial events package can detect collisions). ```csharp ... using Reese.Spatial; ... namespace YourNamespace { [UpdateAfter(typeof(SpatialStartSystem)), UpdateBefore(typeof(SpatialEndSystem))] partial class CatSystem : SystemBase { protected override void OnUpdate() { ... } } } ``` `[UpdateAfter(typeof(SpatialStartSystem)), UpdateBefore(typeof(SpatialEndSystem))]` is critically important! Your system needs to run between the `SpatialStartSystem` and `SpatialEndSystem`. Otherwise, things will not work! ### Overlaps To handle what is currently overlapping, add this block to the `OnUpdate` method: ```csharp Entities // Example handling of the overlap buffer. .WithAll<Cat, SpatialTrigger, PhysicsCollider>() .ForEach((in DynamicBuffer<SpatialOverlap> overlaps) => // Do NOT modify the buffer, hence the in keyword. { // There could be code here to process what currently overlaps in a given frame. }) .WithName("CatOverlapJob") .ScheduleParallel(); ``` ### Entries To handle entries, add this block to the `OnUpdate` method: ```csharp Entities // Example handling of the spatial entry buffer. .WithAll<Cat, SpatialTrigger, PhysicsCollider>() .WithChangeFilter<SpatialEntry>() // Allows us to process (only) new entries once. .ForEach((in DynamicBuffer<SpatialEntry> entries) => // Do NOT modify the buffer, hence the in keyword. { for (var i = entries.Length - 1; i >= 0; --i) // Traversing from the end of the buffer for performance reasons. { Debug.Log($"Entity {entries[i].Value.Activator.Index} is making me purr! Purrrrrrrr!"); } }) .WithName("CatEntryJob") .ScheduleParallel(); ``` If another entity enters the `Cat`'s bounds, purring ensues. ### Exits To handle exits, add this block to the `OnUpdate` method: ```csharp Entities // Example handling of the spatial exit buffer. .WithAll<Cat, SpatialTrigger, PhysicsCollider>() .WithChangeFilter<SpatialExit>() // Allows us to process (only) new exits once. .ForEach((in DynamicBuffer<SpatialExit> exits) => // Do NOT modify the buffer, hence the in keyword. { for (var i = exits.Length - 1; i >= 0; --i) // Traversing from the end of the buffer for performance reasons. { Debug.Log($"Entity {exits[i].Value.Activator.Index} making me meow for attention! MEEEOWWWWWWW!"); } }) .WithName("CatExitJob") .ScheduleParallel(); ``` Upon exit, the `Cat` meows for attention. ## Tips * See the working [CatSystem](https://github.com/reeseschultz/ReeseUnityDemos/blob/master/Assets/Scripts/Stranded/Cat/CatSystem.cs) in the [containing monorepo](https://github.com/reeseschultz/ReeseUnityDemos) that this example was modified from. That system is used in the `Stranded` demo, a concrete way to start learning and using this package and others! * If you want to handle different kinds of events per trigger, you would most likely want to check for existence of a component per entry or exit. To that end, you could use `GetComponentFromEntity`. * It is perfectly fine for an object to be *both* a trigger and activator (even though it may belong to the same tag as itself, self-activation is **not** possible). ## Contributing All contributions to this repository are licensed under [MIT](https://github.com/reeseschultz/ReeseUnityDemos/blob/master/LICENSE).
412
0.841496
1
0.841496
game-dev
MEDIA
0.544622
game-dev
0.739183
1
0.739183
uberto/pesticide
1,418
pesticide-examples/src/test/kotlin/com/ubertob/pesticide/examples/calculator/CalculatorActions.kt
package com.ubertob.pesticide.examples.calculator import com.ubertob.pesticide.core.* import java.util.concurrent.atomic.AtomicInteger fun allCalculatorActionss() = setOf( DomainOnlyCalculator(), FakeHttpCalculator() ) interface CalculatorActions : DomainActions<DdtProtocol> { fun addNumber(num: Int) fun subtractNumber(num: Int) fun getTotal(): Int fun startWithNumber(num: Int): CalculatorActions } class DomainOnlyCalculator : CalculatorActions { var tot = 0 override fun addNumber(num: Int) { tot += num } override fun subtractNumber(num: Int) { tot -= num } override fun getTotal(): Int = tot override fun startWithNumber(num: Int): CalculatorActions { tot = num return this } override val protocol = DomainOnly override fun prepare(): DomainSetUp = Ready } class FakeHttpCalculator : CalculatorActions { val tot = AtomicInteger(0) override fun addNumber(num: Int) { tot.getAndUpdate { it + num } } override fun subtractNumber(num: Int) { TODO("subtractNumber not implemented in HTTP yet") } override fun getTotal(): Int = tot.get() override fun startWithNumber(num: Int): CalculatorActions { tot.set(num) return this } override val protocol = Http("fake") override fun prepare(): DomainSetUp = Ready }
412
0.822694
1
0.822694
game-dev
MEDIA
0.225573
game-dev
0.954197
1
0.954197
mangoszero/server
4,257
src/shared/GameSystem/Grid.h
/** * MaNGOS is a full featured server for World of Warcraft, supporting * the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8 * * Copyright (C) 2005-2025 MaNGOS <https://www.getmangos.eu> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * World of Warcraft, and all World of Warcraft or Warcraft art, images, * and lore are copyrighted by Blizzard Entertainment, Inc. */ #ifndef MANGOS_GRID_H #define MANGOS_GRID_H #include "Platform/Define.h" #include "Policies/ThreadingModel.h" #include "TypeContainer.h" #include "TypeContainerVisitor.h" // forward declaration template<class A, class T, class O> class GridLoader; /** * @brief Grid is a logical segment of the game world represented inside MaNGOS. * * Grid is bind at compile time to a particular type of object which * we call it the object of interest. There are many types of loader, * specially, dynamic loader, static loader, or on-demand loader. There's * a subtle difference between dynamic loader and on-demand loader but * this is implementation specific to the loader class. From the * Grid's perspective, the loader meets its API requirement is suffice. */ template <typename ACTIVE_OBJECT, typename WORLD_CONTAINER, typename GRID_CONTAINER> class Grid { // allows the GridLoader to access its internals template<class A, class T, class O> friend class GridLoader; public: template<class SPECIFIC_OBJECT> /** * @brief an object of interested enters the grid * * @param obj * @return bool */ bool AddWorldObject(SPECIFIC_OBJECT* obj) { return i_worldContainer.template insert<SPECIFIC_OBJECT>(obj); } template<class SPECIFIC_OBJECT> /** * @brief an object of interested exits the grid * * @param obj * @return bool */ bool RemoveWorldObject(SPECIFIC_OBJECT* obj) { return i_worldContainer.template remove<SPECIFIC_OBJECT>(obj); } template<class SPECIFIC_OBJECT> /** * @brief Inserts a container type object into the grid. * * @param obj * @return bool */ bool AddGridObject(SPECIFIC_OBJECT* obj) { if (obj->IsActiveObject()) { m_activeGridObjects.insert(obj); } return i_gridContainer.template insert<SPECIFIC_OBJECT>(obj); } template<class SPECIFIC_OBJECT> /** * @brief Removes a container type object from the grid * * @param obj * @return bool */ bool RemoveGridObject(SPECIFIC_OBJECT* obj) { if (obj->IsActiveObject()) { m_activeGridObjects.erase(obj); } return i_gridContainer.template remove<SPECIFIC_OBJECT>(obj); } template<class T> void Visit(TypeContainerVisitor<T, GRID_CONTAINER>& visitor) { visitor.Visit(i_gridContainer); } template<class T> void Visit(TypeContainerVisitor<T, WORLD_CONTAINER>& visitor) { visitor.Visit(i_worldContainer); } size_t ActiveObjectsInGrid() const { return m_activeGridObjects.size() + i_worldContainer.template count<ACTIVE_OBJECT>(nullptr); } private: GRID_CONTAINER i_gridContainer; WORLD_CONTAINER i_worldContainer; std::set<void*> m_activeGridObjects; }; #endif
412
0.914069
1
0.914069
game-dev
MEDIA
0.477533
game-dev
0.786643
1
0.786643
mono/CocosSharp
12,891
src/Platform/CCContentManager.cs
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace CocosSharp { public class CCContentManager : ContentManager { #region Asset entry private class class AssetEntry { public readonly string AssetFileName; public readonly bool WeakReference; public readonly bool UseContentReader; object asset; #region Properties public object Asset { get { if (WeakReference) { if (((WeakReference)asset).IsAlive) { return ((WeakReference)asset).Target; } return null; } else { return asset; } } set { if (WeakReference) { asset = new WeakReference(value); } else { asset = value; } } } #endregion Properties #region Constructors public AssetEntry(object asset, string assetFileName, bool weakReference, bool useContentReader) { AssetFileName = assetFileName; WeakReference = weakReference; UseContentReader = useContentReader; Asset = asset; } #endregion Constructors } #endregion Asset entry private class public static CCContentManager SharedContentManager { get; internal set; } Dictionary<string, AssetEntry> loadedAssets; Dictionary<string, string> assetLookupDict = new Dictionary<string, string>(); Dictionary<Tuple<string, Type>, string> failedAssets = new Dictionary<Tuple<string, Type>, string>(); List<string> searchPaths = new List<string>(); List<string> searchResolutionsOrder = new List<string>(); #region Constructors public CCContentManager(IServiceProvider serviceProvider) : base(serviceProvider) { loadedAssets = new Dictionary<string, AssetEntry>(); } public CCContentManager(IServiceProvider serviceProvider, string rootDirectory) : base(serviceProvider, rootDirectory) { loadedAssets = new Dictionary<string, AssetEntry>(); } #endregion Constructors internal static void Initialize(IServiceProvider serviceProvider, string rootDirectory) { SharedContentManager = new CCContentManager(new GameServiceContainer(), rootDirectory); } string GetRealName(string assetName) { if (assetLookupDict.ContainsKey(assetName)) { return assetLookupDict[assetName]; } return assetName; } public T TryLoad<T>(string assetName, bool weakReference=false) { var assetKey = Tuple.Create(assetName, typeof(T)); if (failedAssets.ContainsKey(assetKey)) { return default(T); } try { return Load<T>(assetName, weakReference); } catch (Exception) { failedAssets[assetKey] = null; return default(T); } } public override T Load<T>(string assetName) { var assetKey = Tuple.Create(assetName, typeof(T)); if (failedAssets.ContainsKey(assetKey)) { throw new ContentLoadException("Failed to load the asset file from " + assetName); } try { return Load<T>(assetName, false); } catch (Exception) { failedAssets[assetKey] = null; throw; } } public T Load<T>(string assetName, bool weakReference) { if (string.IsNullOrEmpty(assetName)) { throw new ArgumentNullException("assetName"); } // Check for a previously loaded asset first AssetEntry entry; if (loadedAssets.TryGetValue(assetName, out entry)) { if (entry.Asset is T) { return (T)entry.Asset; } else { return InternalLoad<T>(assetName, entry.AssetFileName, weakReference); } } var realName = GetRealName(assetName); foreach (var searchPath in SearchPaths) { foreach (string resolutionOrder in SearchResolutionsOrder) { var path = Path.Combine(Path.Combine(searchPath, resolutionOrder), realName); try { //TODO: for platforms with access to the file system, first check for the existence of the file return InternalLoad<T>(assetName, path, weakReference); } catch (ContentLoadException) { // try other path } } } throw new ContentLoadException("Failed to load the asset file from " + assetName); } public override void Unload() { base.Unload(); loadedAssets.Clear(); } T InternalLoad<T>(string assetName, string path, bool weakReference) { T result = default(T); bool useContentReader = true; try { //Special types if (typeof (T) == typeof (string)) { //TODO: No need CCContent, use TileContainer var content = ReadAsset<CCContent>(path, null); result = (T) (object) content.Content; useContentReader = false; } else { // Load the asset. result = ReadAsset<T>(path, null); } } catch (ContentLoadException) { try { string assetPath = Path.Combine(RootDirectory, path); if (typeof(T) == typeof(string)) { using (var streamContent = TitleContainer.OpenStream(assetPath)) { using (StreamReader reader = new StreamReader(streamContent, Encoding.UTF8)) { result = (T)(object) reader.ReadToEnd(); } } useContentReader = false; } else if (typeof(T) == typeof(PlistDocument)) { try { using (var streamContent = TitleContainer.OpenStream(assetPath)) { result = (T) (object) new PlistDocument(streamContent); } } catch (Exception) { //TODO: Remove This var content = ReadAsset<CCContent>(path, null); result = (T) (object) new PlistDocument(content.Content); } useContentReader = false; } #if XNA else if (typeof (T) == typeof (Texture2D) && Path.HasExtension(path)) { var service = (IGraphicsDeviceService) ServiceProvider.GetService(typeof (IGraphicsDeviceService)); using (var streamContent = TitleContainer.OpenStream(assetPath)) { result = (T) (object) Texture2D.FromStream(service.GraphicsDevice, streamContent); } useContentReader = false; } #endif else { throw; } } catch (Exception) { throw new ContentLoadException("Failed to load the asset file from " + assetName); } } var assetEntry = new AssetEntry(result, path, weakReference, useContentReader); loadedAssets[assetName] = assetEntry; if (result is GraphicsResource) { (result as GraphicsResource).Disposing += AssetDisposing; } return result; } void AssetDisposing(object sender, EventArgs e) { foreach (var loadedAsset in loadedAssets) { if (loadedAsset.Value.Asset == sender) { loadedAssets.Remove(loadedAsset.Key); return; } } } #if MONOGAME protected override void ReloadGraphicsAssets() { foreach (var pair in loadedAssets) { if (pair.Value.UseContentReader && pair.Value.Asset != null) { LoadedAssets.Add(pair.Value.AssetFileName, pair.Value.Asset); } } base.ReloadGraphicsAssets(); foreach (var pair in LoadedAssets) { foreach (var pair2 in loadedAssets) { if (pair2.Value.AssetFileName == pair.Key) { loadedAssets[pair2.Key].Asset = pair.Value; } } } LoadedAssets.Clear(); } #else public void ReloadGraphicsAssets() { foreach (var asset in loadedAssets) { asset.Value.Asset = null; } } #endif public Stream GetAssetStream(string assetName, out string fileName) { fileName = string.Empty; var realName = GetRealName(assetName); foreach (var searchPath in SearchPaths) { foreach (string resolutionOrder in SearchResolutionsOrder) { var path = Path.Combine(Path.Combine(RootDirectory, Path.Combine(searchPath, resolutionOrder)), realName); try { fileName = path; //TODO: for platforms with access to the file system, first check for the existence of the file return TitleContainer.OpenStream(path); } catch (Exception) { // try other path } } } fileName = string.Empty; throw new ContentLoadException("Failed to load the asset stream from " + assetName); } public Stream GetAssetStream(string assetName) { var fileName = string.Empty; return GetAssetStream(assetName, out fileName); } public byte[] GetAssetStreamAsBytes(string assetName, out string fileName) { fileName = string.Empty; try { using (Stream assetStream = GetAssetStream(assetName, out fileName)) { // This used to use a MemoryStream, which could hold a length up to an int. int length = (int)assetStream.Length; if (length == 0) return new byte[0]; var buffer = new byte[length]; assetStream.Read(buffer, 0, length); return buffer; } } catch { return null; } } public byte[] GetAssetStreamAsBytes(string assetName) { string fileName; return GetAssetStreamAsBytes(assetName, out fileName); } public List<string> SearchResolutionsOrder { get { CheckDefaultPath(searchResolutionsOrder); return searchResolutionsOrder; } internal set { searchResolutionsOrder = value; } } public List<string> SearchPaths { get { CheckDefaultPath(searchPaths); return searchPaths; } set { searchPaths = value; } } void CheckDefaultPath(List<string> paths) { for (int i = paths.Count - 1; i >= 0; i--) { if (paths[i] == "") { return; } } paths.Add(""); } } }
412
0.970503
1
0.970503
game-dev
MEDIA
0.887636
game-dev
0.993469
1
0.993469
2004Scape/Server
8,783
data/src/scripts/areas/area_draynor/scripts/aggie.rs2
[opnpc1,aggie] ~chatnpc("<p,happy>What can I help you with?"); def_int $option; if(%prince_progress >= ^prince_spoken_osman & %prince_progress < ^prince_saved) { $option = ~p_choice5("Could you think of a way to make skin paste?", 5, "What could you make for me?", 1, "Cool, do you turn people into frogs?", 2, "You mad old witch, you can't help me.", 3, "Can you make dyes for me please?", 4); }else { $option = ~p_choice4("What could you make for me?", 1, "Cool, do you turn people into frogs?", 2, "You mad old witch, you can't help me.", 3, "Can you make dyes for me please?", 4); } if($option = 1) { ~chatplayer("<p,quiz>What could you make for me?"); ~chatnpc("<p,neutral>I mostly just make what I find pretty. I sometimes make dye for the women's clothes, brighten the place up. I can make red, yellow and blue dyes. Would you like some?"); @aggie_dyes; } else if($option = 2) { ~chatplayer("<p,happy>Cool, do you turn people into frogs?"); ~chatnpc("<p,neutral>Oh, not for years, but if you meet a talking chicken, you have probably met the professor in the manor north of here. A few years ago it was flying fish. That machine is a menace."); } else if($option = 3) { ~chatplayer("<p,angry>You mad old witch, you can't help me."); @aggie_fine; } else if($option = 4) { ~chatplayer("<p,quiz>Can you make dyes for me please?"); ~chatnpc("<p,quiz>What sort of dye would you like? Red, yellow or blue?"); @aggie_dyes; } else if($option = 5) { ~chatplayer("<p,quiz>Could you think of a way to make skin paste?"); if(inv_total(inv, redberry) > 0 & inv_total(inv, pot_flour) > 0 & (inv_total(inv, bucket_water) > 0 | inv_total(inv, jug_water) > 0) & inv_total(inv, ashes) > 0) { ~chatnpc("<p,happy>Yes I can, I see you already have the ingredients. Would you like me to mix some for you now?"); @multi2("Yes please. Mix me some skin paste.", aggie_mix_paste, "No thank you, I don't need any skin paste right now.", aggie_no_paste); } else { ~chatnpc("<p,happy>Why, it's one of my most popular potions.|The women here, they like to have smooth looking skin.|And I must admit, some of the men buy it as well."); ~chatnpc("<p,happy>I can make it for you, just get me what's needed."); ~chatplayer("<p,quiz>What do you need to make it?"); ~chatnpc("<p,neutral>Well dearie, you need a base for the paste.|That's a mix of ash, flour and water.|Then you need redberries to colour it as you want.|Bring me those four items and I will make you some."); } } [opnpcu,aggie] switch_obj(last_useitem) { case onion : @aggie_yellow_dye; case redberry : @aggie_red_dye; case woadleaf : @aggie_blue_dye; case default : ~displaymessage(^dm_default); } [label,aggie_fine] if(inv_total(inv, coins) >= 21 & inv_total(inv, coins) < 101) { inv_del(inv, coins, 5); ~chatnpc("<p,angry>Oh, you like to call a witch names do you?"); npc_anim(human_pickpocket, 0); sound_synth(pick, 0, 0); ~objbox(coins_250, "Aggie waves her hands about, and you seem to be 5 coins poorer.", 250, 0, divide(^objbox_height, 2)); ~chatnpc("<p,neutral>That's a fine for insulting a witch. You should learn some respect."); } else if(inv_total(inv, coins) >= 101) { inv_del(inv, coins, 20); ~chatnpc("<p,angry>Oh, you like to call a witch names do you?"); npc_anim(human_pickpocket, 0); sound_synth(pick, 0, 0); ~objbox(coins_250, "Aggie waves her hands about, and you seem to be 20 coins poorer.", 250, 0, divide(^objbox_height, 2)); ~chatnpc("<p,neutral>That's a fine for insulting a witch. You should learn some respect."); } else if(inv_total(inv, pot_flour) >= 1) { inv_del(inv, pot_flour, 1); ~chatnpc("<p,angry>Oh, you like to call a witch names do you?"); npc_anim(human_pickpocket, 0); sound_synth(pick, 0, 0); ~objbox(pot_flour, "Aggie waves her hands near you, and you seem to have lost some flour.", 250, 0, divide(^objbox_height, 2)); ~chatnpc("<p,neutral>Thank you for your kind present of flour.|I am sure you never meant to insult me."); } else { ~chatnpc("<p,angry>You should be careful about insulting a witch. You never know what shape you could wake up in."); } [label,aggie_dyes] def_int $option = ~p_choice4("What do you need to make red dye?", 1, "What do you need to make yellow dye?", 2, "What do you need to make blue dye?", 3, "No thanks, I am happy the colour I am.", 4); if($option = 1) { ~chatplayer("<p,quiz>What do you need to make red dye?"); ~chatnpc("<p,neutral>3 lots of redberries and 5 coins to you."); @multi3("Okay, make me some red dye please.", aggie_red_dye, "I don't think I have all the ingredients yet.", aggie_ingredients, "I can do without dye at that price.", aggie_without_dye); } else if($option = 2) { ~chatplayer("<p,quiz>What do you need to make yellow dye?"); ~chatnpc("<p,neutral>Yellow is a strange colour to get, comes from onion skins. I need 2 onions and 5 coins to make yellow dye."); @multi3("Okay, make me some yellow dye please.", aggie_yellow_dye, "I don't think I have all the ingredients yet.", aggie_ingredients, "I can do without dye at that price.", aggie_without_dye); } else if($option = 3) { ~chatplayer("<p,quiz>What do you need to make blue dye?"); ~chatnpc("<p,neutral>2 woad leaves and 5 coins to you."); @multi3("Okay, make me some blue dye please.", aggie_blue_dye, "I don't think I have all the ingredients yet.", aggie_ingredients, "I can do without dye at that price.", aggie_without_dye); } else if($option = 4) { ~chatplayer("<p,neutral>No thanks, I am happy the colour I am."); ~chatnpc("<p,neutral>You are easily pleased with yourself then.|When you need dyes, come to me."); } [label,aggie_yellow_dye] if(inv_total(inv, onion) < 2) { ~mesbox("You don't have enough onions to make the yellow dye!"); return; } else if(inv_total(inv, coins) < 5) { ~mesbox("You don't have enough coins to pay for the dye!"); return; } ~chatplayer("<p,neutral>Okay, make me some yellow dye please."); inv_del(inv, coins, 5); inv_del(inv, onion, 2); inv_add(inv, yellowdye, 1); ~objbox(yellowdye, "You hand the onions and payment to Aggie.|Aggie takes a yellow bottle from nowhere and hands it to you.", 250, 0, ^objbox_height); [label,aggie_red_dye] if(inv_total(inv, redberry) < 3) { ~mesbox("You don't have enough berries to make the red dye!"); return; } else if(inv_total(inv, coins) < 5) { ~mesbox("You don't have enough coins to pay for the dye!"); return; } ~chatplayer("<p,neutral>Okay, make me some red dye please."); inv_del(inv, coins, 5); inv_del(inv, redberry, 3); inv_add(inv, reddye, 1); ~objbox(reddye, "You hand the berries and payment to Aggie.|Aggie takes a red bottle from nowhere and hands it to you.", 250, 0, ^objbox_height); [label,aggie_blue_dye] if(inv_total(inv, woadleaf) < 2) { ~mesbox("You don't have enough woad leaves to make the blue dye!"); return; } else if(inv_total(inv, coins) < 5) { ~mesbox("You don't have enough coins to pay for the dye!"); return; } ~chatplayer("<p,neutral>Okay, make me some blue dye please."); inv_del(inv, coins, 5); inv_del(inv, woadleaf, 2); inv_add(inv, bluedye, 1); ~objbox(bluedye, "You hand the woad leaves and payment to Aggie.|Aggie takes a blue bottle from nowhere and hands it to you.", 250, 0, ^objbox_height); [label,aggie_ingredients] ~chatplayer("<p,confused>I don't think I have all the ingredients yet."); ~chatnpc("<p,neutral>You know what you need to get now, come back when you have them. Goodbye for now."); [label,aggie_without_dye] ~chatplayer("<p,angry>I can do without dye at that price."); ~chatnpc("<p,neutral>That's your choice, but I would think you have killed for less. I can see it in your eyes."); [label,aggie_mix_paste] ~chatplayer("<p,happy>Yes please. Mix me some skin paste."); ~chatnpc("<p,happy>That should be simple. Hand the things to Aggie then."); if(inv_total(inv, bucket_water) > 0) { inv_del(inv, bucket_water, 1); } else if(inv_total(inv, jug_water) > 0) { inv_del(inv, jug_water, 1); } ~mesbox("You hand the ash, flour, water and redberries to Aggie.|Aggie tips the ingredients into a cauldron|and mutters some words."); ~chatnpc("<p,confused>Tourniquet, Fenderbaum, Tottenham, Marshmallow, Marblearch."); inv_del(inv, redberry, 1); inv_del(inv, pot_flour, 1); inv_del(inv, ashes, 1); inv_add(inv, skinpaste, 1); ~mesbox("Aggie hands you the skin paste."); ~chatnpc("<p,happy>There you go dearie, your skin potion.|That will make you look good at the Varrock dances."); [label,aggie_no_paste] ~chatplayer("<p,neutral>No thank you, I don't need any skin paste right now."); ~chatnpc("<p,neutral>Okay dearie, that's always your choice.");
412
0.735661
1
0.735661
game-dev
MEDIA
0.920762
game-dev
0.849719
1
0.849719
Aussiemon/Darktide-Source-Code
4,754
dialogues/generated/ogryn_c_psyker_female_c.lua
-- chunkname: @dialogues/generated/ogryn_c_psyker_female_c.lua local ogryn_c_psyker_female_c = { combat_pause_limited_ogryn_c_04_b = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_psyker_female_c__combat_pause_limited_ogryn_c_04_b_01", }, sound_events_duration = { [1] = 3.505, }, randomize_indexes = {}, }, combat_pause_limited_ogryn_c_08_b = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_psyker_female_c__combat_pause_limited_ogryn_c_08_b_01", }, sound_events_duration = { [1] = 2.112875, }, randomize_indexes = {}, }, combat_pause_limited_ogryn_c_12_b = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_psyker_female_c__combat_pause_limited_ogryn_c_12_b_01", }, sound_events_duration = { [1] = 5.843656, }, randomize_indexes = {}, }, combat_pause_limited_ogryn_c_16_b = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_psyker_female_c__combat_pause_limited_ogryn_c_16_b_01", }, sound_events_duration = { [1] = 6.310198, }, randomize_indexes = {}, }, combat_pause_limited_ogryn_c_20_b = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_psyker_female_c__combat_pause_limited_ogryn_c_20_b_01", }, sound_events_duration = { [1] = 4.779521, }, randomize_indexes = {}, }, combat_pause_quirk_abhuman_b = { randomize_indexes_n = 0, sound_events_n = 2, sound_events = { [1] = "loc_psyker_female_c__combat_pause_quirk_abhuman_b_01", [2] = "loc_psyker_female_c__combat_pause_quirk_abhuman_b_02", }, sound_events_duration = { [1] = 2.285177, [2] = 6.50401, }, randomize_indexes = {}, }, combat_pause_quirk_club_thump_b = { randomize_indexes_n = 0, sound_events_n = 2, sound_events = { [1] = "loc_psyker_female_c__combat_pause_quirk_club_thump_b_01", [2] = "loc_psyker_female_c__combat_pause_quirk_club_thump_b_02", }, sound_events_duration = { [1] = 3.663438, [2] = 4.377167, }, randomize_indexes = {}, }, combat_pause_quirk_deddog_b = { randomize_indexes_n = 0, sound_events_n = 2, sound_events = { [1] = "loc_psyker_female_c__combat_pause_quirk_deddog_b_01", [2] = "loc_psyker_female_c__combat_pause_quirk_deddog_b_02", }, sound_events_duration = { [1] = 4.181771, [2] = 5.630354, }, randomize_indexes = {}, }, combat_pause_quirk_glutton_b = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_psyker_female_c__combat_pause_quirk_glutton_b_02", }, sound_events_duration = { [1] = 6.322792, }, randomize_indexes = {}, }, combat_pause_quirk_hates_goo_b = { randomize_indexes_n = 0, sound_events_n = 2, sound_events = { [1] = "loc_psyker_female_c__combat_pause_quirk_hates_goo_b_01", [2] = "loc_psyker_female_c__combat_pause_quirk_hates_goo_b_02", }, sound_events_duration = { [1] = 1.756406, [2] = 1.999719, }, randomize_indexes = {}, }, pimlico_bonding_conversation_heart_b = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_psyker_female_c__pimlico_bonding_conversation_heart_b_01", }, sound_events_duration = { [1] = 3.834188, }, randomize_indexes = {}, }, pimlico_bonding_conversation_heart_d = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_psyker_female_c__pimlico_bonding_conversation_heart_d_01", }, sound_events_duration = { [1] = 2.363625, }, randomize_indexes = {}, }, pimlico_bonding_conversation_snivellers_b = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_psyker_female_c__pimlico_bonding_conversation_snivellers_b_01", }, sound_events_duration = { [1] = 3.548458, }, randomize_indexes = {}, }, pimlico_bonding_conversation_snivellers_d = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_psyker_female_c__pimlico_bonding_conversation_snivellers_d_01", }, sound_events_duration = { [1] = 3.15199, }, randomize_indexes = {}, }, pimlico_bonding_conversation_thinking_b = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_psyker_female_c__pimlico_bonding_conversation_thinking_b_01", }, sound_events_duration = { [1] = 4.78826, }, randomize_indexes = {}, }, pimlico_bonding_conversation_thinking_d = { randomize_indexes_n = 0, sound_events_n = 1, sound_events = { [1] = "loc_psyker_female_c__pimlico_bonding_conversation_thinking_d_01", }, sound_events_duration = { [1] = 4.159813, }, randomize_indexes = {}, }, } return settings("ogryn_c_psyker_female_c", ogryn_c_psyker_female_c)
412
0.66051
1
0.66051
game-dev
MEDIA
0.605806
game-dev
0.732303
1
0.732303
aumuell/open-inventor
5,373
libSoXt/include/SoXtSliderTool.h
/* * * Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy, * Mountain View, CA 94043, or: * * http://www.sgi.com * * For further information regarding this notice, see: * * http://oss.sgi.com/projects/GenInfo/NoticeExplan/ * */ // -*- C++ -*- /* * Copyright (C) 1990-93 Silicon Graphics, Inc. * _______________________________________________________________________ ______________ S I L I C O N G R A P H I C S I N C . ____________ | | $Revision: 1.1.1.1 $ | | Description: | A component class that creates a more functionally extensive | slider than that given by motif. | | Author(s) : Paul Isaacs | ______________ S I L I C O N G R A P H I C S I N C . ____________ _______________________________________________________________________ */ #ifndef SO_XT_SLIDER_TOOL_ #define SO_XT_SLIDER_TOOL_ #include "Xm/Xm.h" #include <Inventor/Xt/SoXtSliderSetBase.h> #include "SoXtMinMaxSlider.h" #include "SoXtFloatText.h" #include "SoXtMMSliderMin.h" #include "SoXtMMSliderMax.h" #define DEFAULT_SLIDER_TOOL_LEFT_DIVIDING_POINT 25 #define DEFAULT_SLIDER_TOOL_RIGHT_DIVIDING_POINT 75 #define DEFAULT_SLIDER_TOOL_SLIDER_DIVIDING_POINT 40 #define DEFAULT_SLIDER_TOOL_MIN_DIVIDING_POINT 40 #define DEFAULT_SLIDER_TOOL_MAX_DIVIDING_POINT 40 #define DEFAULT_SLIDER_TOOL_MIN_BOTTOM_POINT 80 #define DEFAULT_SLIDER_TOOL_MAX_BOTTOM_POINT 80 #define DEFAULT_SLIDER_TOOL_SKINNY_OPEN_POINT_1 22 #define DEFAULT_SLIDER_TOOL_SKINNY_OPEN_POINT_2 44 #define DEFAULT_SLIDER_TOOL_SKINNY_OPEN_POINT_3 78 #define DEFAULT_SLIDER_TOOL_SKINNY_CLOSED_POINT_1 30 #define DEFAULT_SLIDER_TOOL_BORDER_WIDTH 2 #define SLIDER_TOOL_STYLE_CLOSED 0 #define SLIDER_TOOL_STYLE_OPEN 1 #define SLIDER_TOOL_STYLE_SKINNY_OPEN 2 #define SLIDER_TOOL_STYLE_SKINNY_CLOSED 3 class SoXtSliderTool : public SoXtSliderSetBase { public: SoXtSliderTool( Widget parent = NULL, const char *name = NULL, SbBool buildInsideParent = TRUE, int startingMin = DEFAULT_SLIDER_SCALE_MINIMUM, int startingMax = DEFAULT_SLIDER_SCALE_MAXIMUM); ~SoXtSliderTool(); void openMinMax(); void closeMinMax(); void makeSkinnyOpen(); void makeSkinnyClosed(); // return various widgets from the sliderTool Widget getContainer() { return widget; }; SoXtMinMaxSlider *getSlider() { return _slider; }; SoXtFloatText *getValue() { return _value; }; SoXtFloatText *getMinValue() { return _minValue; }; SoXtFloatText *getMaxValue() { return _maxValue; }; // return the value that the sliderTool is currently set at float getSliderValue() { return _slider->getSliderValue(); }; // set the sliderTool's value, min, or max. void toolSetValue( float newVal ); void toolSetMin( float newVal ); void toolSetMax( float newVal ); // internal: static void sliderValueCallback(Widget w, void *client_data, void *call_data ); static void minValueCallback(Widget w, void *client_data, void *call_data ); static void maxValueCallback(Widget w, void *client_data, void *call_data ); void setMultiSlider( SoXtMultiSlider *newOne ); Widget buildWidget( Widget parent, int startingMin, int startingMax); private: SoXtFloatText *_value; SoXtMinMaxSlider *_slider; SoXtFloatText *_minValue; SoXtFloatText *_maxValue; SoXtMMSliderMin *_min; SoXtMMSliderMax *_max; XmString _title; int _leftDividingPoint; // left edge (in percents) of the // slider area when all three sections // are shown. int _rightDividingPoint; // right edge (in percents) of the // slider area when all three sections // are shown. int _sliderDividingPoint; int _minDividingPoint; int _maxDividingPoint; int _minBottomPoint; int _maxBottomPoint; void initLayout(); SoXtMultiSlider *_multiSlider; }; #endif /* SO_XT_SLIDER_TOOL_ */
412
0.852764
1
0.852764
game-dev
MEDIA
0.337596
game-dev
0.650185
1
0.650185
jjbali/Extended-Experienced-PD
3,628
core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/levels/rooms/secret/SecretMazeRoom.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2023 Evan Debenham * * Experienced Pixel Dungeon * Copyright (C) 2019-2020 Trashbox Bobylev * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.levels.rooms.secret; import com.shatteredpixel.shatteredpixeldungeon.Challenges; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.items.Generator; import com.shatteredpixel.shatteredpixeldungeon.items.Heap; import com.shatteredpixel.shatteredpixeldungeon.items.Item; import com.shatteredpixel.shatteredpixeldungeon.levels.Level; import com.shatteredpixel.shatteredpixeldungeon.levels.Terrain; import com.shatteredpixel.shatteredpixeldungeon.levels.features.Maze; import com.shatteredpixel.shatteredpixeldungeon.levels.painters.Painter; import com.watabou.utils.PathFinder; import com.watabou.utils.Point; import com.watabou.utils.Random; public class SecretMazeRoom extends SecretRoom { @Override public int minWidth() { return 14; } @Override public int minHeight() { return 14; } @Override public int maxWidth() { return 18; } @Override public int maxHeight() { return 18; } @Override public void paint(Level level) { Painter.fill(level, this, Terrain.WALL); Painter.fill(level, this, 1, Terrain.EMPTY); //true = space, false = wall Maze.allowDiagonals = false; boolean[][] maze = Maze.generate(this); boolean[] passable = new boolean[width()*height()]; Painter.fill(level, this, 1, Terrain.EMPTY); for (int x = 0; x < maze.length; x++) { for (int y = 0; y < maze[0].length; y++) { if (maze[x][y] == Maze.FILLED) { Painter.fill(level, x + left, y + top, 1, 1, Terrain.WALL); } passable[x + width()*y] = maze[x][y] == Maze.EMPTY; } } PathFinder.setMapSize(width(), height()); Point entrance = entrance(); int entrancePos = (entrance.x - left) + width()*(entrance.y - top); PathFinder.buildDistanceMap( entrancePos, passable ); int bestDist = 0; Point bestDistP = new Point(); for (int i = 0; i < PathFinder.distance.length; i++){ if (PathFinder.distance[i] != Integer.MAX_VALUE && PathFinder.distance[i] > bestDist){ bestDist = PathFinder.distance[i]; bestDistP.x = (i % width()) + left; bestDistP.y = (i / width()) + top; } } Item prize; //1 floor set higher in probability, never cursed do { if (Random.Int(2) == 0) { prize = Generator.randomWeapon((Dungeon.depth / 5) + 1, true); } else { prize = Generator.randomArmor((Dungeon.depth / 5) + 1); } } while (prize.cursed || Challenges.isItemBlocked(prize)); prize.cursedKnown = true; //33% chance for an extra update. if (Random.Int(3) == 0){ prize.upgrade(); } level.drop(prize, level.pointToCell(bestDistP)).type = Heap.Type.CHEST; PathFinder.setMapSize(level.width(), level.height()); entrance().set(Door.Type.HIDDEN); } }
412
0.870302
1
0.870302
game-dev
MEDIA
0.990003
game-dev
0.986943
1
0.986943
DaZombieKiller/TypeTreeDumper
8,807
TypeTreeDumper/Dumper.cs
using Newtonsoft.Json; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using Unity; namespace TypeTreeDumper { static class Dumper { static ExportOptions Options = new(); public static void Execute(UnityEngine engine, ExportOptions options, DumperEngine dumperEngine) { Options = options; Logger.Info($"Starting export. UnityVersion {engine.Version}."); Directory.CreateDirectory(Options.OutputDirectory); TransferInstructionFlags releaseFlags = Options.TransferFlags | TransferInstructionFlags.SerializeGameRelease; TransferInstructionFlags editorFlags = Options.TransferFlags & (~TransferInstructionFlags.SerializeGameRelease); var info = UnityInfo.Create(engine, releaseFlags, editorFlags); if (options.ExportClassesJson) { ExportClassesJson(info); } if (options.ExportTextDump) { ExportRTTI(info); ExportStructDump(info, "structs.dump", true); ExportStructDump(info, "editor_structs.dump", false); ExportInfoJson(info); } if (options.ExportBinaryDump) { if (engine.Version >= UnityVersion.Unity5_0) { ExportStringData(engine.CommonString); } ExportStructData(engine, "structs.dat", releaseFlags); ExportStructData(engine, "editor_structs.dat", editorFlags); } dumperEngine.InvokeExportCompleted(engine, options); Logger.Info("Success"); // Kill the process since we're done and don't want to wait for Unity to exit on its own. // Unity 6.2+ requires this. Process.GetCurrentProcess().Kill(); } static void ExportRTTI(UnityInfo info) { Logger.Info("Writing RTTI..."); using var tw = new StreamWriter(Path.Combine(Options.OutputDirectory, "RTTI.dump")); foreach (var type in info.Classes.OrderBy(x => x.TypeID)) { tw.WriteLine($"PersistentTypeID {type.TypeID}"); tw.WriteLine($" Name {type.Name}"); tw.WriteLine($" Namespace {type.Namespace}"); tw.WriteLine($" Module {type.Module}"); tw.WriteLine($" Base {type.Base ?? ""}"); tw.WriteLine($" DescendantCount {type.DescendantCount}"); tw.WriteLine($" IsAbstract {type.IsAbstract}"); tw.WriteLine($" IsSealed {type.IsSealed}"); tw.WriteLine($" IsStripped {type.IsStripped}"); tw.WriteLine($" IsEditorOnly {type.IsEditorOnly}"); tw.WriteLine(); } } static void ExportStringData(CommonString strings) { byte[] data = strings.GetData().ToArray(); if (data.Length == 0) return; Logger.Info("Writing common string buffer..."); File.WriteAllBytes(Path.Combine(Options.OutputDirectory, "strings.dat"), data); } static void ExportClassesJson(UnityInfo info) { Logger.Info("Writing classes.json..."); using var tw = new StreamWriter(Path.Combine(Options.OutputDirectory, "classes.json")); tw.WriteLine("{"); IEnumerable<string> entries = from type in info.Classes.OrderBy(x => (int)x.TypeID) select $" \"{(int)type.TypeID}\": \"{type.Name}\""; var json = string.Join(',' + tw.NewLine, entries); tw.WriteLine(json); tw.WriteLine("}"); } unsafe static void ExportStructData(UnityEngine engine, string fileName, TransferInstructionFlags flags) { Logger.Info("Writing structure information..."); using var bw = new BinaryWriter(File.OpenWrite(Path.Combine(Options.OutputDirectory, fileName))); bw.Write(Encoding.UTF8.GetBytes(engine.Version.ToString())); bw.Write((byte)0); bw.Write((int)RuntimePlatform.WindowsEditor); bw.Write((byte)1); // hasTypeTrees var countPosition = (int)bw.BaseStream.Position; var typeCount = 0; //Later will be overwritten with actual type count bw.Write(typeCount); Logger.Verb("Writing runtime types..."); foreach(var type in engine.RuntimeTypes.ToArray().OrderBy(x => (int)x.PersistentTypeID)) { var iter = type; Logger.Verb("[{0}] Child: {1}::{2}, {3}, {4}", typeCount, type.Namespace, type.Name, type.Module, type.PersistentTypeID ); Logger.Verb("[{0}] Getting base type...", typeCount); while (iter.IsAbstract) { if (iter.Base == null) break; iter = iter.Base; } Logger.Verb("[{0}] Base: {1}::{2}, {3}, {4}", typeCount, iter.Namespace, iter.Name, iter.Module, iter.PersistentTypeID ); Logger.Verb("[{0}] Producing native object...", typeCount); var obj = engine.ObjectFactory.GetOrProduce(iter); if (obj == null) continue; Logger.Verb("[{0}] Produced object {1}. Persistent = {2}.", typeCount, obj.InstanceID, obj.IsPersistent); Logger.Verb("[{0}] Generating type tree...", typeCount); var tree = engine.TypeTreeFactory.GetTypeTree(obj, flags); Logger.Verb("[{0}] Getting GUID...", typeCount); bw.Write((int)iter.PersistentTypeID); for (int j = 0, n = iter.PersistentTypeID < 0 ? 0x20 : 0x10; j < n; ++j) bw.Write((byte)0); TypeTreeUtility.CreateBinaryDump(tree, bw); typeCount++; } bw.Seek(countPosition, SeekOrigin.Begin); bw.Write(typeCount); } static void ExportStructDump(UnityInfo info, string fileName, bool isRelease) { Logger.Info("Writing structure information dump..."); using var tw = new StreamWriter(Path.Combine(Options.OutputDirectory, fileName)); int typeCount = 0; foreach (var type in info.Classes.OrderBy(x => (int)x.TypeID)) { var iter = type; var inheritance = string.Empty; Logger.Verb("[{0}] Child: {1}::{2}, {3}, {4}", typeCount, type.Namespace, type.Name, type.Module, type.TypeID ); Logger.Verb("[{0}] Getting base type...", typeCount); while (true) { inheritance += iter.Name; if (string.IsNullOrEmpty(iter.Base)) break; inheritance += " <- "; iter = info.Classes.Single(c => c.Name == iter.Base); } tw.WriteLine("\n// classID{{{0}}}: {1}", (int)type.TypeID, inheritance); iter = type; while (iter.IsAbstract) { tw.WriteLine("// {0} is abstract", iter.Name); if (string.IsNullOrEmpty(iter.Base)) break; iter = info.Classes.Single(c => c.Name == iter.Base); } Logger.Verb("[{0}] Base: {1}::{2}, {3}, {4}", typeCount, iter.Namespace, iter.Name, iter.Module, iter.TypeID ); var tree = isRelease ? iter.ReleaseRootNode : iter.EditorRootNode; if(tree != null) TypeTreeUtility.CreateTextDump(tree, tw); typeCount++; } } static void ExportInfoJson(UnityInfo info) { Logger.Info("Writing information json..."); using var sw = new StreamWriter(Path.Combine(Options.OutputDirectory, "info.json")); using var jw = new JsonTextWriter(sw) { Indentation = 1, IndentChar = '\t' }; new JsonSerializer { Formatting = Formatting.Indented }.Serialize(jw, info); } } }
412
0.878062
1
0.878062
game-dev
MEDIA
0.408775
game-dev
0.918318
1
0.918318
georgmartius/lpzrobots
3,765
ode_robots/obstacles/randomobstacles.h
/*************************************************************************** * Copyright (C) 2005-2011 LpzRobots development team * * Georg Martius <georg dot martius at web dot de> * * Frank Guettler <guettler at informatik dot uni-leipzig dot de * * Frank Hesse <frank at nld dot ds dot mpg dot de> * * Ralf Der <ralfder at mis dot mpg dot de> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * ***************************************************************************/ #ifndef __RANDOMOBSTACLES_H #define __RANDOMOBSTACLES_H #include "abstractobstacle.h" #include "abstractground.h" #include "pos.h" namespace lpzrobots { struct RandomObstaclesConf { Pos area; ///< zero centered, use setPose to shift around (z() component is the height) osg::Matrix pose; Pos minSize; Pos maxSize; double minDensity; double maxDensity; int boxRelFreq; int sphereRelFreq; int capRelFreq; }; /** * Passive random obstacles: * with spawn and remove obstacles can be created and removed. * Add an instance to global.obstacles to customize the creation * otherwise a default version is used (though dependend on the playground) */ class RandomObstacles : public AbstractObstacle { int index; RandomObstaclesConf conf; public: enum OType {Box, Sphere, Caps, ORandom}; enum SType {Metal, Plastic, Rubber, Foam, SRandom}; /// creates a default configuration, optionally with the size and position of the ground static RandomObstaclesConf getDefaultConf(AbstractGround* ground = 0){ RandomObstaclesConf c; if(ground){ c.area = Pos(ground->getGroundLength()/2, ground->getGroundWidth()/2, 5)*0.95; c.pose = ground->getPose(); }else{ c.area = Pos(10,10,4); c.pose = osg::Matrix::translate(0,0,0); } c.minSize = Pos(.5,.5,.5); c.maxSize = Pos(2,2,2); c.minDensity=1; c.maxDensity=10; c.boxRelFreq=5; c.sphereRelFreq=1; c.capRelFreq=1; return c; } RandomObstacles(const OdeHandle& odeHandle, const OsgHandle& osgHandle, const RandomObstaclesConf& conf = getDefaultConf()); virtual void setPose(const osg::Matrix& pose); virtual Primitive* getMainPrimitive() const; virtual void create(){}; virtual void remove(bool all = false); virtual void spawn(OType type = ORandom , SType subtype = SRandom); }; } #endif
412
0.881677
1
0.881677
game-dev
MEDIA
0.753953
game-dev
0.894915
1
0.894915
PhoenixBladez/SpiritMod
1,221
Tiles/Furniture/Acid/AcidPianoTile.cs
using Microsoft.Xna.Framework; using Terraria; using Terraria.ID; using Terraria.ModLoader; using Terraria.ObjectData; namespace SpiritMod.Tiles.Furniture.Acid { public class AcidPianoTile : ModTile { public override void SetDefaults() { Main.tileFrameImportant[Type] = true; Main.tileNoAttach[Type] = true; Main.tileTable[Type] = true; Main.tileLavaDeath[Type] = true; TileObjectData.newTile.CopyFrom(TileObjectData.Style3x2); TileObjectData.newTile.Height = 2; TileObjectData.newTile.CoordinateHeights = new int[] { 16, 18 }; TileObjectData.addTile(Type); AddToArray(ref TileID.Sets.RoomNeeds.CountsAsTable); ModTranslation name = CreateMapEntryName(); name.SetDefault("Corrosive Piano"); AddMapEntry(new Color(100, 122, 111), name); disableSmartCursor = true; dustType = -1; } public override void SetDrawPositions(int i, int j, ref int width, ref int offsetY, ref int height) { offsetY = 2; } public override void KillMultiTile(int i, int j, int frameX, int frameY) { Main.PlaySound(new Terraria.Audio.LegacySoundStyle(3, 4)); Terraria.Item.NewItem(i * 16, j * 16, 32, 16, ModContent.ItemType<Items.Placeable.Furniture.Acid.AcidPiano>()); } } }
412
0.747878
1
0.747878
game-dev
MEDIA
0.824945
game-dev
0.696044
1
0.696044
dotnet/dotnet
1,824
src/runtime/src/tests/JIT/Regression/JitBlue/Runtime_57061/Runtime_57061_3.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Generated by Fuzzlyn v1.2 on 2021-08-16 22:20:52 // Run on .NET 6.0.0-dev on X86 Windows // Seed: 15888848110967612195 // Reduced from 235.4 KiB to 1.4 KiB in 00:22:05 // Crashes the runtime using System.Runtime.CompilerServices; using Xunit; class C0 { public ushort F0; public short F1; public ulong F2; public short F3; public C0(ushort f0, ulong f2, short f3) { F0 = f0; F2 = f2; F3 = f3; } } class C1 { public uint F1; } struct S0 { public byte F0; public C0 F3; } public class Runtime_57061_3 { static long s_2; static S0[][][] s_3; static S0 s_4; [Fact] public static void TestEntryPoint() { C1 vr3 = default(C1); for (int vr4 = 0; vr4 < Bound(); vr4++) { try { System.Console.WriteLine(vr3.F1); } finally { s_2 = s_2; } bool vr5 = false; if (vr5) { try { vr5 &= 0 == s_4.F3.F1; } finally { var vr6 = new C0(1, 1, 0); var vr7 = new C0(0, 0, 0); S0 vr10 = s_3[0][0][0]; byte vr11 = s_4.F0++; uint vr12 = default(uint); var vr8 = (byte)vr12; M4(ref s_3[0][0][0], vr8); } } } } static uint M4(ref S0 arg2, byte arg3) { return default(uint); } [MethodImpl(MethodImplOptions.NoInlining)] static int Bound() => 0; }
412
0.767677
1
0.767677
game-dev
MEDIA
0.239982
game-dev
0.669142
1
0.669142
rndmorris/Salis-Arcana
1,988
src/main/java/dev/rndmorris/salisarcana/mixins/late/tiles/MixinTileEldritchAltar_SpawnMobs.java
package dev.rndmorris.salisarcana.mixins.late.tiles; import java.util.Random; import net.minecraft.world.IBlockAccess; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import com.llamalad7.mixinextras.injector.wrapoperation.Operation; import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; import com.llamalad7.mixinextras.sugar.Local; import com.llamalad7.mixinextras.sugar.ref.LocalIntRef; import dev.rndmorris.salisarcana.config.SalisConfig; import thaumcraft.api.TileThaumcraft; import thaumcraft.common.tiles.TileEldritchAltar; @Mixin(value = TileEldritchAltar.class, remap = false) public abstract class MixinTileEldritchAltar_SpawnMobs extends TileThaumcraft { @WrapOperation( method = { "spawnGuards", "spawnGuardian" }, at = @At( value = "INVOKE", target = "Lnet/minecraft/util/MathHelper;getRandomIntegerInRange(Ljava/util/Random;II)I")) private int preventRandCalls(Random random, int min, int max, Operation<Integer> original) { return 0; } @WrapOperation( method = { "spawnGuards", "spawnGuardian" }, at = @At( value = "INVOKE", target = "Lnet/minecraft/world/World;doesBlockHaveSolidTopSurface(Lnet/minecraft/world/IBlockAccess;III)Z")) @SuppressWarnings("ParameterCanBeLocal") private boolean pickAndCheckCoords(IBlockAccess worldIn, int x, int y, int z, Operation<Boolean> original, @Local(name = "i1") LocalIntRef xRef, @Local(name = "j1") LocalIntRef yRef, @Local(name = "k1") LocalIntRef zRef) { final var spawnSettings = SalisConfig.features.eldritchAltarSpawningMethod; xRef.set(x = xCoord + spawnSettings.randomHorizontal(worldObj.rand)); yRef.set(y = yCoord + spawnSettings.randomVertical(worldObj.rand)); zRef.set(z = zCoord + spawnSettings.randomHorizontal(worldObj.rand)); return original.call(worldIn, x, y - 1, z); } }
412
0.898126
1
0.898126
game-dev
MEDIA
0.980978
game-dev
0.901388
1
0.901388
GaijinEntertainment/DagorEngine
3,162
prog/3rdPartyLibs/phys/bullet-3/src/BulletSoftBody/btCGProjection.h
/* Written by Xuchen Han <xuchenhan2015@u.northwestern.edu> Bullet Continuous Collision Detection and Physics Library Copyright (c) 2019 Google Inc. http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_CG_PROJECTION_H #define BT_CG_PROJECTION_H #include "btSoftBody.h" #include "BulletDynamics/Featherstone/btMultiBodyLinkCollider.h" #include "BulletDynamics/Featherstone/btMultiBodyConstraint.h" struct DeformableContactConstraint { const btSoftBody::Node* m_node; btAlignedObjectArray<const btSoftBody::RContact*> m_contact; btAlignedObjectArray<btVector3> m_total_normal_dv; btAlignedObjectArray<btVector3> m_total_tangent_dv; btAlignedObjectArray<bool> m_static; btAlignedObjectArray<bool> m_can_be_dynamic; DeformableContactConstraint(const btSoftBody::RContact& rcontact) : m_node(rcontact.m_node) { append(rcontact); } DeformableContactConstraint() : m_node(NULL) { m_contact.push_back(NULL); } void append(const btSoftBody::RContact& rcontact) { m_contact.push_back(&rcontact); m_total_normal_dv.push_back(btVector3(0, 0, 0)); m_total_tangent_dv.push_back(btVector3(0, 0, 0)); m_static.push_back(false); m_can_be_dynamic.push_back(true); } void replace(const btSoftBody::RContact& rcontact) { m_contact.clear(); m_total_normal_dv.clear(); m_total_tangent_dv.clear(); m_static.clear(); m_can_be_dynamic.clear(); append(rcontact); } ~DeformableContactConstraint() { } }; class btCGProjection { public: typedef btAlignedObjectArray<btVector3> TVStack; typedef btAlignedObjectArray<btAlignedObjectArray<btVector3> > TVArrayStack; typedef btAlignedObjectArray<btAlignedObjectArray<btScalar> > TArrayStack; btAlignedObjectArray<btSoftBody*>& m_softBodies; const btScalar& m_dt; // map from node indices to node pointers const btAlignedObjectArray<btSoftBody::Node*>* m_nodes; btCGProjection(btAlignedObjectArray<btSoftBody*>& softBodies, const btScalar& dt) : m_softBodies(softBodies), m_dt(dt) { } virtual ~btCGProjection() { } // apply the constraints virtual void project(TVStack& x) = 0; virtual void setConstraints() = 0; // update the constraints virtual btScalar update() = 0; virtual void reinitialize(bool nodeUpdated) { } virtual void setIndices(const btAlignedObjectArray<btSoftBody::Node*>* nodes) { m_nodes = nodes; } }; #endif /* btCGProjection_h */
412
0.893438
1
0.893438
game-dev
MEDIA
0.980282
game-dev
0.837734
1
0.837734
lordofduct/spacepuppy-unity-framework
5,025
SpacepuppyBase/Utils/ColliderUtil.cs
using UnityEngine; using System.Collections.Generic; using System.Linq; namespace com.spacepuppy.Utils { public static class ColliderUtil { public delegate void TriggerEventCallback(Collider sender, Collider other); public delegate void CollisionEventCallback(Collider sender, Collision collision); #region Trigger Event Handlers public static void AddOnTriggerEnterCallback(this Rigidbody rb, TriggerEventCallback callback) { if (rb == null || callback == null) return; var handle = rb.AddOrGetComponent<OnTriggerEnterCallbackHandle>(); handle.TriggerEntered += callback; } public static void AddOnTriggerExitCallback(this Rigidbody rb, TriggerEventCallback callback) { if (rb == null || callback == null) return; var handle = rb.AddOrGetComponent<OnTriggerExitCallbackHandle>(); handle.TriggerExited += callback; } public static void AddOnTriggerEnterCallback(this Collider collider, TriggerEventCallback callback) { if (collider == null || callback == null) return; var handle = collider.AddOrGetComponent<OnTriggerEnterCallbackHandle>(); handle.TriggerEntered += callback; } public static void AddOnTriggerExitCallback(this Collider collider, TriggerEventCallback callback) { if (collider == null || callback == null) return; var handle = collider.AddOrGetComponent<OnTriggerExitCallbackHandle>(); handle.TriggerExited += callback; } public static void RemoveOnTriggerEnterCallback(this Rigidbody rb, TriggerEventCallback callback) { if (rb == null || callback == null) return; var handle = rb.GetComponent<OnTriggerEnterCallbackHandle>(); if (handle != null) { handle.TriggerEntered -= callback; } } public static void RemoveOnTriggerExitCallback(this Rigidbody rb, TriggerEventCallback callback) { if (rb == null || callback == null) return; var handle = rb.GetComponent<OnTriggerExitCallbackHandle>(); if (handle != null) { handle.TriggerExited -= callback; } } public static void RemoveOnTriggerEnterCallback(this Collider collider, TriggerEventCallback callback) { if (collider == null || callback == null) return; var handle = collider.GetComponent<OnTriggerEnterCallbackHandle>(); if(handle != null) { handle.TriggerEntered -= callback; } } public static void RemoveOnTriggerExitCallback(this Collider collider, TriggerEventCallback callback) { if (collider == null || callback == null) return; var handle = collider.GetComponent<OnTriggerExitCallbackHandle>(); if (handle != null) { handle.TriggerExited -= callback; } } #endregion #region Special Types private sealed class OnTriggerEnterCallbackHandle : MonoBehaviour { public event TriggerEventCallback TriggerEntered { add { _triggerEntered += value; this.enabled = (_triggerEntered != null); } remove { _triggerEntered -= value; this.enabled = (_triggerEntered != null); } } private TriggerEventCallback _triggerEntered; private Collider _collider; void Awake() { _collider = this.GetComponent<Collider>(); } private void OnTriggerEnter(Collider other) { var d = _triggerEntered; if (d != null) d(_collider, other); } } private sealed class OnTriggerExitCallbackHandle : MonoBehaviour { public event TriggerEventCallback TriggerExited { add { _triggerExited += value; this.enabled = (_triggerExited != null); } remove { _triggerExited -= value; this.enabled = (_triggerExited != null); } } private TriggerEventCallback _triggerExited; private Collider _collider; void Awake() { _collider = this.GetComponent<Collider>(); } private void OnTriggerEnter(Collider other) { var d = _triggerExited; if (d != null) d(_collider, other); } } #endregion } }
412
0.786896
1
0.786896
game-dev
MEDIA
0.895277
game-dev
0.770664
1
0.770664
demoth/jake2
6,254
game/src/main/kotlin/jake2/game/adapters/SuperAdapter.kt
/* Copyright (C) 1997-2001 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // Created on 09.01.2004 by RST. package jake2.game.adapters import jake2.game.GameEntity import jake2.game.GameExportsImpl import jake2.qcommon.cplane_t import jake2.qcommon.csurface_t import jake2.qcommon.filesystem.QuakeFile /** * There are many fields in the [GameEntity] class. Some of them represent state - like 'health', 'damage' etc, * other represent behaviour - like 'think', 'touch', 'use' etc. * In c version these were function pointers. * * * The purpose of all Adapter registration is to store and restore such behavioural edict fields. */ abstract class SuperAdapter { init { register(iD, this) } abstract val iD: String override fun toString(): String { return "${this.javaClass.simpleName} '$iD'" } override fun equals(other: Any?): Boolean { return if (other is SuperAdapter) { iD == other.iD } else false } companion object { fun register(id: String?, sa: SuperAdapter): String { if (id.isNullOrBlank()) { // TODO: exception return "null" } adapters[id] = sa return id } fun registerThink(id: String, think: (self: GameEntity, game: GameExportsImpl) -> Boolean): EntThinkAdapter { val adapter = object : EntThinkAdapter() { override fun think(self: GameEntity, game: GameExportsImpl): Boolean { return think.invoke(self, game) } override val iD: String = id } register(id, adapter) return adapter } fun registerBlocked(id: String, block: (self: GameEntity, obstacle: GameEntity, game: GameExportsImpl ) -> Unit): EntBlockedAdapter { val adapter = object: EntBlockedAdapter() { override fun blocked(self: GameEntity, obstacle: GameEntity, game: GameExportsImpl) { block.invoke(self, obstacle, game) } override val iD: String = id } register(id, adapter) return adapter } fun registerUse(id: String, use: (self: GameEntity, other: GameEntity?, activator: GameEntity?, game: GameExportsImpl) -> Unit): EntUseAdapter { val adapter = object : EntUseAdapter() { override fun use( self: GameEntity, other: GameEntity?, activator: GameEntity?, gameExports: GameExportsImpl ) { use.invoke(self, other, activator, gameExports) } override val iD = id } register(id, adapter) return adapter } fun registerTouch(id: String, touch: (self: GameEntity, other: GameEntity, plane: cplane_t, surf: csurface_t?, game: GameExportsImpl) -> Unit): EntTouchAdapter { val adapter = object : EntTouchAdapter() { override fun touch( self: GameEntity, other: GameEntity, plane: cplane_t, surf: csurface_t?, game: GameExportsImpl ) { touch.invoke(self, other, plane, surf, game) } override val iD = id } register(id, adapter) return adapter } fun registerDie(id:String, die: (self: GameEntity, inflictor: GameEntity?, attacker: GameEntity?, damage: Int, point: FloatArray?, game: GameExportsImpl) -> Unit): EntDieAdapter { val adapter = object : EntDieAdapter() { override fun die( self: GameEntity, inflictor: GameEntity?, attacker: GameEntity?, damage: Int, point: FloatArray?, gameExports: GameExportsImpl ) { die.invoke(self, inflictor, attacker, damage, point, gameExports) } override val iD = id } register(id, adapter) return adapter } /** Adapter repository. */ private val adapters: MutableMap<String, SuperAdapter> = HashMap() /** * Returns the adapter from the repository given by its ID. */ @JvmStatic fun getFromID(key: String): SuperAdapter? { return adapters[key] } /** Writes the Adapter-ID to the file. */ @JvmStatic fun writeAdapter(f: QuakeFile, a: SuperAdapter?) { f.writeInt(3988) if (a == null) f.writeString(null) else { f.writeString(a.iD) } } /** Reads the adapter id and returns the adapter. */ @JvmStatic fun readAdapter(f: QuakeFile): SuperAdapter? { if (f.readInt() != 3988) { // replace with log // Com.DPrintf("wrong read position: readadapter 3988 \n"); } val id = f.readString() ?: return null return getFromID(id) } fun think(s: String): EntThinkAdapter { val adapter = adapters[s] if (adapter is EntThinkAdapter) return adapter else throw IllegalStateException("No such think adapter: $s") } } }
412
0.798406
1
0.798406
game-dev
MEDIA
0.922732
game-dev
0.755953
1
0.755953
exmex/HC
5,940
Client/Resource_Client/data/battle/heroes/SB.lua
local ed = ed local rush_speed = 300 local SB_Rush_Buff_ID = 148 local SB_Waiting_Buff_ID = 149 local function reset(basefunc, hero) basefunc(hero) local dir = hero:getInitDir() hero.position[1] = 400 - 480 * dir local has_friend_unit = false local unit_list = ed.engine.unit_list for i, unit in pairs(unit_list) do if unit.name ~= hero.name and unit.camp == hero.camp then has_friend_unit = true break end end for _, skill in pairs(hero.skill_list) do if skill.info["Skill Name"] == "SB_atk2" then if has_friend_unit then do local owner = hero local bid = SB_Waiting_Buff_ID local binfo = ed.lookupDataTable("Buff", nil, bid) local buff = ed.BuffCreate(binfo, owner, owner) owner:addBuff(buff, owner) end break end skill.cd_remaining = 999 break end end end local function skillatk2_takeEffectOn(skillatk2, owner, unit) local x = unit.position[1] local dir = owner:getInitDir() local extraDis = (dir > 0 and x or 800 - x) * 0.05 local distance = math.abs(x - (390 + dir * extraDis)) unit:knockup(math.max(0.3, distance / 400), { distance * dir, 0 }) owner.skillatk2_affected_units[unit] = true local bid = 6 local binfo = ed.lookupDataTable("Buff", nil, bid) local buff = ed.BuffCreate(binfo, unit, owner) unit:addBuff(buff, owner) if ed.run_with_scene then local info = skillatk2.info local effect_name = info["Point Effect"] if effect_name then local effect_z = info["Point Zorder"] or 0 ed.scene:playEffectOnScene(effect_name, unit.position, { owner.direction, 1 }, nil, effect_z) end end skillatk2:takeEffectOn(unit, owner) end local function skillatk2_onAttackFrame(basefunc, skill) local owner = skill.caster owner.position = { 400 - 80 * owner:getInitDir(), 0 } for _, tbuff in ipairs(owner.buff_list) do if tbuff.info.ID == SB_Rush_Buff_ID then local buff = tbuff buff.owner:removeBuff(buff) end end owner.walk_v = {0, 0} end local function skillatk2_buff_update(basefunc, buff, dt) local owner = buff.owner local skillatk2 = owner.skillatk2 if skillatk2 then local owner = skillatk2.caster local info = skillatk2.info local direction = owner.direction local location = owner.position local origin = { location[1] + info["X Shift"] * direction, location[2] } local shape = info["AOE Shape"] local arg1 = 120 local arg2 = info["Shape Arg2"] for unit in ed.engine:foreachAliveUnit(skillatk2:affectedCamp()) do local skillatk2_affected_units = owner.skillatk2_affected_units if not skillatk2_affected_units[unit] then local p2 = ed.edpSub(unit.position, origin) p2[1] = p2[1] * direction if skillatk2.testPointInShape(p2, shape, arg1, arg2) then skillatk2_affected_units[unit] = true skillatk2_takeEffectOn(skillatk2, owner, unit) end end end end basefunc(buff, dt) end local function skillatk2_start(basefunc, skill, target) basefunc(skill, target) local sb = skill.caster sb.skillatk2 = skill sb.skillatk2_affected_units = {} sb.rush_destination = 400 local caster = skill.caster local eventList = skill.current_phase.event_list local atkFrame for i = 1, #eventList do if eventList[i].Type == "Attack" then atkFrame = eventList[i] break end end local time = atkFrame.Time local dir = caster:getInitDir() caster.position = { 400 - (80 + time * rush_speed) * dir, 0 } caster.walk_v = { rush_speed * dir, 0 } local bid = SB_Rush_Buff_ID local binfo = ed.lookupDataTable("Buff", nil, bid) local owner = skill.caster local buff = ed.BuffCreate(binfo, owner, owner) buff.update = override(buff.update, skillatk2_buff_update) owner:addBuff(buff, owner) end local function skillatk2_finish(basefunc, skill, target) local owner = skill.caster for _, tbuff in ipairs(owner.buff_list) do if tbuff.info.ID == SB_Rush_Buff_ID then local buff = tbuff buff.owner:removeBuff(buff) end end basefunc(skill, target) end local ori_position local skillult_start = function(basefunc, skill, target) basefunc(skill, target) local caster = skill.caster if skill.target then local position1 = skill.target.position[1] + caster.direction * 70 caster:setPosition({ position1, skill.target.position[2] }) end end local skillult_takeEffectAt = function(basefunc, skill, location, source) local caster = skill.caster if skill.attack_counter == 1 then if skill.target then local position1 = skill.target.position[1] + caster.direction * 70 caster:setPosition({ position1, skill.target.position[2] }) end else basefunc(skill, location, source) end end local function awake_update(basefunc, self, dt) if self.state == ed.emUnitState_Dying then if not self.dyingTimer then self.dyingTimer = 1 end self.dyingTimer = self.dyingTimer - dt if self.dyingTimer <= 0 then self.dyingTimer = 99999 local skill = self.skills.SB_awake skill:takeEffectAt(self.position) ed.engine:deliverBall(self, skill, 1) end else self.dyingTimer = nil end basefunc(self, dt) end local function init_hero(hero) if ed.protoAwake(hero.proto) then hero.update = override(hero.update, awake_update) end hero.reset = override(hero.reset, reset) local skillatk2 = hero.skills.SB_atk2 if skillatk2 then skillatk2.start = override(skillatk2.start, skillatk2_start) skillatk2.onAttackFrame = override(skillatk2.onAttackFrame, skillatk2_onAttackFrame) end local skillult = hero.skills.SB_ult if skillult then skillult.start = override(skillult.start, skillult_start) end return hero end return init_hero
412
0.834676
1
0.834676
game-dev
MEDIA
0.991275
game-dev
0.931278
1
0.931278
Edgarins29/Doom3
4,213
neo/game/physics/Force_Drag.cpp
/* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code"). Doom 3 Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Doom 3 Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #include "sys/platform.h" #include "framework/UsercmdGen.h" #include "physics/Physics.h" #include "physics/Force_Drag.h" CLASS_DECLARATION( idForce, idForce_Drag ) END_CLASS /* ================ idForce_Drag::idForce_Drag ================ */ idForce_Drag::idForce_Drag( void ) { damping = 0.5f; dragPosition = vec3_zero; physics = NULL; id = 0; p = vec3_zero; dragPosition = vec3_zero; } /* ================ idForce_Drag::~idForce_Drag ================ */ idForce_Drag::~idForce_Drag( void ) { } /* ================ idForce_Drag::Init ================ */ void idForce_Drag::Init( float damping ) { if ( damping >= 0.0f && damping < 1.0f ) { this->damping = damping; } } /* ================ idForce_Drag::SetPhysics ================ */ void idForce_Drag::SetPhysics( idPhysics *phys, int id, const idVec3 &p ) { this->physics = phys; this->id = id; this->p = p; } /* ================ idForce_Drag::SetDragPosition ================ */ void idForce_Drag::SetDragPosition( const idVec3 &pos ) { this->dragPosition = pos; } /* ================ idForce_Drag::GetDragPosition ================ */ const idVec3 &idForce_Drag::GetDragPosition( void ) const { return this->dragPosition; } /* ================ idForce_Drag::GetDraggedPosition ================ */ const idVec3 idForce_Drag::GetDraggedPosition( void ) const { return ( physics->GetOrigin( id ) + p * physics->GetAxis( id ) ); } /* ================ idForce_Drag::Evaluate ================ */ void idForce_Drag::Evaluate( int time ) { float l1, l2, mass; idVec3 dragOrigin, dir1, dir2, velocity, centerOfMass; idMat3 inertiaTensor; idRotation rotation; idClipModel *clipModel; if ( !physics ) { return; } clipModel = physics->GetClipModel( id ); if ( clipModel != NULL && clipModel->IsTraceModel() ) { clipModel->GetMassProperties( 1.0f, mass, centerOfMass, inertiaTensor ); } else { centerOfMass.Zero(); } centerOfMass = physics->GetOrigin( id ) + centerOfMass * physics->GetAxis( id ); dragOrigin = physics->GetOrigin( id ) + p * physics->GetAxis( id ); dir1 = dragPosition - centerOfMass; dir2 = dragOrigin - centerOfMass; l1 = dir1.Normalize(); l2 = dir2.Normalize(); rotation.Set( centerOfMass, dir2.Cross( dir1 ), RAD2DEG( idMath::ACos( dir1 * dir2 ) ) ); physics->SetAngularVelocity( rotation.ToAngularVelocity() / MS2SEC( USERCMD_MSEC ), id ); velocity = physics->GetLinearVelocity( id ) * damping + dir1 * ( ( l1 - l2 ) * ( 1.0f - damping ) / MS2SEC( USERCMD_MSEC ) ); physics->SetLinearVelocity( velocity, id ); } /* ================ idForce_Drag::RemovePhysics ================ */ void idForce_Drag::RemovePhysics( const idPhysics *phys ) { if ( physics == phys ) { physics = NULL; } }
412
0.660622
1
0.660622
game-dev
MEDIA
0.980681
game-dev
0.511153
1
0.511153
followingthefasciaplane/source-engine-diff-check
3,592
misc/game/server/tf/bot/behavior/scenario/capture_the_flag/tf_bot_attack_flag_defenders.cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // tf_bot_attack_flag_defenders.cpp // Attack enemies that are preventing the flag from reaching its destination // Michael Booth, May 2011 #include "cbase.h" #include "bot/tf_bot.h" #include "bot/behavior/scenario/capture_the_flag/tf_bot_attack_flag_defenders.h" #include "bot/behavior/scenario/capture_the_flag/tf_bot_escort_flag_carrier.h" ConVar tf_bot_flag_escort_range( "tf_bot_flag_escort_range", "500", FCVAR_CHEAT ); extern ConVar tf_bot_flag_escort_max_count; extern int GetBotEscortCount( int team ); //--------------------------------------------------------------------------------------------- CTFBotAttackFlagDefenders::CTFBotAttackFlagDefenders( float minDuration ) { if ( minDuration > 0.0f ) { m_minDurationTimer.Start( minDuration ); } else { m_minDurationTimer.Invalidate(); } } //--------------------------------------------------------------------------------------------- ActionResult< CTFBot > CTFBotAttackFlagDefenders::OnStart( CTFBot *me, Action< CTFBot > *priorAction ) { m_path.SetMinLookAheadDistance( me->GetDesiredPathLookAheadRange() ); m_chasePlayer = NULL; return CTFBotAttack::OnStart( me, priorAction ); } //--------------------------------------------------------------------------------------------- ActionResult< CTFBot > CTFBotAttackFlagDefenders::Update( CTFBot *me, float interval ) { const CKnownEntity *threat = me->GetVisionInterface()->GetPrimaryKnownThreat(); if ( threat && threat->IsVisibleRecently() ) { // prepare to fight me->EquipBestWeaponForThreat( threat ); } if ( m_watchFlagTimer.IsElapsed() && m_minDurationTimer.IsElapsed() ) { m_watchFlagTimer.Start( RandomFloat( 1.0f, 3.0f ) ); CCaptureFlag *flag = me->GetFlagToFetch(); if ( !flag ) { return Done( "No flag" ); } // can't reach flag if it is at home if ( !TFGameRules()->IsMannVsMachineMode() || !flag->IsHome() ) { CTFPlayer *carrier = ToTFPlayer( flag->GetOwnerEntity() ); if ( !carrier ) { return Done( "Flag was dropped" ); } if ( me->IsSelf( carrier ) ) { return Done( "I picked up the flag!" ); } // escort the flag carrier, unless the carrier is in a squad CTFBot *botCarrier = ToTFBot( carrier ); if ( !botCarrier || !botCarrier->IsInASquad() ) { if ( me->IsRangeLessThan( carrier, tf_bot_flag_escort_range.GetFloat() ) ) { if ( GetBotEscortCount( me->GetTeamNumber() ) < tf_bot_flag_escort_max_count.GetInt() ) { return ChangeTo( new CTFBotEscortFlagCarrier, "Near flag carrier - escorting" ); } } } } } ActionResult< CTFBot > result = CTFBotAttack::Update( me, interval ); if ( result.IsDone() ) { // nothing to attack, move towards a random player if ( m_chasePlayer == NULL || !m_chasePlayer->IsAlive() ) { m_chasePlayer = me->SelectRandomReachableEnemy(); } if ( m_chasePlayer == NULL ) { // everyone is dead or hiding in the spawn room - go escort the flag return ChangeTo( new CTFBotEscortFlagCarrier, "No reachable victim - escorting flag" ); } // cheat and "see" our victim so we know where to go me->GetVisionInterface()->AddKnownEntity( m_chasePlayer ); if ( m_repathTimer.IsElapsed() ) { m_repathTimer.Start( RandomFloat( 1.0f, 3.0f ) ); CTFBotPathCost cost( me, DEFAULT_ROUTE ); float maxPathLength = TFGameRules()->IsMannVsMachineMode() ? TFBOT_MVM_MAX_PATH_LENGTH : 0.0f; m_path.Compute( me, m_chasePlayer, cost, maxPathLength ); } m_path.Update( me ); } return Continue(); }
412
0.992884
1
0.992884
game-dev
MEDIA
0.818092
game-dev
0.977743
1
0.977743
Coldzer0/ImGui-Pascal
30,692
SDL2-for-Pascal/units/sdlgamecontroller.inc
//from sdl_gamecontroller.h {** * SDL_gamecontroller.h * * In order to use these functions, SDL_Init() must have been called * with the ::SDL_INIT_JOYSTICK flag. This causes SDL to scan the system * for game controllers, and load appropriate drivers. * * If you would like to receive controller updates while the application * is in the background, you should set the following hint before calling * SDL_Init(): SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS *} {* The gamecontroller structure used to identify an SDL game controller *} type PPSDL_GameController = ^PSDL_GameController; PSDL_GameController = ^TSDL_GameController; TSDL_GameController = record end; PPSDL_GameControllerType = ^PSDL_GameControllerType; PSDL_GameControllerType = ^TSDL_GameControllerType; TSDL_GameControllerType = type cint; const SDL_CONTROLLER_TYPE_UNKNOWN = TSDL_GameControllerType(0); SDL_CONTROLLER_TYPE_XBOX360 = TSDL_GameControllerType(1); SDL_CONTROLLER_TYPE_XBOXONE = TSDL_GameControllerType(2); SDL_CONTROLLER_TYPE_PS3 = TSDL_GameControllerType(3); SDL_CONTROLLER_TYPE_PS4 = TSDL_GameControllerType(4); SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO = TSDL_GameControllerType(5); SDL_CONTROLLER_TYPE_VIRTUAL = TSDL_GameControllerType(6); SDL_CONTROLLER_TYPE_PS5 = TSDL_GameControllerType(7); SDL_CONTROLLER_TYPE_AMAZON_LUNA = TSDL_GameControllerType(8); SDL_CONTROLLER_TYPE_GOOGLE_STADIA = TSDL_GameControllerType(9); SDL_CONTROLLER_TYPE_NVIDIA_SHIELD = TSDL_GameControllerType(10); SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_LEFT = TSDL_GameControllerType(11); SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT = TSDL_GameControllerType(12); SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_PAIR = TSDL_GameControllerType(13); type PPSDL_GameControllerBindType = ^PSDL_GameControllerBindType; PSDL_GameControllerBindType = ^TSDL_GameControllerBindType; TSDL_GameControllerBindType = type cint; const SDL_CONTROLLER_BINDTYPE_NONE = TSDL_GameControllerBindType(0); SDL_CONTROLLER_BINDTYPE_BUTTON = TSDL_GameControllerBindType(1); SDL_CONTROLLER_BINDTYPE_AXIS = TSDL_GameControllerBindType(2); SDL_CONTROLLER_BINDTYPE_HAT = TSDL_GameControllerBindType(3); {** * Get the SDL joystick layer binding for this controller button/axis mapping *} type THat = record hat: cint; hat_mask: cint; end; PPSDL_GameControllerButtonBind = ^PSDL_GameControllerButtonBind; PSDL_GameControllerButtonBind = ^TSDL_GameControllerButtonBind; TSDL_GameControllerButtonBind = record bindType: TSDL_GameControllerBindType; case cint of 0: ( button: cint; ); 1: ( axis: cint; ); 2: ( hat: THat; ); end; {** * To count the number of game controllers in the system for the following: * int nJoysticks = SDL_NumJoysticks(); * int nGameControllers = 0; * for ( int i = 0; i < nJoysticks; i++ ) [ * if ( SDL_IsGameController(i) ) [ * nGameControllers++; * * !! Pascal Conv.: Changed curly to square brackets in above example code to prevent opening comment blocks! * * Using the SDL_HINT_GAMECONTROLLERCONFIG hint or the SDL_GameControllerAddMapping you can add support for controllers SDL is unaware of or cause an existing controller to have a different binding. The format is: * guid,name,mappings * * Where GUID is the string value from SDL_JoystickGetGUIDString(), name is the human readable string for the device and mappings are controller mappings to joystick ones. * Under Windows there is a reserved GUID of "xinput" that covers any XInput devices. * The mapping format for joystick is: * bX - a joystick button, index X * hX.Y - hat X with value Y * aX - axis X of the joystick * Buttons can be used as a controller axis and vice versa. * * This string shows an example of a valid mapping for a controller * "341a3608000000000000504944564944,Afterglow PS3 Controller,a:b1,b:b2,y:b3,x:b0,start:b9,guide:b12,back:b8,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2,leftshoulder:b4,rightshoulder:b5,leftstick:b10,rightstick:b11,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:b6,righttrigger:b7", * *} {** * Add or update an existing mapping configuration * * 1 if mapping is added, 0 if updated, -1 on error *} function SDL_GameControllerAddMapping( mappingString: PAnsiChar ): cint cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerAddMapping' {$ENDIF} {$ENDIF}; {** * Load a set of mappings from a seekable SDL data stream (memory or file), filtered by the current SDL_GetPlatform() * A community sourced database of controllers is available at https://raw.github.com/gabomdq/SDL_GameControllerDB/master/gamecontrollerdb.txt * * If freerw is non-zero, the stream will be closed after being read. * * Returns number of mappings added, -1 on error *} function SDL_GameControllerAddMappingsFromRW(rw: PSDL_RWops; freerw: cint32):cint32; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerAddMappingsFromRW' {$ENDIF} {$ENDIF}; {** * Get the number of mappings installed. *} function SDL_GameControllerNumMappings():cint; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerNumMappings' {$ENDIF} {$ENDIF}; {** * Get a mapping string for a GUID * * the mapping string. Must be freed with SDL_free. Returns NULL if no mapping is available *} function SDL_GameControllerMappingForGUID( guid: TSDL_JoystickGUID ): PAnsiChar cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerMappingForGUID' {$ENDIF} {$ENDIF}; {** * Get the mapping at a particular index. * * Returns the mapping string. Must be freed with SDL_free(). * Returns NIL if the index is out of range. *} function SDL_GameControllerMappingForIndex(mapping_index: cint): PAnsiChar; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerMappingForIndex' {$ENDIF} {$ENDIF}; {** * Get a mapping string for an open GameController * * the mapping string. Must be freed with SDL_free. Returns NULL if no mapping is available *} function SDL_GameControllerMapping( gamecontroller: PSDL_GameController ): PAnsiChar cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerMapping' {$ENDIF} {$ENDIF}; {** * Is the joystick on this index supported by the game controller interface? *} function SDL_IsGameController(joystick_index: cint): TSDL_Bool cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_IsGameController' {$ENDIF} {$ENDIF}; {** * Get the implementation dependent name of a game controller. * This can be called before any controllers are opened. * If no name can be found, this function returns NULL. *} function SDL_GameControllerNameForIndex(joystick_index: cint): PAnsiChar cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerNameForIndex' {$ENDIF} {$ENDIF}; {** * Get the implementation dependent path for the game controller. * * This function can be called before any controllers are opened. * * `joystick_index` is the same as the `device_index` passed to * SDL_JoystickOpen(). * * \param joystick_index the device_index of a device, from zero to * SDL_NumJoysticks()-1 * \returns the implementation-dependent path for the game controller, or NIL * if there is no path or the index is invalid. * * \since This function is available since SDL 2.24.0. * * \sa SDL_GameControllerPath *} function SDL_GameControllerPathForIndex(joystick_index: cint): PAnsiChar; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerPathForIndex' {$ENDIF} {$ENDIF}; {** * Get the type of a game controller. * This can be called before any controllers are opened. *} function SDL_GameControllerTypeForIndex(joystick_index: cint): TSDL_GameControllerType; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerTypeForIndex' {$ENDIF} {$ENDIF}; {** * Get the mapping of a game controller. * This can be called before any controllers are opened. * * Returns the mapping string. Must be freed with SDL_free(). * Returns NIL if no mapping is available. *} function SDL_GameControllerMappingForDeviceIndex(joystick_index: cint): PAnsiChar; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerMappingForDeviceIndex' {$ENDIF} {$ENDIF}; {** * Open a game controller for use. * The index passed as an argument refers to the N'th game controller on the system. * This index is the value which will identify this controller in future controller * events. * * A controller identifier, or NULL if an error occurred. *} function SDL_GameControllerOpen(joystick_index: cint): PSDL_GameController cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerOpen' {$ENDIF} {$ENDIF}; {** * Return the SDL_GameController associated with an instance id. *} function SDL_GameControllerFromInstanceID(joyid: TSDL_JoystickID): PSDL_GameController; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerFromInstanceID' {$ENDIF} {$ENDIF}; {** * Get the SDL_GameController associated with a player index. * * Please note that the player index is _not_ the device index, nor is it the * instance id! * *} function SDL_GameControllerFromPlayerIndex(player_index: cint): PSDL_GameController; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerFromPlayerIndex' {$ENDIF} {$ENDIF}; {** * Return the name for this currently opened controller *} function SDL_GameControllerName(gamecontroller: PSDL_GameController): PAnsiChar cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerName' {$ENDIF} {$ENDIF}; {** * Get the implementation-dependent path for an opened game controller. * * This is the same path as returned by SDL_GameControllerNameForIndex(), but * it takes a controller identifier instead of the (unstable) device index. * * \param gamecontroller a game controller identifier previously returned by * SDL_GameControllerOpen() * \returns the implementation dependent path for the game controller, or NIL * if there is no path or the identifier passed is invalid. * * \since This function is available since SDL 2.24.0. * * \sa SDL_GameControllerPathForIndex *} function SDL_GameControllerPath(gamecontroller: PSDL_GameController): PAnsiChar; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerPath' {$ENDIF} {$ENDIF}; {** * Get the type of this currently opened controller * * This is the same name as returned by SDL_GameControllerTypeForIndex(), but * it takes a controller identifier instead of the (unstable) device index. *} function SDL_GameControllerGetType(gamecontroller: PSDL_GameController): TSDL_GameControllerType; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetType' {$ENDIF} {$ENDIF}; {** * Get the player index of an opened game controller. * For XInput controllers this returns the XInput user index. * * Returns the player index for controller, or -1 if it's not available. *} function SDL_GameControllerGetPlayerIndex(gamecontroller: PSDL_GameController): cint; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetPlayerIndex' {$ENDIF} {$ENDIF}; {** * Set the player index of an opened game controller. *} procedure SDL_GameControllerSetPlayerIndex(gamecontroller: PSDL_GameController; player_index: cint); cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerSetPlayerIndex' {$ENDIF} {$ENDIF}; {** * Get the USB vendor ID of an opened controller, if available. * * If the vendor ID isn't available this function returns 0. * * \param gamecontroller the game controller object to query. * \return the USB vendor ID, or zero if unavailable. * * \since This function is available since SDL 2.0.6. *} function SDL_GameControllerGetVendor(gamecontroller: PSDL_GameController): cuint16; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetVendor' {$ENDIF} {$ENDIF}; {** * Get the USB product ID of an opened controller, if available. * If the product ID isn't available, this function returns 0. *} function SDL_GameControllerGetProduct(gamecontroller: PSDL_GameController): cuint16; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetProduct' {$ENDIF} {$ENDIF}; {** * Get the product version of an opened controller, if available. * If the product version isn't available, this function returns 0. *} function SDL_GameControllerGetProductVersion(gamecontroller: PSDL_GameController): cuint16; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetProductVersion' {$ENDIF} {$ENDIF}; {** * Get the firmware version of an opened controller, if available. * * If the firmware version isn't available this function returns 0. * * \param gamecontroller the game controller object to query. * \return the controller firmware version, or zero if unavailable. * * \since This function is available since SDL 2.24.0. *} function SDL_GameControllerGetFirmwareVersion(gamecontroller: PSDL_GameController): cuint16; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetFirmwareVersion' {$ENDIF} {$ENDIF}; {** * Get the serial number of an opened controller, if available. * * Returns a string containing the serial number of the controller, * or NIL if it is not available. Do _not_ free the string with SDL_free(). *} function SDL_GameControllerGetSerial(gamecontroller: PSDL_GameController): PAnsiChar; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetSerial' {$ENDIF} {$ENDIF}; {** * Returns SDL_TRUE if the controller has been opened and currently connected, * or SDL_FALSE if it has not. *} function SDL_GameControllerGetAttached(gamecontroller: PSDL_GameController): TSDL_Bool cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetAttached' {$ENDIF} {$ENDIF}; {** * Get the underlying joystick object used by a controller *} function SDL_GameControllerGetJoystick(gamecontroller: PSDL_GameController): PSDL_Joystick cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetJoystick' {$ENDIF} {$ENDIF}; {** * Enable/disable controller event polling. * * If controller events are disabled, you must call SDL_GameControllerUpdate() * yourself and check the state of the controller when you want controller * information. * * The state can be one of ::SDL_QUERY, ::SDL_ENABLE or ::SDL_IGNORE. *} function SDL_GameControllerEventState(state: cint): cint cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerEventState' {$ENDIF} {$ENDIF}; {** * Update the current state of the open game controllers. * * This is called automatically by the event loop if any game controller * events are enabled. *} procedure SDL_GameControllerUpdate() cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerUpdate' {$ENDIF} {$ENDIF}; {** * The list of axes available from a controller *} type PPSDL_GameControllerAxis = ^PSDL_GameControllerAxis; PSDL_GameControllerAxis = ^TSDL_GameControllerAxis; TSDL_GameControllerAxis = type cint; const SDL_CONTROLLER_AXIS_INVALID = TSDL_GameControllerAxis(-1); SDL_CONTROLLER_AXIS_LEFTX = TSDL_GameControllerAxis(0); SDL_CONTROLLER_AXIS_LEFTY = TSDL_GameControllerAxis(1); SDL_CONTROLLER_AXIS_RIGHTX = TSDL_GameControllerAxis(2); SDL_CONTROLLER_AXIS_RIGHTY = TSDL_GameControllerAxis(3); SDL_CONTROLLER_AXIS_TRIGGERLEFT = TSDL_GameControllerAxis(4); SDL_CONTROLLER_AXIS_TRIGGERRIGHT = TSDL_GameControllerAxis(5); SDL_CONTROLLER_AXIS_MAX = TSDL_GameControllerAxis(6); {** * turn this string into a axis mapping *} function SDL_GameControllerGetAxisFromString(pchString: PAnsiChar): TSDL_GameControllerAxis cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetAxisFromString' {$ENDIF} {$ENDIF}; {** * turn this axis enum into a string mapping *} function SDL_GameControllerGetStringForAxis(axis: TSDL_GameControllerAxis): PAnsiChar cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetStringForAxis' {$ENDIF} {$ENDIF}; {** * Get the SDL joystick layer binding for this controller button mapping *} function SDL_GameControllerGetBindForAxis(gamecontroller: PSDL_GameController; axis: TSDL_GameControllerAxis): TSDL_GameControllerButtonBind cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetBindForAxis' {$ENDIF} {$ENDIF}; {** * Query whether a game controller has a given axis. * * This merely reports whether the controller's mapping defined this axis, * as that is all the information SDL has about the physical device. *} function SDL_GameControllerHasAxis(gamecontroller: PSDL_GameController; axis: TSDL_GameControllerAxis): TSDL_Bool; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerHasAxis' {$ENDIF} {$ENDIF}; {** * Get the current state of an axis control on a game controller. * * The state is a value ranging from -32768 to 32767. * * The axis indices start at index 0. *} function SDL_GameControllerGetAxis(gamecontroller: PSDL_GameController; axis: TSDL_GameControllerAxis): cint16 cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetAxis' {$ENDIF} {$ENDIF}; {** * The list of buttons available from a controller *} type PPSDL_GameControllerButton = ^PSDL_GameControllerButton; PSDL_GameControllerButton = ^TSDL_GameControllerButton; TSDL_GameControllerButton = type cint; const SDL_CONTROLLER_BUTTON_INVALID = TSDL_GameControllerButton(-1); SDL_CONTROLLER_BUTTON_A = TSDL_GameControllerButton(0); SDL_CONTROLLER_BUTTON_B = TSDL_GameControllerButton(1); SDL_CONTROLLER_BUTTON_X = TSDL_GameControllerButton(2); SDL_CONTROLLER_BUTTON_Y = TSDL_GameControllerButton(3); SDL_CONTROLLER_BUTTON_BACK = TSDL_GameControllerButton(4); SDL_CONTROLLER_BUTTON_GUIDE = TSDL_GameControllerButton(5); SDL_CONTROLLER_BUTTON_START = TSDL_GameControllerButton(6); SDL_CONTROLLER_BUTTON_LEFTSTICK = TSDL_GameControllerButton(7); SDL_CONTROLLER_BUTTON_RIGHTSTICK = TSDL_GameControllerButton(8); SDL_CONTROLLER_BUTTON_LEFTSHOULDER = TSDL_GameControllerButton(9); SDL_CONTROLLER_BUTTON_RIGHTSHOULDER = TSDL_GameControllerButton(10); SDL_CONTROLLER_BUTTON_DPAD_UP = TSDL_GameControllerButton(11); SDL_CONTROLLER_BUTTON_DPAD_DOWN = TSDL_GameControllerButton(12); SDL_CONTROLLER_BUTTON_DPAD_LEFT = TSDL_GameControllerButton(13); SDL_CONTROLLER_BUTTON_DPAD_RIGHT = TSDL_GameControllerButton(14); SDL_CONTROLLER_BUTTON_MISC1 = TSDL_GameControllerButton(15); {**< Xbox Series X share button, PS5 microphone button, Nintendo Switch Pro capture button, Amazon Luna microphone button *} SDL_CONTROLLER_BUTTON_PADDLE1 = TSDL_GameControllerButton(16); {**< Xbox Elite paddle P1 *} SDL_CONTROLLER_BUTTON_PADDLE2 = TSDL_GameControllerButton(17); {**< Xbox Elite paddle P3 *} SDL_CONTROLLER_BUTTON_PADDLE3 = TSDL_GameControllerButton(18); {**< Xbox Elite paddle P2 *} SDL_CONTROLLER_BUTTON_PADDLE4 = TSDL_GameControllerButton(19); {**< Xbox Elite paddle P4 *} SDL_CONTROLLER_BUTTON_TOUCHPAD = TSDL_GameControllerButton(20); {**< PS4/PS5 touchpad button *} SDL_CONTROLLER_BUTTON_MAX = TSDL_GameControllerButton(21); {** * turn this string into a button mapping *} function SDL_GameControllerGetButtonFromString(pchString: PAnsiChar): TSDL_GameControllerButton cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetButtonFromString' {$ENDIF} {$ENDIF}; {** * turn this button enum into a string mapping *} function SDL_GameControllerGetStringForButton(button: TSDL_GameControllerButton): PAnsiChar cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetStringForButton' {$ENDIF} {$ENDIF}; {** * Get the SDL joystick layer binding for this controller button mapping *} function SDL_GameControllerGetBindForButton(gamecontroller: PSDL_GameController; button: TSDL_GameControllerButton): TSDL_GameControllerButtonBind cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetBindForButton' {$ENDIF} {$ENDIF}; {** * Query whether a game controller has a given button. * * This merely reports whether the controller's mapping defined this button, * as that is all the information SDL has about the physical device. *} function SDL_GameControllerHasButton(gamecontroller: PSDL_GameController; button: TSDL_GameControllerButton): TSDL_Bool; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerHasButton' {$ENDIF} {$ENDIF}; {** * Get the current state of a button on a game controller. * * The button indices start at index 0. *} function SDL_GameControllerGetButton(gamecontroller: PSDL_GameController; button: TSDL_GameControllerButton): cuint8 cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetButton' {$ENDIF} {$ENDIF}; {** * Get the number of touchpads on a game controller. *} function SDL_GameControllerGetNumTouchpads(gamecontroller: PSDL_GameController): cint; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetNumTouchpads' {$ENDIF} {$ENDIF}; {** * Get the number of supported simultaneous fingers on a touchpad on a game controller. *} function SDL_GameControllerGetNumTouchpadFingers(gamecontroller: PSDL_GameController; touchpad: cint): cint; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetNumTouchpadFingers' {$ENDIF} {$ENDIF}; {** * Get the current state of a finger on a touchpad on a game controller. *} function SDL_GameControllerGetTouchpadFinger( gamecontroller: PSDL_GameController; touchpad, finger: cint; state: pcuint8; x, y, pressure: pcfloat ): cint; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetTouchpadFinger' {$ENDIF} {$ENDIF}; {** * Return whether a game controller has a particular sensor. *} function SDL_GameControllerHasSensor(gamecontroller: PSDL_GameController; senstype: TSDL_SensorType): TSDL_Bool; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerHasSensor' {$ENDIF} {$ENDIF}; {** * Set whether data reporting for a game controller sensor is enabled. *} function SDL_GameControllerSetSensorEnabled(gamecontroller: PSDL_GameController; senstype: TSDL_SensorType; enabled: TSDL_bool): cint; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerSetSensorEnabled' {$ENDIF} {$ENDIF}; {** * Query whether sensor data reporting is enabled for a game controller. *} function SDL_GameControllerIsSensorEnabled(gamecontroller: PSDL_GameController; senstype: TSDL_SensorType): TSDL_Bool; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerIsSensorEnabled' {$ENDIF} {$ENDIF}; {** * Get the data rate (number of events per second) of * a game controller sensor. * * Returns the data rate, or 0.0 if the data rate is not available. *} function SDL_GameControllerGetSensorDataRate(gamecontroller: PSDL_GameController; senstype: TSDL_SensorType): cfloat; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetSensorDataRate' {$ENDIF} {$ENDIF}; {** * Get the current state of a game controller sensor. * * The number of values and interpretation of the data is sensor dependent. * See sdlsensor.inc for the details for each type of sensor. *} function SDL_GameControllerGetSensorData(gamecontroller: PSDL_GameController; senstype: TSDL_SensorType; data: pcfloat; num_values: cint): cint; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetSensorData' {$ENDIF} {$ENDIF}; {** * Query whether a game controller has rumble support. *} function SDL_GameControllerHasRumble(gamecontroller: PSDL_GameController): TSDL_Bool; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerHasRumble' {$ENDIF} {$ENDIF}; {** * Start a rumble effect on a game controller. * * Each call to this function cancels any previous rumble effect, and calling * it with 0 intensity stops any rumbling. * * Returns 0, or -1 if rumble isn't supported on this controller. *} function SDL_GameControllerRumble( gamecontroller: PSDL_GameController; low_frequency_rumble, high_frequency_rumble: cuint16; duration_ms: cuint32 ): cint; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerRumble' {$ENDIF} {$ENDIF}; {** * Query whether a game controller has rumble support on triggers. *} function SDL_GameControllerHasRumbleTriggers(gamecontroller: PSDL_GameController): TSDL_Bool; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerHasRumbleTriggers' {$ENDIF} {$ENDIF}; {** * Start a rumble effect in the game controller's triggers. * * Each call to this function cancels any previous trigger rumble effect, and * calling it with 0 intensity stops any rumbling. * * Note that this is rumbling of the _triggers_ and not the game controller as * a whole. This is currently only supported on Xbox One controllers. If you * want the (more common) whole-controller rumble, use * SDL_GameControllerRumble() instead. * * Returns 0, or -1 if trigger rumble isn't supported on this controller *} function SDL_GameControllerRumbleTriggers( gamecontroller: PSDL_GameController; left_rumble, right_rumble: cuint16; duration_ms: cuint32 ): cint; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerRumbleTriggers' {$ENDIF} {$ENDIF}; {** * Query whether a game controller has an LED. *} function SDL_GameControllerHasLED(gamecontroller: PSDL_GameController): TSDL_Bool; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerHasLED' {$ENDIF} {$ENDIF}; {** * Update a game controller's LED color. * * Returns 0, or -1 if this controller does not have a modifiable LED. *} function SDL_GameControllerSetLED(gamecontroller: PSDL_GameController; red, green, blue: cuint8): cint; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerSetLED' {$ENDIF} {$ENDIF}; {** * Send a controller-specific effect packet. * * Returns 0, or -1 if this controller or driver does not * support effect packets. *} function SDL_GameControllerSendEffect(gamecontroller: PSDL_GameController; data: Pointer; size: cint): cint; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerSendEffect' {$ENDIF} {$ENDIF}; {** * Close a controller previously opened with SDL_GameControllerOpen(). *} procedure SDL_GameControllerClose(gamecontroller: PSDL_GameController) cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerClose' {$ENDIF} {$ENDIF}; {** * Return the sfSymbolsName for a given axis on a game controller * on Apple platforms. * * Returns the sfSymbolsName, or NIL if the name can't be found. * Do _not_ pass this string to SDL_free(). *} function SDL_GameControllerGetAppleSFSymbolsNameForAxis(gamecontroller: PSDL_GameController; axis: TSDL_GameControllerAxis): PAnsiChar; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetAppleSFSymbolsNameForAxis' {$ENDIF} {$ENDIF}; {** * Return the sfSymbolsName for a given button on a game controller * on Apple platforms. * * Returns the sfSymbolsName, or NIL if the name can't be found. * Do _not_ pass this string to SDL_free(). *} function SDL_GameControllerGetAppleSFSymbolsNameForButton(gamecontroller: PSDL_GameController; button: TSDL_GameControllerButton): PAnsiChar; cdecl; external {$IFDEF DYNAMIC_LINK}SDL_LibName{$ENDIF} {$IFDEF DELPHI} {$IFDEF MACOS} name '_SDL_GameControllerGetAppleSFSymbolsNameForButton' {$ENDIF} {$ENDIF}; function SDL_GameControllerAddMappingsFromFile(Const FilePath:PAnsiChar):cint32;
412
0.912034
1
0.912034
game-dev
MEDIA
0.988899
game-dev
0.79907
1
0.79907
stefanvranjes/Vigilante2Unity
2,530
Assets/Scripts/Fire1.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Fire1 : VigObject { protected override void Start() { base.Start(); } protected override void Update() { base.Update(); } public XOBF_DB DAT_98; //FUN_3982C public override uint UpdateW(int arg1, int arg2) { short sVar1; uint uVar2; VigObject oVar2; Vehicle vVar2; Fire2 ppcVar3; uint uVar4; int iVar6; Vehicle vVar6; int iVar9; if (arg1 == 0) { sVar1 = (short)(physics1.M0 - 1); physics1.M0 = sVar1; uVar2 = 0; if (sVar1 == -1) { ppcVar3 = DAT_98.ini.FUN_2C17C((ushort)physics2.M3, typeof(Fire2), 8) as Fire2; uVar4 = GameManager.FUN_2AC5C(); iVar6 = (int)(uVar4 & 0xfff) * 2; ppcVar3.flags |= 0x434; iVar9 = physics1.Y * GameManager.DAT_65C90[iVar6]; if (iVar9 < 0) iVar9 += 4095; ppcVar3.physics1.Z = iVar9 >> 12; iVar6 = physics1.Y * GameManager.DAT_65C90[iVar6 + 1]; if (iVar6 < 0) iVar6 += 4095; ppcVar3.physics2.X = iVar6 >> 12; iVar6 = (int)GameManager.FUN_2AC5C(); ppcVar3.physics1.W = physics1.Z + (iVar6 * physics1.Z >> 15); ppcVar3.screen = GameManager.instance.FUN_2CE50(this); ppcVar3.FUN_4EE40(); ppcVar3.FUN_30B78(); physics1.M0 = physics1.M1; vVar2 = Utilities.FUN_2CDB0(this) as Vehicle; vVar2.FUN_39DCC(-maxHalfHealth, vTransform.position, true); if (DAT_18 != 0) { uVar2 = GameManager.instance.FUN_1E478(ppcVar3.vTransform.position); GameManager.instance.FUN_1E2C8(DAT_18, uVar2); uVar2 = 0; } } } else { if (arg1 == 2) { vVar6 = Utilities.FUN_2CDB0(this) as Vehicle; vVar6.DAT_F6 &= 0xfff7; GameManager.instance.FUN_1DE78(DAT_18); oVar2 = FUN_2CCBC(); GameManager.instance.FUN_307CC(oVar2); uVar2 = 0xffffffff; } else uVar2 = 0; } return uVar2; } }
412
0.880971
1
0.880971
game-dev
MEDIA
0.951177
game-dev
0.957053
1
0.957053
olgirard/openmsp430
2,204
fpga/actel_m1a3pl_dev_kit/software/spacewar/score.c
#include "spacewar.h" //************************************************************ // externals // extern void reset_rkts(rkt_data *, rkt_data *); extern void reset_game(rkt_data *); extern void explode(int, int); extern void rocket1(rkt_data *); extern void rocket2(rkt_data *); extern int bzsin(char); //************************************************************ // // chk_shlds // // check rockets shields for game end // /* Description: Checks if shields of first rocket structure is zero. If zero then draws an explosion for the first structure rocket and adds a point to the second structure rocket game score. */ void chk_shlds(rkt_data *rkta, rkt_data *rktb) { if(rkta->shield == 0) { // rkt a dead ? explode(rkta->xdisp, rkta->ydisp); // yes - explode rktb->game++; // add one rktb's game total } } //************************************************************ // // score // // check for game end, show score // /* Description: Checks if shields of rocket 1 the rocket 2. Explodes and scores if shields equal zero. Sets rocket 1 position to top left and rocket 2 to bottom left. Starts displaying the number of games won by rocket pictures. Resets all rocket positions back to inital positions. */ void score(rkt_data *rkt1, rkt_data *rkt2) { int i, j; chk_shlds(rkt1, rkt2); // rkt1 dead ? chk_shlds(rkt2, rkt1); // rkt2 dead ? if((rkt1->shield == 0) || (rkt2->shield == 0)) { reset_rkts(rkt1, rkt2); // reset rkt positons rkt1->xsize = 0; rkt1->ysize = rktsiz; rkt2->xsize = 0; rkt2->ysize = rktsiz; reset_game(rkt1); reset_game(rkt2); for(i = 0; i < 512; i++) { // show score rkt1->xdisp = rktsiz << 2; // left side of screen rkt2->xdisp = rktsiz << 2; // left side of screen for(j = 0; j < rkt1->game; j++) { rocket1(rkt1); rkt1->xdisp += rktsiz << 1; } for(j = 0; j < rkt2->game; j++) { rocket2(rkt2); rkt2->xdisp += rktsiz << 1; } } reset_rkts(rkt1, rkt2); // reset rkt positons } }
412
0.829711
1
0.829711
game-dev
MEDIA
0.967121
game-dev
0.930933
1
0.930933
project-topaz/topaz
1,070
scripts/globals/mobskills/dynamic_implosion.lua
--------------------------------------------- -- Dynamic Implosion -- -- Description: Deals damage to players within an area of effect. Additional effect: Stun (Status Effect) -- Type: Physical -- Utsusemi/Blink absorb: Unknown -- Range: Unknown radial -- Notes: --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------- function onMobSkillCheck(target, mob, skill) return 0 end function onMobWeaponSkill(target, mob, skill) local numhits = 1 local accmod = 1 local dmgmod = 2.5 local info = MobPhysicalMove(mob, target, skill, numhits, accmod, dmgmod, TP_DMG_VARIES, 1, 2, 3) local dmg = MobFinalAdjustments(info.dmg, mob, skill, target, tpz.attackType.PHYSICAL, tpz.damageType.SLASHING, info.hitslanded) MobPhysicalStatusEffectMove(mob, target, skill, tpz.effect.STUN, 1, 0, 7) target:takeDamage(dmg, mob, tpz.attackType.PHYSICAL, tpz.damageType.SLASHING) return dmg end
412
0.791028
1
0.791028
game-dev
MEDIA
0.989536
game-dev
0.782689
1
0.782689
AlessioGr/NotQuests
3,118
paper/src/main/java/rocks/gravili/notquests/paper/events/hooks/BetonQuestEvents.java
/* * NotQuests - A Questing plugin for Minecraft Servers * Copyright (C) 2022 Alessio Gravili * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package rocks.gravili.notquests.paper.events.hooks; import org.betonquest.betonquest.BetonQuest; import org.betonquest.betonquest.api.ConversationOptionEvent; import org.betonquest.betonquest.api.PlayerObjectiveChangeEvent; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import rocks.gravili.notquests.paper.NotQuests; import rocks.gravili.notquests.paper.structs.QuestPlayer; import rocks.gravili.notquests.paper.structs.objectives.hooks.betonquest.BetonQuestObjectiveStateChangeObjective; public class BetonQuestEvents implements Listener { private final NotQuests main; public BetonQuestEvents(NotQuests main) { this.main = main; } @EventHandler public void onBetonQuestObjectiveStateChange(final PlayerObjectiveChangeEvent e) { final QuestPlayer questPlayer = main.getQuestPlayerManager().getActiveQuestPlayer(e.getProfile().getProfileUUID()); if (questPlayer == null || questPlayer.getActiveQuests().isEmpty()) { return; } questPlayer.queueObjectiveCheck(activeObjective -> { if (activeObjective.getObjective() instanceof final BetonQuestObjectiveStateChangeObjective betonQuestObjectiveStateChangeObjective) { if (activeObjective.isUnlocked()) { if(e.getState() == betonQuestObjectiveStateChangeObjective.getObjectiveState()){ if(e.getObjectiveID().getFullID().equalsIgnoreCase(betonQuestObjectiveStateChangeObjective.getObjectiveFullID())){ activeObjective.addProgress(1); } } } } }); questPlayer.checkQueuedObjectives(); } @EventHandler public void onBetonQuestObjectiveStateChange(final ConversationOptionEvent e) { final BetonQuest betonQuest = main.getIntegrationsManager().getBetonQuestManager().getBetonQuest(); if(e.getConversation().getInterceptor() != null && e.getConversation().getInterceptor().getClass() == betonQuest.getInterceptor("notquests") && main.getConversationManager() != null){ if(e.getProfile().getPlayer().isOnline()){ main.getConversationManager().removeOldMessages( e.getProfile().getPlayer().getPlayer() ); } } } }
412
0.854895
1
0.854895
game-dev
MEDIA
0.83687
game-dev
0.810849
1
0.810849
greisane/gret
23,116
mesh/collision.py
from itertools import chain from math import pi, radians, sqrt, isclose from mathutils import Matrix, Vector import bmesh import bpy import re from ..math import ( calc_best_fit_line, get_dist_sq, get_point_dist_to_line_sq, get_range_pct, ) from .helpers import clear_object_data from ..helpers import get_collection, instant_modifier # make_collision TODO: # - Non-axis aligned boxes # - Symmetrize for convex isn't good # - Wall collision should try to decompose into boxes # - Convex decomposition with v-hacd? collision_prefixes = ('UCX', 'UBX', 'UCP', 'USP') def get_collision_objects(context, obj): pattern = r"^(?:%s)_%s_\d+$" % ('|'.join(collision_prefixes), obj.name) return [o for o in context.scene.objects if re.match(pattern, o.name)] def find_free_col_name(prefix, name): n = 0 while True: col_name = f"{prefix}_{name}_{n}" n += 1 if col_name not in bpy.context.scene.objects: break return col_name class GRET_OT_collision_assign(bpy.types.Operator): """Assign selected collision meshes to the active object""" bl_idname = 'gret.collision_assign' bl_label = "Assign Collision" bl_options = {'REGISTER', 'UNDO'} @classmethod def poll(cls, context): return len(context.selected_objects) > 1 and context.object and context.mode == 'OBJECT' def execute(self, context): for obj in context.selected_objects[:]: if obj == context.active_object: continue prefix = obj.name[:3] if prefix in collision_prefixes: obj.name = find_free_col_name(prefix, context.active_object.name) if obj.data.users == 1: obj.data.name = obj.name return {'FINISHED'} class GRET_OT_collision_copy_to_linked(bpy.types.Operator): """Copy collision meshes from active to linked objects""" bl_idname = 'gret.collision_copy_to_linked' bl_label = "Copy Collision to Linked" bl_options = {'REGISTER', 'UNDO'} @classmethod def poll(cls, context): return bool(context.active_object) def execute(self, context): obj = context.active_object col_objs = get_collision_objects(context, obj) if not col_objs: self.report({'WARNING'}, "Active object has no collision assigned.") return {'CANCELLED'} if obj.data.users == 1: self.report({'WARNING'}, "Active object data has no other users.") return {'CANCELLED'} num_linked = 0 for other_obj in bpy.data.objects: if other_obj != obj and other_obj.data == obj.data: num_linked += 1 # Clean collision for old_col_obj in get_collision_objects(context, other_obj): bpy.data.objects.remove(old_col_obj) # Copy collision to other object's location obj_to_other = obj.matrix_world.inverted() @ other_obj.matrix_world for col_obj in col_objs: name = find_free_col_name(col_obj.name[:3], other_obj.name) new_col_obj = bpy.data.objects.new(name, col_obj.data) new_col_obj.matrix_world = (other_obj.matrix_world @ (obj.matrix_world.inverted() @ col_obj.matrix_world)) new_col_obj.show_wire = col_obj.show_wire new_col_obj.display_type = col_obj.display_type new_col_obj.display.show_shadows = col_obj.display.show_shadows for collection in col_obj.users_collection: collection.objects.link(new_col_obj) self.report({'INFO'}, f"Copied collision to {num_linked} other objects.") return {'FINISHED'} def is_box(bm): """Check if the mesh can be represented by a box collision shape.""" if len(bm.verts) != 8: return False c = sum((vert.co for vert in bm.verts), Vector()) / len(bm.verts) avg_d_sq = sum(get_dist_sq(vert.co, c) for vert in bm.verts) / len(bm.verts) return all(isclose(avg_d_sq, get_dist_sq(vert.co, c), abs_tol=0.0001) for vert in bm.verts) class GRET_OT_collision_make(bpy.types.Operator): """Generate collision for selected geometry""" bl_idname = 'gret.collision_make' bl_label = "Make Collision" bl_options = {'REGISTER', 'UNDO'} shape: bpy.props.EnumProperty( name="Shape", description="Selects the collision shape", items=[ ('AABB', "AABB", "Axis-aligned box collision", 'MESH_PLANE', 0), ('CYLINDER', "Cylinder", "Cylinder collision", 'MESH_CYLINDER', 1), ('CAPSULE', "Capsule", "Capsule collision", 'MESH_CAPSULE', 2), ('SPHERE', "Sphere", "Sphere collision", 'MESH_UVSPHERE', 3), ('CONVEX', "Convex", "Convex collision", 'MESH_ICOSPHERE', 4), ], ) output: bpy.props.EnumProperty( name="Output", description="Where to output collision objects", items=[ ('CHILD', "As Child", "Parent collision objects to the mesh"), ('SIBLING', "As Sibling", "Put collision objects next to the mesh"), ('COLLECTION', "To Collection", "Move collision objects to a new collection"), ('SCENE', "To Scene Collection", "Move collision objects to the scene collection"), ], default='COLLECTION', ) collection: bpy.props.StringProperty( name="Collection", description="Name of the new collection", default="Collision", ) wire: bpy.props.BoolProperty( name="Wire", description="How to display collision objects in viewport", default=False, ) hollow: bpy.props.BoolProperty( name="Hollow", description="Create a hollow shape from multiple bodies", default=False, ) thickness: bpy.props.FloatProperty( name="Thickness", description="Wall thickness", subtype='DISTANCE', default=0.2, min=0.001, ) offset: bpy.props.FloatProperty( name="Offset", description="Offset the thickness from the center", subtype='FACTOR', default=-1.0, min=-1.0, max=1.0, ) location: bpy.props.FloatVectorProperty( name="Location", description="Shape location", subtype='TRANSLATION', size=3, ) # AABB settings aabb_width: bpy.props.FloatProperty( name="Width", description="Bounding box width", subtype='DISTANCE', min=0.001, ) aabb_height: bpy.props.FloatProperty( name="Height", description="Bounding box height", subtype='DISTANCE', min=0.001, ) aabb_depth: bpy.props.FloatProperty( name="Depth", description="Bounding box depth", subtype='DISTANCE', min=0.001, ) # Cylinder settings cyl_caps: bpy.props.BoolProperty( name="Caps", description="Create shapes for the top and bottom of the cylinder", default=False, ) cyl_sides: bpy.props.IntProperty( name="Sides", description="Number of sides", default=8, min=3, ) cyl_rotate: bpy.props.BoolProperty( name="Rotate", description="Rotate cylinder by half", ) cyl_radius1: bpy.props.FloatProperty( name="Radius 1", description="First cylinder radius", subtype='DISTANCE', min=0.001, ) cyl_radius2: bpy.props.FloatProperty( name="Radius 2", description="Second cylinder radius", subtype='DISTANCE', min=0.001, ) cyl_height: bpy.props.FloatProperty( name="Height", description="Cylinder height", subtype='DISTANCE', min=0.001, ) # Capsule settings cap_radius: bpy.props.FloatProperty( name="Radius", description="Capsule radius", subtype='DISTANCE', min=0.001, ) cap_depth: bpy.props.FloatProperty( name="Depth", description="Capsule depth", subtype='DISTANCE', min=0.001, ) cap_rotation: bpy.props.FloatVectorProperty( name="Rotation", description="Capsule rotation", subtype='EULER', size=3, ) # Sphere settings sph_radius: bpy.props.FloatProperty( name="Radius", description="Sphere radius", subtype='DISTANCE', min=0.001, ) # Convex settings planar_angle: bpy.props.FloatProperty( name="Max Face Angle", description="Use to remove decimation bias towards large, bumpy faces", subtype='ANGLE', default=radians(10.0), min=0.0, max=radians(180.0), soft_max=radians(90.0), ) decimate_ratio: bpy.props.FloatProperty( name="Decimate Ratio", description="Percentage of edges to collapse", subtype='FACTOR', default=1.0, min=0.0, max=1.0, ) use_symmetry: bpy.props.BoolProperty( name="Symmetry", description="Maintain symmetry on an axis", default=False, ) symmetry_axis: bpy.props.EnumProperty( name="Symmetry Axis", description="Axis of symmetry", items=[ ('X', "X", "X"), ('Y', "Y", "Y"), ('Z', "Z", "Z"), ], ) # Wall settings wall_fill_holes: bpy.props.BoolProperty( name="Fill holes", description="Fill rectangular holes in walls", default=False, ) @classmethod def poll(cls, context): obj = context.active_object return obj and obj.type == 'MESH' and obj.mode in {'OBJECT', 'EDIT'} def create_col_object_from_bm(self, context, obj, bm, matrix, prefix=None): if not prefix: # Autodetect (should detect sphere too) prefix = 'UBX' if is_box(bm) else 'UCX' name = find_free_col_name(prefix, obj.name) data = bpy.data.meshes.new(name) bmesh.ops.recalc_face_normals(bm, faces=bm.faces) bm.to_mesh(data) parent = None if self.output == 'COLLECTION' and self.collection: collection = get_collection(context, self.collection, allow_duplicate=True, clean=False) collection.color_tag = 'COLOR_04' elif self.output in 'CHILD': collection = obj.users_collection[0] parent = obj elif self.output == 'SIBLING': collection = obj.users_collection[0] parent = obj.parent else: collection = context.scene.collection col_obj = bpy.data.objects.new(name, data) col_obj.parent = parent col_obj.matrix_world = obj.matrix_world @ matrix col_obj.show_wire = True col_obj.display_type = 'WIRE' if self.wire else 'SOLID' col_obj.display.show_shadows = False # bmeshes created with from_mesh or from_object may have some UVs or customdata clear_object_data(col_obj) collection.objects.link(col_obj) return col_obj def create_split_col_object_from_bm(self, context, obj, bm, mat, thickness, offset=0.0): # Based on https://github.com/blender/blender-addons/blob/master/mesh_tools/split_solidify.py # by zmj100, updated by zeffii to BMesh distance = thickness * (offset + 1.0) * 0.5 bm = bm bm.faces.ensure_lookup_table() bm.verts.ensure_lookup_table() bm.normal_update() for face in bm.faces: bm2 = bmesh.new() # Add new vertices verts1, verts2 = [], [] for vert in face.verts: p1 = vert.co + face.normal * distance # Out p2 = vert.co + face.normal * (distance - thickness) # In verts1.append(bm2.verts.new(p1)) verts2.append(bm2.verts.new(p2)) # Add new faces n = len(verts1) bm2.faces.new(verts1) for i in range(n): j = (i + 1) % n vseq = verts1[i], verts2[i], verts2[j], verts1[j] bm2.faces.new(vseq) verts2.reverse() bm2.faces.new(verts2) self.create_col_object_from_bm(context, obj, bm2, mat) bm2.free() def make_aabb_collision(self, context, obj): mat = Matrix.Translation(self.location) half_extents = Vector((self.aabb_depth, self.aabb_width, self.aabb_height)) * 0.5 bm = bmesh.new() verts = bmesh.ops.create_cube(bm, calc_uvs=False)['verts'] verts[0].co = -half_extents.x, -half_extents.y, -half_extents.z verts[1].co = -half_extents.x, -half_extents.y, +half_extents.z verts[2].co = -half_extents.x, +half_extents.y, -half_extents.z verts[3].co = -half_extents.x, +half_extents.y, +half_extents.z verts[4].co = +half_extents.x, -half_extents.y, -half_extents.z verts[5].co = +half_extents.x, -half_extents.y, +half_extents.z verts[6].co = +half_extents.x, +half_extents.y, -half_extents.z verts[7].co = +half_extents.x, +half_extents.y, +half_extents.z if self.hollow: self.create_split_col_object_from_bm(context, obj, bm, mat, self.thickness, self.offset) else: self.create_col_object_from_bm(context, obj, bm, mat) bm.free() def make_cylinder_collision(self, context, obj): mat = Matrix.Translation(self.location) if self.cyl_rotate: mat @= Matrix.Rotation(pi / self.cyl_sides, 4, 'Z') bm = bmesh.new() cap_ends = not self.hollow or self.cyl_caps bmesh.ops.create_cone(bm, cap_ends=cap_ends, cap_tris=False, segments=self.cyl_sides, radius1=self.cyl_radius1, radius2=self.cyl_radius2, depth=self.cyl_height, calc_uvs=False) if self.hollow: self.create_split_col_object_from_bm(context, obj, bm, mat, self.thickness, self.offset) else: self.create_col_object_from_bm(context, obj, bm, mat) bm.free() def make_capsule_collision(self, context, obj): bm_mat = Matrix.Rotation(pi * 0.5, 4, 'X') mat = Matrix.Translation(self.location) @ self.cap_rotation.to_matrix().to_4x4() @ bm_mat bm = bmesh.new() bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=8, radius1=self.cap_radius, radius2=self.cap_radius, depth=self.cap_depth, calc_uvs=False, matrix=bm_mat) bm.faces.ensure_lookup_table() caps = [bm.faces[-1], bm.faces[-4]] bmesh.ops.poke(bm, faces=caps, offset=self.cap_radius) self.create_col_object_from_bm(context, obj, bm, mat, prefix='UCP') bm.free() def make_sphere_collision(self, context, obj): mat = Matrix.Translation(self.location) bm = bmesh.new() bmesh.ops.create_icosphere(bm, subdivisions=2, radius=self.sph_radius*0.5, calc_uvs=False) self.create_col_object_from_bm(context, obj, bm, mat, prefix='USP') bm.free() def make_convex_collision(self, context, obj): if context.mode == 'EDIT_MESH': bm = bmesh.from_edit_mesh(obj.data).copy() bm.verts.ensure_lookup_table() bmesh.ops.delete(bm, geom=[v for v in bm.verts if not v.select], context='VERTS') else: bm = bmesh.new() dg = context.evaluated_depsgraph_get() bm.from_object(obj, dg) # Clean incoming mesh bm.edges.ensure_lookup_table() for edge in bm.edges: edge.seam = False edge.smooth = True bm.faces.ensure_lookup_table() for face in bm.faces: face.smooth = False # While convex_hull works only on verts, pass all the geometry so that it gets tagged geom = list(chain(bm.verts, bm.edges, bm.faces)) result = bmesh.ops.convex_hull(bm, input=geom, use_existing_faces=True) # geom_interior: elements that ended up inside the hull rather than part of it # geom_unused: elements that ended up inside the hull and are are unused by other geometry # The two sets may intersect, so for now just delete one of them. I haven't found a case yet # where this leaves out unwanted geometry bmesh.ops.delete(bm, geom=result['geom_interior'], context='TAGGED_ONLY') bm.normal_update() bmesh.ops.dissolve_limit(bm, angle_limit=self.planar_angle, verts=bm.verts, edges=bm.edges, use_dissolve_boundaries=False, delimit=set()) bmesh.ops.triangulate(bm, faces=bm.faces) median = sum((vert.co for vert in bm.verts), Vector()) / len(bm.verts) bmesh.ops.translate(bm, verts=bm.verts, vec=-median) mat = Matrix.Translation(median) col_obj = self.create_col_object_from_bm(context, obj, bm, mat, prefix='UCX') bm.free() # Decimate (no bmesh op for this currently?) with instant_modifier(col_obj, type='DECIMATE') as decimate_mod: decimate_mod.ratio = self.decimate_ratio decimate_mod.use_symmetry = self.use_symmetry decimate_mod.symmetry_axis = self.symmetry_axis def execute(self, context): obj = context.active_object if obj.mode != 'EDIT': # When working from object mode, it follows that there should be only one collision shape pattern = re.compile(rf"^U[A-Z][A-Z]_{obj.name}_\d+") for mesh in [mesh for mesh in bpy.data.meshes if pattern.match(mesh.name)]: bpy.data.meshes.remove(mesh) if self.shape == 'AABB': self.make_aabb_collision(context, obj) elif self.shape == 'CYLINDER': self.make_cylinder_collision(context, obj) elif self.shape == 'CAPSULE': self.make_capsule_collision(context, obj) elif self.shape == 'SPHERE': self.make_sphere_collision(context, obj) elif self.shape == 'CONVEX': self.make_convex_collision(context, obj) return {'FINISHED'} def invoke(self, context, event): # Calculate initial properties try: self.calculate_parameters(context, context.object) except RuntimeError as e: self.report({'ERROR'}, str(e)) return {'CANCELLED'} # Ideally this would execute once then show the popup dialog, doesn't seem possible return context.window_manager.invoke_props_dialog(self) def calculate_parameters(self, context, obj): if obj.mode == 'EDIT': bm = bmesh.from_edit_mesh(obj.data) vert_cos = [vert.co for vert in bm.verts if vert.select] else: dg = context.evaluated_depsgraph_get() obj_eval = obj.evaluated_get(dg) vert_cos = [vert.co for vert in obj_eval.data.vertices] if len(vert_cos) < 3: raise RuntimeError("Requires at least three vertices") axis, _ = calc_best_fit_line(vert_cos) corner1 = vert_cos[0].copy() corner2 = vert_cos[1].copy() for co in vert_cos: corner1.x = min(corner1.x, co.x) corner1.y = min(corner1.y, co.y) corner1.z = min(corner1.z, co.z) corner2.x = max(corner2.x, co.x) corner2.y = max(corner2.y, co.y) corner2.z = max(corner2.z, co.z) # Bounding box dimensions self.aabb_depth = abs(corner1.x - corner2.x) self.aabb_width = abs(corner1.y - corner2.y) self.aabb_height = abs(corner1.z - corner2.z) self.location = center = (corner1 + corner2) * 0.5 # Cylinder radius self.cyl_radius1 = self.cyl_radius2 = 0.001 for co in vert_cos: dx = center.x - co.x dy = center.y - co.y d = sqrt(dx * dx + dy * dy) influence2 = get_range_pct(corner1.z, corner2.z, co.z) influence1 = 1.0 - influence2 self.cyl_radius1 = max(self.cyl_radius1, d * influence1) self.cyl_radius2 = max(self.cyl_radius2, d * influence2) self.cyl_height = self.aabb_height # Capsule axis and radius radius_sq = 0.001 depth_sq = 0.0 for co in vert_cos: dist_to_axis_sq = get_point_dist_to_line_sq(co, axis, center) if dist_to_axis_sq > radius_sq: radius_sq = dist_to_axis_sq dist_along_axis_sq = (co - center).project(axis).length_squared if dist_along_axis_sq > depth_sq: depth_sq = dist_along_axis_sq self.cap_radius = sqrt(radius_sq) self.cap_rotation = axis.to_track_quat('Z', 'X').to_euler('XYZ') self.cap_depth = sqrt(depth_sq) * 2.0 - self.cap_radius # Sphere radius self.sph_radius = max(self.aabb_depth, self.aabb_width, self.aabb_height) def draw(self, context): layout = self.layout layout.use_property_split = True col = layout.column() row = col.row(align=True) row.prop(self, 'shape') row.prop(self, 'wire', icon='MOD_WIREFRAME', text="") col.prop(self, 'output') if self.output == 'COLLECTION': col.prop(self, 'collection') if self.shape in {'AABB', 'CYLINDER'}: col.separator() col.prop(self, 'hollow') if self.hollow: col.prop(self, 'thickness') col.prop(self, 'offset') if self.shape == 'AABB': col.prop(self, 'aabb_width') col.prop(self, 'aabb_height') col.prop(self, 'aabb_depth') elif self.shape == 'CYLINDER': col.prop(self, 'cyl_rotate') col.prop(self, 'cyl_sides') col.prop(self, 'cyl_radius1') col.prop(self, 'cyl_radius2') col.prop(self, 'cyl_height') col.prop(self, 'cyl_caps') elif self.shape == 'CAPSULE': col.prop(self, 'cap_radius') col.prop(self, 'cap_depth') elif self.shape == 'SPHERE': col.prop(self, 'sph_radius') elif self.shape == 'CONVEX': col.prop(self, 'planar_angle') col.prop(self, 'decimate_ratio') row = col.row(align=True, heading="Symmetrize") row.prop(self, 'use_symmetry', text="") row.prop(self, 'symmetry_axis', expand=True) def draw_panel(self, context): layout = self.layout row = layout.split(align=True, factor=0.75) row.operator('gret.collision_make', icon='MESH_CUBE') row.operator('gret.collision_assign', text="Assign") classes = ( GRET_OT_collision_assign, GRET_OT_collision_copy_to_linked, GRET_OT_collision_make, ) def register(settings, prefs): if not prefs.mesh__enable_make_collision: return False for cls in classes: bpy.utils.register_class(cls) def unregister(): for cls in reversed(classes): bpy.utils.unregister_class(cls)
412
0.871368
1
0.871368
game-dev
MEDIA
0.876156
game-dev
0.958452
1
0.958452
scottalford75/Remora
2,273
Firmware/FirmwareSource/Remora-OS6/lib/ArduinoJson6/ArduinoJson/Object/ObjectIterator.hpp
// ArduinoJson - arduinojson.org // Copyright Benoit Blanchon 2014-2019 // MIT License #pragma once #include "../Variant/SlotFunctions.hpp" #include "Pair.hpp" namespace ARDUINOJSON_NAMESPACE { class PairPtr { public: PairPtr(MemoryPool *pool, VariantSlot *slot) : _pair(pool, slot) {} const Pair *operator->() const { return &_pair; } const Pair &operator*() const { return _pair; } private: Pair _pair; }; class ObjectIterator { public: ObjectIterator() : _slot(0) {} explicit ObjectIterator(MemoryPool *pool, VariantSlot *slot) : _pool(pool), _slot(slot) {} Pair operator*() const { return Pair(_pool, _slot); } PairPtr operator->() { return PairPtr(_pool, _slot); } bool operator==(const ObjectIterator &other) const { return _slot == other._slot; } bool operator!=(const ObjectIterator &other) const { return _slot != other._slot; } ObjectIterator &operator++() { _slot = _slot->next(); return *this; } ObjectIterator &operator+=(size_t distance) { _slot = _slot->next(distance); return *this; } VariantSlot *internal() { return _slot; } private: MemoryPool *_pool; VariantSlot *_slot; }; class PairConstPtr { public: PairConstPtr(const VariantSlot *slot) : _pair(slot) {} const PairConst *operator->() const { return &_pair; } const PairConst &operator*() const { return _pair; } private: PairConst _pair; }; class ObjectConstIterator { public: ObjectConstIterator() : _slot(0) {} explicit ObjectConstIterator(const VariantSlot *slot) : _slot(slot) {} PairConst operator*() const { return PairConst(_slot); } PairConstPtr operator->() { return PairConstPtr(_slot); } bool operator==(const ObjectConstIterator &other) const { return _slot == other._slot; } bool operator!=(const ObjectConstIterator &other) const { return _slot != other._slot; } ObjectConstIterator &operator++() { _slot = _slot->next(); return *this; } ObjectConstIterator &operator+=(size_t distance) { _slot = _slot->next(distance); return *this; } const VariantSlot *internal() { return _slot; } private: const VariantSlot *_slot; }; } // namespace ARDUINOJSON_NAMESPACE
412
0.867357
1
0.867357
game-dev
MEDIA
0.29379
game-dev
0.820443
1
0.820443
geotools/geotools
3,154
modules/library/main/src/main/java/org/geotools/filter/identity/FeatureIdImpl.java
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2002-2008, Open Source Geospatial Foundation (OSGeo) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotools.filter.identity; import org.geotools.api.feature.Feature; import org.geotools.api.filter.identity.FeatureId; /** * Implementation of {@link org.geotools.api.filter.identity.FeatureId} * * <p>This class is mutable under one condition only; during a commit a datastore can update the internal fid to reflect * the real identify assigned by the database or wfs. * * <p> * * @author Justin Deoliveira, The Open Planning Project * @since 2.5 * @version 8.0 */ public class FeatureIdImpl implements FeatureId { /** underlying fid */ protected String fid; protected String origionalFid; public FeatureIdImpl(String fid) { this.fid = fid; if (fid == null) { throw new NullPointerException("fid must not be null"); } } @Override public String getID() { return fid; } public void setID(String id) { if (id == null) { throw new NullPointerException("fid must not be null"); } if (origionalFid == null) { origionalFid = fid; } fid = id; } public boolean matches(Feature feature) { if (feature == null) { return false; } return equalsExact(feature.getIdentifier()); } @Override public boolean matches(Object object) { if (object instanceof Feature feature) { return matches(feature); } return false; } @Override public String toString() { return fid; } @Override public boolean equals(Object obj) { if (obj instanceof FeatureId id) { return fid.equals(id.getID()); } return false; } @Override public int hashCode() { return fid.hashCode(); } @Override public boolean equalsExact(FeatureId id) { if (id != null) { return fid.equals(id.getID()) && fid.equals(id.getRid()) && id.getPreviousRid() == null && id.getFeatureVersion() == null; } return false; } @Override public boolean equalsFID(FeatureId id) { if (id == null) return false; return getID().equals(id.getID()); } @Override public String getRid() { return getID(); } @Override public String getPreviousRid() { return null; } @Override public String getFeatureVersion() { return null; } }
412
0.746117
1
0.746117
game-dev
MEDIA
0.182812
game-dev
0.508969
1
0.508969
huzhenjie/ImageSelector
2,113
selectorlibrary/src/main/java/com/scrat/app/selectorlibrary/view/GridSpacingItemDecoration.java
package com.scrat.app.selectorlibrary.view; import android.graphics.Rect; import android.support.v7.widget.RecyclerView; import android.view.View; /** * Created by yixuanxuan on 16/8/23. */ public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration { private int spanCount; private int spacing; private int bottomSpacing; private int topSpacing; private boolean includeEdge; public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge, int topSpacing, int bottomSpacing) { this.spanCount = spanCount; this.spacing = spacing; this.includeEdge = includeEdge; this.topSpacing = topSpacing; this.bottomSpacing = bottomSpacing; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { int position = parent.getChildAdapterPosition(view); // item position int column = position % spanCount; // item column if (includeEdge) { outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing) outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing) if (position < spanCount) { // top edge outRect.top = spacing; } outRect.bottom = spacing; // item bottom } else { outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing) outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing) if (position >= spanCount) { outRect.top = spacing; // item top } } if (position < spanCount) { outRect.top = topSpacing; } int totalCount = parent.getAdapter().getItemCount(); int pos = totalCount - (totalCount % spanCount == 0 ? spanCount : totalCount % spanCount) - 1; if (position > pos) { outRect.bottom = bottomSpacing; } } }
412
0.845094
1
0.845094
game-dev
MEDIA
0.483282
game-dev,desktop-app
0.970678
1
0.970678
discordia-space/CEV-Eris
2,743
code/game/objects/items/weapons/melee/misc.dm
/obj/item/melee/toolbox_maul name = "toolmop the maul" desc = "Toolbox tied to mop. A weapon of choice." icon = 'icons/obj/weapons.dmi' icon_state = "hm_hammer" item_state = "hm_hammer" force = WEAPON_FORCE_PAINFUL throwforce = WEAPON_FORCE_PAINFUL w_class = ITEM_SIZE_BULKY origin_tech = list(TECH_COMBAT = 3) attack_verb = list("robusted", "slammed") structure_damage_factor = STRUCTURE_DAMAGE_HEAVY var/reinforced = FALSE var/obj/item/storage/toolbox/toolbox New() ..() if(!toolbox) src.name = "unfinished [src.name]" src.desc = "Wired mop. You need toolbox to finish this." icon_state = "hm_hammer_unfinished" item_state = "" force = WEAPON_FORCE_WEAK throwforce = WEAPON_FORCE_WEAK origin_tech = list(TECH_COMBAT = 1) /obj/item/melee/toolbox_maul/update_icon() ..() cut_overlays() if(reinforced) overlays += "[icon_state]-duct_tape" /obj/item/melee/toolbox_maul/proc/break_apart(var/mob/living/user) qdel(src) var/obj/item/mop/mop = new(user.loc) if(!user.get_active_hand()) user.put_in_active_hand(mop) else user.put_in_inactive_hand(mop) toolbox.loc = user.loc /obj/item/melee/toolbox_maul/attackby(obj/item/C, mob/living/user) if(toolbox) if(istype(C, /obj/item/tool/wirecutters)) if(reinforced) to_chat(user, SPAN_NOTICE("You cutted up the tapes from [src].")) reinforced = FALSE else to_chat(user, SPAN_NOTICE("You carefully cut cables from [src].")) break_apart(user) if(istype(C, /obj/item/tool/tape_roll)) to_chat(user, SPAN_NOTICE("You begins to tie [src] with [C]...")) if(do_after(user, 50)) if(!reinforced) to_chat(user, SPAN_NOTICE("You reinforce [src].")) reinforced = TRUE else to_chat(user, SPAN_WARNING("[src] is already reinforced.")) else if(istype(C, /obj/item/storage/toolbox)) src.name = initial(src.name) src.desc = initial(src.desc) src.force = initial(src.force) throwforce = initial(throwforce) origin_tech = initial(origin_tech) icon_state = initial(icon_state) item_state = initial(item_state) toolbox = C user.drop_from_inventory(C, src) if(istype(C, /obj/item/storage/toolbox/electrical)) icon_state = "hm_hammer_yellow" item_state = "hm_hammer_yellow" if(istype(C, /obj/item/storage/toolbox/mechanical)) icon_state = "hm_hammer_blue" item_state = "hm_hammer_blue" to_chat(user, SPAN_NOTICE("You tied [C] to [src] and finally finish it!")) update_icon() /obj/item/melee/toolbox_maul/attack(mob/living/carbon/human/M as mob, mob/living/carbon/user as mob) ..() if(!reinforced && prob(5)) break_apart(user) playsound(src.loc, 'sound/effects/bang.ogg', 45, 1) user.visible_message(SPAN_WARNING("[src] breaks in hands of [user]!"))
412
0.89234
1
0.89234
game-dev
MEDIA
0.849439
game-dev
0.953566
1
0.953566
0xd4d/dnlib
31,783
src/DotNet/Writer/NativeModuleWriter.cs
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; using dnlib.IO; using dnlib.PE; using dnlib.W32Resources; using dnlib.DotNet.MD; using System.Diagnostics; namespace dnlib.DotNet.Writer { /// <summary> /// <see cref="NativeModuleWriter"/> options /// </summary> public sealed class NativeModuleWriterOptions : ModuleWriterOptionsBase { /// <summary> /// If <c>true</c>, any extra data after the PE data in the original file is also saved /// at the end of the new file. Enable this option if some protector has written data to /// the end of the file and uses it at runtime. /// </summary> public bool KeepExtraPEData { get; set; } /// <summary> /// If <c>true</c>, keep the original Win32 resources /// </summary> public bool KeepWin32Resources { get; set; } internal bool OptimizeImageSize { get; } /// <summary> /// Constructor /// </summary> /// <param name="module">Module</param> /// <param name="optimizeImageSize">true to optimize the image size so it's as small as possible. /// Since the file can contain native methods and other native data, we re-use the /// original file when writing the new file. If <paramref name="optimizeImageSize"/> is true, /// we'll try to re-use the old method body locations in the original file and /// also try to fit the new metadata in the old metadata location.</param> public NativeModuleWriterOptions(ModuleDefMD module, bool optimizeImageSize) : base(module) { // C++ .NET mixed mode assemblies sometimes/often call Module.ResolveMethod(), // so method metadata tokens must be preserved. MetadataOptions.Flags |= MetadataFlags.PreserveAllMethodRids; if (optimizeImageSize) { OptimizeImageSize = true; // Prevent the #Blob heap from getting bigger. Encoded TypeDefOrRef tokens are stored there (in // typesigs and callingconvsigs) so we must preserve TypeDefOrRef tokens (or the #Blob heap could // grow in size and new MD won't fit in old location) MetadataOptions.Flags |= MetadataFlags.PreserveTypeRefRids | MetadataFlags.PreserveTypeDefRids | MetadataFlags.PreserveTypeSpecRids; } } } /// <summary> /// A module writer that supports saving mixed-mode modules (modules with native code). /// The original image will be re-used. See also <see cref="ModuleWriter"/> /// </summary> public sealed class NativeModuleWriter : ModuleWriterBase { /// <summary>The original .NET module</summary> readonly ModuleDefMD module; /// <summary>All options</summary> NativeModuleWriterOptions options; /// <summary> /// Any extra data found at the end of the original file. This is <c>null</c> if there's /// no extra data or if <see cref="NativeModuleWriterOptions.KeepExtraPEData"/> is /// <c>false</c>. /// </summary> DataReaderChunk extraData; /// <summary>The original PE sections and their data</summary> List<OrigSection> origSections; readonly struct ReusedChunkInfo { public IReuseChunk Chunk { get; } public RVA RVA { get; } public ReusedChunkInfo(IReuseChunk chunk, RVA rva) { Chunk = chunk; RVA = rva; } } List<ReusedChunkInfo> reusedChunks; /// <summary>Original PE image</summary> readonly IPEImage peImage; /// <summary>New sections we've added and their data</summary> List<PESection> sections; /// <summary>New .text section where we put some stuff, eg. .NET metadata</summary> PESection textSection; /// <summary>The new COR20 header</summary> ByteArrayChunk imageCor20Header; /// <summary> /// New .rsrc section where we put the new Win32 resources. This is <c>null</c> if there /// are no Win32 resources or if <see cref="NativeModuleWriterOptions.KeepWin32Resources"/> /// is <c>true</c> /// </summary> PESection rsrcSection; /// <summary> /// Offset in <see cref="ModuleWriterBase.destStream"/> of the PE checksum field. /// </summary> long checkSumOffset; /// <summary> /// Original PE section /// </summary> public sealed class OrigSection : IDisposable { /// <summary>PE section</summary> public ImageSectionHeader PESection; /// <summary>PE section data</summary> public DataReaderChunk Chunk; /// <summary> /// Constructor /// </summary> /// <param name="peSection">PE section</param> public OrigSection(ImageSectionHeader peSection) => PESection = peSection; /// <inheritdoc/> public void Dispose() { Chunk = null; PESection = null; } /// <inheritdoc/> public override string ToString() { uint offs = Chunk.CreateReader().StartOffset; return $"{PESection.DisplayName} FO:{offs:X8} L:{Chunk.CreateReader().Length:X8}"; } } /// <summary> /// Gets the module /// </summary> public ModuleDefMD ModuleDefMD => module; /// <inheritdoc/> public override ModuleDef Module => module; /// <inheritdoc/> public override ModuleWriterOptionsBase TheOptions => Options; /// <summary> /// Gets/sets the writer options. This is never <c>null</c> /// </summary> public NativeModuleWriterOptions Options { get => options ??= new NativeModuleWriterOptions(module, optimizeImageSize: true); set => options = value; } /// <summary> /// Gets all <see cref="PESection"/>s /// </summary> public override List<PESection> Sections => sections; /// <summary> /// Gets the original PE sections and their data /// </summary> public List<OrigSection> OrigSections => origSections; /// <summary> /// Gets the <c>.text</c> section /// </summary> public override PESection TextSection => textSection; /// <summary> /// Gets the <c>.rsrc</c> section or <c>null</c> if there's none /// </summary> public override PESection RsrcSection => rsrcSection; /// <summary> /// Constructor /// </summary> /// <param name="module">The module</param> /// <param name="options">Options or <c>null</c></param> public NativeModuleWriter(ModuleDefMD module, NativeModuleWriterOptions options) { this.module = module; this.options = options; peImage = module.Metadata.PEImage; reusedChunks = new List<ReusedChunkInfo>(); } /// <inheritdoc/> protected override long WriteImpl() { try { return Write(); } finally { if (origSections is not null) { foreach (var section in origSections) section.Dispose(); } } } long Write() { Initialize(); // It's not safe to create new Field RVAs so re-use them all. The user can override // this by setting field.RVA = 0 when creating a new field.InitialValue. metadata.KeepFieldRVA = true; metadata.CreateTables(); return WriteFile(); } void Initialize() { CreateSections(); OnWriterEvent(ModuleWriterEvent.PESectionsCreated); CreateChunks(); OnWriterEvent(ModuleWriterEvent.ChunksCreated); AddChunksToSections(); OnWriterEvent(ModuleWriterEvent.ChunksAddedToSections); } void CreateSections() { CreatePESections(); CreateRawSections(); CreateExtraData(); } void CreateChunks() { CreateMetadataChunks(module); methodBodies.CanReuseOldBodyLocation = Options.OptimizeImageSize; CreateDebugDirectory(); imageCor20Header = new ByteArrayChunk(new byte[0x48]); CreateStrongNameSignature(); } void AddChunksToSections() { textSection.Add(imageCor20Header, DEFAULT_COR20HEADER_ALIGNMENT); textSection.Add(strongNameSignature, DEFAULT_STRONGNAMESIG_ALIGNMENT); textSection.Add(constants, DEFAULT_CONSTANTS_ALIGNMENT); textSection.Add(methodBodies, DEFAULT_METHODBODIES_ALIGNMENT); textSection.Add(netResources, DEFAULT_NETRESOURCES_ALIGNMENT); textSection.Add(metadata, DEFAULT_METADATA_ALIGNMENT); textSection.Add(debugDirectory, DebugDirectory.DEFAULT_DEBUGDIRECTORY_ALIGNMENT); if (rsrcSection is not null) rsrcSection.Add(win32Resources, DEFAULT_WIN32_RESOURCES_ALIGNMENT); } /// <inheritdoc/> protected override Win32Resources GetWin32Resources() { if (Options.KeepWin32Resources) return null; if (Options.NoWin32Resources) return null; return Options.Win32Resources ?? module.Win32Resources; } void CreatePESections() { sections = new List<PESection>(); sections.Add(textSection = new PESection(".text", 0x60000020)); if (GetWin32Resources() is not null) sections.Add(rsrcSection = new PESection(".rsrc", 0x40000040)); } /// <summary> /// Gets the raw section data of the image. The sections are saved in /// <see cref="origSections"/>. /// </summary> void CreateRawSections() { var fileAlignment = peImage.ImageNTHeaders.OptionalHeader.FileAlignment; origSections = new List<OrigSection>(peImage.ImageSectionHeaders.Count); foreach (var peSection in peImage.ImageSectionHeaders) { var newSection = new OrigSection(peSection); origSections.Add(newSection); uint sectionSize = Utils.AlignUp(peSection.SizeOfRawData, fileAlignment); newSection.Chunk = new DataReaderChunk(peImage.CreateReader(peSection.VirtualAddress, sectionSize), peSection.VirtualSize); } } /// <summary> /// Creates the PE header "section" /// </summary> DataReaderChunk CreateHeaderSection(out IChunk extraHeaderData) { uint afterLastSectHeader = GetOffsetAfterLastSectionHeader() + (uint)sections.Count * 0x28; uint firstRawOffset = Math.Min(GetFirstRawDataFileOffset(), peImage.ImageNTHeaders.OptionalHeader.SectionAlignment); uint headerLen = afterLastSectHeader; if (firstRawOffset > headerLen) headerLen = firstRawOffset; headerLen = Utils.AlignUp(headerLen, peImage.ImageNTHeaders.OptionalHeader.FileAlignment); if (headerLen <= peImage.ImageNTHeaders.OptionalHeader.SectionAlignment) { uint origSizeOfHeaders = peImage.ImageNTHeaders.OptionalHeader.SizeOfHeaders; uint extraLen; if (headerLen <= origSizeOfHeaders) extraLen = 0; else { extraLen = headerLen - origSizeOfHeaders; headerLen = origSizeOfHeaders; } if (extraLen > 0) extraHeaderData = new ByteArrayChunk(new byte[(int)extraLen]); else extraHeaderData = null; return new DataReaderChunk(peImage.CreateReader((FileOffset)0, headerLen)); } //TODO: Support this too throw new ModuleWriterException("Could not create header"); } uint GetOffsetAfterLastSectionHeader() { var lastSect = peImage.ImageSectionHeaders[peImage.ImageSectionHeaders.Count - 1]; return (uint)lastSect.EndOffset; } uint GetFirstRawDataFileOffset() { uint len = uint.MaxValue; foreach (var section in peImage.ImageSectionHeaders) len = Math.Min(len, section.PointerToRawData); return len; } /// <summary> /// Saves any data that is appended to the original PE file /// </summary> void CreateExtraData() { if (!Options.KeepExtraPEData) return; var lastOffs = GetLastFileSectionOffset(); extraData = new DataReaderChunk(peImage.CreateReader((FileOffset)lastOffs)); if (extraData.CreateReader().Length == 0) extraData = null; } uint GetLastFileSectionOffset() { uint rva = 0; foreach (var sect in origSections) rva = Math.Max(rva, (uint)sect.PESection.VirtualAddress + sect.PESection.SizeOfRawData); return (uint)peImage.ToFileOffset((RVA)(rva - 1)) + 1; } void ReuseIfPossible(PESection section, IReuseChunk chunk, RVA origRva, uint origSize, uint requiredAlignment) { if (origRva == 0 || origSize == 0) return; if (chunk is null) return; if (!chunk.CanReuse(origRva, origSize)) return; if (((uint)origRva & (requiredAlignment - 1)) != 0) return; var origEnd = origRva + origSize; foreach (var reusedChunk in reusedChunks) { if (origRva < reusedChunk.RVA + reusedChunk.Chunk.GetVirtualSize() && origEnd > reusedChunk.RVA) return; } if (section.Remove(chunk) is null) throw new InvalidOperationException(); reusedChunks.Add(new ReusedChunkInfo(chunk, origRva)); } FileOffset GetNewFileOffset(RVA rva) { foreach (var sect in origSections) { var section = sect.PESection; if (section.VirtualAddress <= rva && rva < section.VirtualAddress + Math.Max(section.VirtualSize, section.SizeOfRawData)) return sect.Chunk.FileOffset + (rva - section.VirtualAddress); } return (FileOffset)rva; } long WriteFile() { bool entryPointIsManagedOrNoEntryPoint = GetEntryPoint(out uint entryPointToken); OnWriterEvent(ModuleWriterEvent.BeginWritePdb); WritePdbFile(); OnWriterEvent(ModuleWriterEvent.EndWritePdb); metadata.OnBeforeSetOffset(); OnWriterEvent(ModuleWriterEvent.BeginCalculateRvasAndFileOffsets); if (Options.OptimizeImageSize) { // Check if we can reuse the old MD location for the new MD. // If we can't reuse it, it could be due to several reasons: // - TypeDefOrRef tokens weren't preserved resulting in a new #Blob heap that's bigger than the old #Blob heap // - New MD was added or existing MD was modified (eg. types were renamed) by the user so it's // now bigger and doesn't fit in the old location // - The original location wasn't aligned properly // - The new MD is bigger because the other MD writer was slightly better at optimizing the MD. // This should be considered a bug. var mdDataDir = module.Metadata.ImageCor20Header.Metadata; metadata.SetOffset(peImage.ToFileOffset(mdDataDir.VirtualAddress), mdDataDir.VirtualAddress); ReuseIfPossible(textSection, metadata, mdDataDir.VirtualAddress, mdDataDir.Size, DEFAULT_METADATA_ALIGNMENT); var resourceDataDir = peImage.ImageNTHeaders.OptionalHeader.DataDirectories[2]; if (win32Resources is not null && resourceDataDir.VirtualAddress != 0 && resourceDataDir.Size != 0) { var win32ResourcesOffset = peImage.ToFileOffset(resourceDataDir.VirtualAddress); if (win32Resources.CheckValidOffset(win32ResourcesOffset)) { win32Resources.SetOffset(win32ResourcesOffset, resourceDataDir.VirtualAddress); ReuseIfPossible(rsrcSection, win32Resources, resourceDataDir.VirtualAddress, resourceDataDir.Size, DEFAULT_WIN32_RESOURCES_ALIGNMENT); } } ReuseIfPossible(textSection, imageCor20Header, module.Metadata.PEImage.ImageNTHeaders.OptionalHeader.DataDirectories[14].VirtualAddress, module.Metadata.PEImage.ImageNTHeaders.OptionalHeader.DataDirectories[14].Size, DEFAULT_COR20HEADER_ALIGNMENT); if ((module.Metadata.ImageCor20Header.Flags & ComImageFlags.StrongNameSigned) != 0) ReuseIfPossible(textSection, strongNameSignature, module.Metadata.ImageCor20Header.StrongNameSignature.VirtualAddress, module.Metadata.ImageCor20Header.StrongNameSignature.Size, DEFAULT_STRONGNAMESIG_ALIGNMENT); ReuseIfPossible(textSection, netResources, module.Metadata.ImageCor20Header.Resources.VirtualAddress, module.Metadata.ImageCor20Header.Resources.Size, DEFAULT_NETRESOURCES_ALIGNMENT); if (methodBodies.ReusedAllMethodBodyLocations) textSection.Remove(methodBodies); var debugDataDir = peImage.ImageNTHeaders.OptionalHeader.DataDirectories[6]; if (debugDataDir.VirtualAddress != 0 && debugDataDir.Size != 0 && TryGetRealDebugDirectorySize(peImage, out uint realDebugDirSize)) ReuseIfPossible(textSection, debugDirectory, debugDataDir.VirtualAddress, realDebugDirSize, DebugDirectory.DEFAULT_DEBUGDIRECTORY_ALIGNMENT); } if (constants.IsEmpty) textSection.Remove(constants); if (netResources.IsEmpty) textSection.Remove(netResources); if (textSection.IsEmpty) sections.Remove(textSection); if (rsrcSection is not null && rsrcSection.IsEmpty) { sections.Remove(rsrcSection); rsrcSection = null; } var headerSection = CreateHeaderSection(out var extraHeaderData); var chunks = new List<IChunk>(); uint headerLen; if (extraHeaderData is not null) { var list = new ChunkList<IChunk>(); list.Add(headerSection, 1); list.Add(extraHeaderData, 1); chunks.Add(list); headerLen = headerSection.GetVirtualSize() + extraHeaderData.GetVirtualSize(); } else { chunks.Add(headerSection); headerLen = headerSection.GetVirtualSize(); } foreach (var origSection in origSections) chunks.Add(origSection.Chunk); foreach (var section in sections) chunks.Add(section); if (extraData is not null) chunks.Add(extraData); CalculateRvasAndFileOffsets(chunks, 0, 0, peImage.ImageNTHeaders.OptionalHeader.FileAlignment, peImage.ImageNTHeaders.OptionalHeader.SectionAlignment); if (reusedChunks.Count > 0 || methodBodies.HasReusedMethods) { methodBodies.InitializeReusedMethodBodies(GetNewFileOffset); foreach (var info in reusedChunks) { var offset = GetNewFileOffset(info.RVA); info.Chunk.SetOffset(offset, info.RVA); } } metadata.UpdateMethodAndFieldRvas(); foreach (var section in origSections) { if (section.Chunk.RVA != section.PESection.VirtualAddress) throw new ModuleWriterException("Invalid section RVA"); } OnWriterEvent(ModuleWriterEvent.EndCalculateRvasAndFileOffsets); OnWriterEvent(ModuleWriterEvent.BeginWriteChunks); var writer = new DataWriter(destStream); WriteChunks(writer, chunks, 0, peImage.ImageNTHeaders.OptionalHeader.FileAlignment); long imageLength = writer.Position - destStreamBaseOffset; if (reusedChunks.Count > 0 || methodBodies.HasReusedMethods) { var pos = writer.Position; foreach (var info in reusedChunks) { Debug.Assert(info.Chunk.RVA == info.RVA); if (info.Chunk.RVA != info.RVA) throw new InvalidOperationException(); writer.Position = destStreamBaseOffset + (uint)info.Chunk.FileOffset; info.Chunk.VerifyWriteTo(writer); } methodBodies.WriteReusedMethodBodies(writer, destStreamBaseOffset); writer.Position = pos; } var sectionSizes = new SectionSizes(peImage.ImageNTHeaders.OptionalHeader.FileAlignment, peImage.ImageNTHeaders.OptionalHeader.SectionAlignment, headerLen, GetSectionSizeInfos); UpdateHeaderFields(writer, entryPointIsManagedOrNoEntryPoint, entryPointToken, ref sectionSizes); OnWriterEvent(ModuleWriterEvent.EndWriteChunks); OnWriterEvent(ModuleWriterEvent.BeginStrongNameSign); if (Options.StrongNameKey is not null) StrongNameSign((long)strongNameSignature.FileOffset); OnWriterEvent(ModuleWriterEvent.EndStrongNameSign); OnWriterEvent(ModuleWriterEvent.BeginWritePEChecksum); if (Options.AddCheckSum) { destStream.Position = destStreamBaseOffset; uint newCheckSum = destStream.CalculatePECheckSum(imageLength, checkSumOffset); writer.Position = checkSumOffset; writer.WriteUInt32(newCheckSum); } OnWriterEvent(ModuleWriterEvent.EndWritePEChecksum); return imageLength; } static bool TryGetRealDebugDirectorySize(IPEImage peImage, out uint realSize) { realSize = 0; if (peImage.ImageDebugDirectories.Count == 0) return false; var dirs = new List<ImageDebugDirectory>(peImage.ImageDebugDirectories); dirs.Sort((a, b) => a.AddressOfRawData.CompareTo(b.AddressOfRawData)); var debugDataDir = peImage.ImageNTHeaders.OptionalHeader.DataDirectories[6]; var prevEnd = (uint)debugDataDir.VirtualAddress + debugDataDir.Size; for (int i = 0; i < dirs.Count; i++) { uint prevEndAligned = (prevEnd + 3) & ~3U; var dir = dirs[i]; if (dir.AddressOfRawData == 0 || dir.SizeOfData == 0) continue; if (!(prevEnd <= (uint)dir.AddressOfRawData && (uint)dir.AddressOfRawData <= prevEndAligned)) return false; prevEnd = (uint)dir.AddressOfRawData + dir.SizeOfData; } realSize = prevEnd - (uint)debugDataDir.VirtualAddress; return true; } /// <summary> /// <c>true</c> if image is 64-bit /// </summary> bool Is64Bit() => peImage.ImageNTHeaders.OptionalHeader is ImageOptionalHeader64; Characteristics GetCharacteristics() { var ch = module.Characteristics; if (Is64Bit()) ch &= ~Characteristics.Bit32Machine; else ch |= Characteristics.Bit32Machine; if (Options.IsExeFile) ch &= ~Characteristics.Dll; else ch |= Characteristics.Dll; return ch; } /// <summary> /// Updates the PE header and COR20 header fields that need updating. All sections are /// also updated, and the new ones are added. /// </summary> void UpdateHeaderFields(DataWriter writer, bool entryPointIsManagedOrNoEntryPoint, uint entryPointToken, ref SectionSizes sectionSizes) { long fileHeaderOffset = destStreamBaseOffset + (long)peImage.ImageNTHeaders.FileHeader.StartOffset; long optionalHeaderOffset = destStreamBaseOffset + (long)peImage.ImageNTHeaders.OptionalHeader.StartOffset; long sectionsOffset = destStreamBaseOffset + (long)peImage.ImageSectionHeaders[0].StartOffset; long dataDirOffset = destStreamBaseOffset + (long)peImage.ImageNTHeaders.OptionalHeader.EndOffset - 16 * 8; long cor20Offset = destStreamBaseOffset + (long)imageCor20Header.FileOffset; // Update PE file header var peOptions = Options.PEHeadersOptions; writer.Position = fileHeaderOffset; writer.WriteUInt16((ushort)(peOptions.Machine ?? module.Machine)); writer.WriteUInt16((ushort)(origSections.Count + sections.Count)); WriteUInt32(writer, peOptions.TimeDateStamp); WriteUInt32(writer, peOptions.PointerToSymbolTable); WriteUInt32(writer, peOptions.NumberOfSymbols); writer.Position += 2; // sizeof(SizeOfOptionalHeader) writer.WriteUInt16((ushort)(peOptions.Characteristics ?? GetCharacteristics())); // Update optional header writer.Position = optionalHeaderOffset; bool is32BitOptionalHeader = peImage.ImageNTHeaders.OptionalHeader is ImageOptionalHeader32; if (is32BitOptionalHeader) { writer.Position += 2; WriteByte(writer, peOptions.MajorLinkerVersion); WriteByte(writer, peOptions.MinorLinkerVersion); writer.WriteUInt32(sectionSizes.SizeOfCode); writer.WriteUInt32(sectionSizes.SizeOfInitdData); writer.WriteUInt32(sectionSizes.SizeOfUninitdData); writer.Position += 4; // EntryPoint writer.WriteUInt32(sectionSizes.BaseOfCode); writer.WriteUInt32(sectionSizes.BaseOfData); WriteUInt32(writer, peOptions.ImageBase); writer.Position += 8; // SectionAlignment, FileAlignment WriteUInt16(writer, peOptions.MajorOperatingSystemVersion); WriteUInt16(writer, peOptions.MinorOperatingSystemVersion); WriteUInt16(writer, peOptions.MajorImageVersion); WriteUInt16(writer, peOptions.MinorImageVersion); WriteUInt16(writer, peOptions.MajorSubsystemVersion); WriteUInt16(writer, peOptions.MinorSubsystemVersion); WriteUInt32(writer, peOptions.Win32VersionValue); writer.WriteUInt32(sectionSizes.SizeOfImage); writer.WriteUInt32(sectionSizes.SizeOfHeaders); checkSumOffset = writer.Position; writer.WriteInt32(0); // CheckSum WriteUInt16(writer, peOptions.Subsystem); WriteUInt16(writer, peOptions.DllCharacteristics); WriteUInt32(writer, peOptions.SizeOfStackReserve); WriteUInt32(writer, peOptions.SizeOfStackCommit); WriteUInt32(writer, peOptions.SizeOfHeapReserve); WriteUInt32(writer, peOptions.SizeOfHeapCommit); WriteUInt32(writer, peOptions.LoaderFlags); WriteUInt32(writer, peOptions.NumberOfRvaAndSizes); } else { writer.Position += 2; WriteByte(writer, peOptions.MajorLinkerVersion); WriteByte(writer, peOptions.MinorLinkerVersion); writer.WriteUInt32(sectionSizes.SizeOfCode); writer.WriteUInt32(sectionSizes.SizeOfInitdData); writer.WriteUInt32(sectionSizes.SizeOfUninitdData); writer.Position += 4; // EntryPoint writer.WriteUInt32(sectionSizes.BaseOfCode); WriteUInt64(writer, peOptions.ImageBase); writer.Position += 8; // SectionAlignment, FileAlignment WriteUInt16(writer, peOptions.MajorOperatingSystemVersion); WriteUInt16(writer, peOptions.MinorOperatingSystemVersion); WriteUInt16(writer, peOptions.MajorImageVersion); WriteUInt16(writer, peOptions.MinorImageVersion); WriteUInt16(writer, peOptions.MajorSubsystemVersion); WriteUInt16(writer, peOptions.MinorSubsystemVersion); WriteUInt32(writer, peOptions.Win32VersionValue); writer.WriteUInt32(sectionSizes.SizeOfImage); writer.WriteUInt32(sectionSizes.SizeOfHeaders); checkSumOffset = writer.Position; writer.WriteInt32(0); // CheckSum WriteUInt16(writer, peOptions.Subsystem ?? GetSubsystem()); WriteUInt16(writer, peOptions.DllCharacteristics ?? module.DllCharacteristics); WriteUInt64(writer, peOptions.SizeOfStackReserve); WriteUInt64(writer, peOptions.SizeOfStackCommit); WriteUInt64(writer, peOptions.SizeOfHeapReserve); WriteUInt64(writer, peOptions.SizeOfHeapCommit); WriteUInt32(writer, peOptions.LoaderFlags); WriteUInt32(writer, peOptions.NumberOfRvaAndSizes); } // Update Win32 resources data directory, if we wrote a new one if (win32Resources is not null) { writer.Position = dataDirOffset + 2 * 8; writer.WriteDataDirectory(win32Resources); } // Clear the security descriptor directory writer.Position = dataDirOffset + 4 * 8; writer.WriteDataDirectory(null); // Write a new debug directory writer.Position = dataDirOffset + 6 * 8; writer.WriteDebugDirectory(debugDirectory); // Write a new Metadata data directory writer.Position = dataDirOffset + 14 * 8; writer.WriteDataDirectory(imageCor20Header); // Update old sections, and add new sections writer.Position = sectionsOffset; foreach (var section in origSections) { writer.Position += 0x14; writer.WriteUInt32((uint)section.Chunk.FileOffset); // PointerToRawData writer.Position += 0x10; } foreach (var section in sections) section.WriteHeaderTo(writer, peImage.ImageNTHeaders.OptionalHeader.FileAlignment, peImage.ImageNTHeaders.OptionalHeader.SectionAlignment, (uint)section.RVA); // Write the .NET header writer.Position = cor20Offset; writer.WriteInt32(0x48); // cb WriteUInt16(writer, Options.Cor20HeaderOptions.MajorRuntimeVersion); WriteUInt16(writer, Options.Cor20HeaderOptions.MinorRuntimeVersion); writer.WriteDataDirectory(metadata); writer.WriteUInt32((uint)GetComImageFlags(entryPointIsManagedOrNoEntryPoint)); writer.WriteUInt32(entryPointToken); writer.WriteDataDirectory(netResources); writer.WriteDataDirectory(strongNameSignature); WriteDataDirectory(writer, module.Metadata.ImageCor20Header.CodeManagerTable); WriteDataDirectory(writer, module.Metadata.ImageCor20Header.VTableFixups); WriteDataDirectory(writer, module.Metadata.ImageCor20Header.ExportAddressTableJumps); WriteDataDirectory(writer, module.Metadata.ImageCor20Header.ManagedNativeHeader); UpdateVTableFixups(writer); } static void WriteDataDirectory(DataWriter writer, ImageDataDirectory dataDir) { writer.WriteUInt32((uint)dataDir.VirtualAddress); writer.WriteUInt32(dataDir.Size); } static void WriteByte(DataWriter writer, byte? value) { if (value is null) writer.Position++; else writer.WriteByte(value.Value); } static void WriteUInt16(DataWriter writer, ushort? value) { if (value is null) writer.Position += 2; else writer.WriteUInt16(value.Value); } static void WriteUInt16(DataWriter writer, Subsystem? value) { if (value is null) writer.Position += 2; else writer.WriteUInt16((ushort)value.Value); } static void WriteUInt16(DataWriter writer, DllCharacteristics? value) { if (value is null) writer.Position += 2; else writer.WriteUInt16((ushort)value.Value); } static void WriteUInt32(DataWriter writer, uint? value) { if (value is null) writer.Position += 4; else writer.WriteUInt32(value.Value); } static void WriteUInt32(DataWriter writer, ulong? value) { if (value is null) writer.Position += 4; else writer.WriteUInt32((uint)value.Value); } static void WriteUInt64(DataWriter writer, ulong? value) { if (value is null) writer.Position += 8; else writer.WriteUInt64(value.Value); } ComImageFlags GetComImageFlags(bool isManagedEntryPoint) { var flags = Options.Cor20HeaderOptions.Flags ?? module.Cor20HeaderFlags; if (Options.Cor20HeaderOptions.EntryPoint is not null) return flags; if (isManagedEntryPoint) return flags & ~ComImageFlags.NativeEntryPoint; return flags | ComImageFlags.NativeEntryPoint; } Subsystem GetSubsystem() { if (module.Kind == ModuleKind.Windows) return Subsystem.WindowsGui; return Subsystem.WindowsCui; } /// <summary> /// Converts <paramref name="rva"/> to a file offset in the destination stream /// </summary> /// <param name="rva">RVA</param> long ToWriterOffset(RVA rva) { if (rva == 0) return 0; foreach (var sect in origSections) { var section = sect.PESection; if (section.VirtualAddress <= rva && rva < section.VirtualAddress + Math.Max(section.VirtualSize, section.SizeOfRawData)) return destStreamBaseOffset + (long)sect.Chunk.FileOffset + (rva - section.VirtualAddress); } return 0; } IEnumerable<SectionSizeInfo> GetSectionSizeInfos() { foreach (var section in origSections) yield return new SectionSizeInfo(section.Chunk.GetVirtualSize(), section.PESection.Characteristics); foreach (var section in sections) yield return new SectionSizeInfo(section.GetVirtualSize(), section.Characteristics); } void UpdateVTableFixups(DataWriter writer) { var vtableFixups = module.VTableFixups; if (vtableFixups is null || vtableFixups.VTables.Count == 0) return; writer.Position = ToWriterOffset(vtableFixups.RVA); if (writer.Position == 0) { Error("Could not convert RVA to file offset"); return; } foreach (var vtable in vtableFixups) { if (vtable.Methods.Count > ushort.MaxValue) throw new ModuleWriterException("Too many methods in vtable"); writer.WriteUInt32((uint)vtable.RVA); writer.WriteUInt16((ushort)vtable.Methods.Count); writer.WriteUInt16((ushort)vtable.Flags); long pos = writer.Position; writer.Position = ToWriterOffset(vtable.RVA); if (writer.Position == 0) { if (vtable.RVA != 0 || vtable.Methods.Count > 0) Error("Could not convert RVA to file offset"); } else { var methods = vtable.Methods; int count = methods.Count; for (int i = 0; i < count; i++) { var method = methods[i]; writer.WriteUInt32(GetMethodToken(method)); if (vtable.Is64Bit) writer.WriteInt32(0); } } writer.Position = pos; } } uint GetMethodToken(IMethod method) { if (method is MethodDef md) return new MDToken(Table.Method, metadata.GetRid(md)).Raw; if (method is MemberRef mr) return new MDToken(Table.MemberRef, metadata.GetRid(mr)).Raw; if (method is MethodSpec ms) return new MDToken(Table.MethodSpec, metadata.GetRid(ms)).Raw; if (method is null) return 0; Error("Invalid VTable method type: {0}", method.GetType()); return 0; } /// <summary> /// Gets the entry point /// </summary> /// <param name="ep">Updated with entry point (either a token or RVA of native method)</param> /// <returns><c>true</c> if it's a managed entry point or there's no entry point, /// <c>false</c> if it's a native entry point</returns> bool GetEntryPoint(out uint ep) { var tok = Options.Cor20HeaderOptions.EntryPoint; if (tok is not null) { ep = tok.Value; return ep == 0 || ((Options.Cor20HeaderOptions.Flags ?? 0) & ComImageFlags.NativeEntryPoint) == 0; } if (module.ManagedEntryPoint is MethodDef epMethod) { ep = new MDToken(Table.Method, metadata.GetRid(epMethod)).Raw; return true; } if (module.ManagedEntryPoint is FileDef file) { ep = new MDToken(Table.File, metadata.GetRid(file)).Raw; return true; } ep = (uint)module.NativeEntryPoint; return ep == 0; } } }
412
0.969138
1
0.969138
game-dev
MEDIA
0.313301
game-dev
0.769419
1
0.769419
vayerx/shadowgrounds
2,108
game/scripting/UnitScripting.h
#ifndef UNITSCRIPTING_H #define UNITSCRIPTING_H #include <DatatypeDef.h> namespace util { class ScriptProcess; } namespace game { class Game; class GameScriptData; class Unit; class UnitScripting { public: /** * Just processes one command... */ static void process(util::ScriptProcess *sp, int command, floatint intFloat, const char *stringData, ScriptLastValueType *lastValue, GameScriptData *gsd, Game *game, bool *pause); static Unit *findClosestHostileUnit(Game *game, VC3 &position, int player, Unit *ignore); static Unit *findClosestFriendlyUnit(Game *game, VC3 &position, int player, Unit *ignore); static Unit *findClosestOwnedUnit(Game *game, VC3 &position, int player, Unit *ignore); static Unit *findUnitByCharacterName(Game *game, const char *charname); static Unit *findClosestUnitOfType(Game *game, const VC3 &position, const char *unittype); static Unit *nextOwnedUnit(Game *game, const VC3 &position, int player, Unit *ignore, bool only_active = true); static Unit *randomOwnedUnit(Game *game, VC3 &position, int player); static Unit *findClosestUnitWithVariableSet(Game *game, const VC3 &position, const char *unitvar, bool varIsNonZero); static Unit *findClosestUnitOfTypeWithVariableSet(Game *game, const VC3 &position, const char *unittype, const char *unitvar, bool varIsNonZero); static bool findGroup(Game *game, Unit *unit); static void moveUnitToDirection(Unit *unit, int direction, float amount); }; } #endif
412
0.726347
1
0.726347
game-dev
MEDIA
0.891968
game-dev
0.547361
1
0.547361
DarioSamo/libgens-sonicglvl
53,492
depends/ogre/include/OGRE/OgreResourceGroupManager.h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef _ResourceGroupManager_H__ #define _ResourceGroupManager_H__ #include "OgrePrerequisites.h" #include "OgreSingleton.h" #include "OgreCommon.h" #include "OgreDataStream.h" #include "OgreResource.h" #include "OgreArchive.h" #include "OgreIteratorWrappers.h" #include <ctime> #include "OgreHeaderPrefix.h" // If X11/Xlib.h gets included before this header (for example it happens when // including wxWidgets and FLTK), Status is defined as an int which we don't // want as we have an enum named Status. #ifdef Status #undef Status #endif namespace Ogre { /** \addtogroup Core * @{ */ /** \addtogroup Resources * @{ */ /** This abstract class defines an interface which is called back during resource group loading to indicate the progress of the load. @remarks Resource group loading is in 2 phases - creating resources from declarations (which includes parsing scripts), and loading resources. Note that you don't necessarily have to have both; it is quite possible to just parse all the scripts for a group (see ResourceGroupManager::initialiseResourceGroup, but not to load the resource group. The sequence of events is (* signifies a repeating item): <ul> <li>resourceGroupScriptingStarted</li> <li>scriptParseStarted (*)</li> <li>scriptParseEnded (*)</li> <li>resourceGroupScriptingEnded</li> <li>resourceGroupLoadStarted</li> <li>resourceLoadStarted (*)</li> <li>resourceLoadEnded (*)</li> <li>worldGeometryStageStarted (*)</li> <li>worldGeometryStageEnded (*)</li> <li>resourceGroupLoadEnded</li> <li>resourceGroupPrepareStarted</li> <li>resourcePrepareStarted (*)</li> <li>resourcePrepareEnded (*)</li> <li>resourceGroupPrepareEnded</li> </ul> @note If OGRE_THREAD_SUPPORT is 1, this class is thread-safe. */ class _OgreExport ResourceGroupListener { public: virtual ~ResourceGroupListener() {} /** This event is fired when a resource group begins parsing scripts. @note Remember that if you are loading resources through ResourceBackgroundQueue, these callbacks will occur in the background thread, so you should not perform any thread-unsafe actions in this callback if that's the case (check the group name / script name). @param groupName The name of the group @param scriptCount The number of scripts which will be parsed */ virtual void resourceGroupScriptingStarted(const String& groupName, size_t scriptCount) = 0; /** This event is fired when a script is about to be parsed. @param scriptName Name of the to be parsed @param skipThisScript A boolean passed by reference which is by default set to false. If the event sets this to true, the script will be skipped and not parsed. Note that in this case the scriptParseEnded event will not be raised for this script. */ virtual void scriptParseStarted(const String& scriptName, bool& skipThisScript) = 0; /** This event is fired when the script has been fully parsed. */ virtual void scriptParseEnded(const String& scriptName, bool skipped) = 0; /** This event is fired when a resource group finished parsing scripts. */ virtual void resourceGroupScriptingEnded(const String& groupName) = 0; /** This event is fired when a resource group begins preparing. @param groupName The name of the group being prepared @param resourceCount The number of resources which will be prepared, including a number of stages required to prepare any linked world geometry */ virtual void resourceGroupPrepareStarted(const String& groupName, size_t resourceCount) { (void)groupName; (void)resourceCount; } /** This event is fired when a declared resource is about to be prepared. @param resource Weak reference to the resource prepared. */ virtual void resourcePrepareStarted(const ResourcePtr& resource) { (void)resource; } /** This event is fired when the resource has been prepared. */ virtual void resourcePrepareEnded(void) {} /** This event is fired when a stage of preparing linked world geometry is about to start. The number of stages required will have been included in the resourceCount passed in resourceGroupLoadStarted. @param description Text description of what was just prepared */ virtual void worldGeometryPrepareStageStarted(const String& description) { (void)description; } /** This event is fired when a stage of preparing linked world geometry has been completed. The number of stages required will have been included in the resourceCount passed in resourceGroupLoadStarted. */ virtual void worldGeometryPrepareStageEnded(void) {} /** This event is fired when a resource group finished preparing. */ virtual void resourceGroupPrepareEnded(const String& groupName) { (void)groupName; } /** This event is fired when a resource group begins loading. @param groupName The name of the group being loaded @param resourceCount The number of resources which will be loaded, including a number of stages required to load any linked world geometry */ virtual void resourceGroupLoadStarted(const String& groupName, size_t resourceCount) = 0; /** This event is fired when a declared resource is about to be loaded. @param resource Weak reference to the resource loaded. */ virtual void resourceLoadStarted(const ResourcePtr& resource) = 0; /** This event is fired when the resource has been loaded. */ virtual void resourceLoadEnded(void) = 0; /** This event is fired when a stage of loading linked world geometry is about to start. The number of stages required will have been included in the resourceCount passed in resourceGroupLoadStarted. @param description Text description of what was just loaded */ virtual void worldGeometryStageStarted(const String& description) = 0; /** This event is fired when a stage of loading linked world geometry has been completed. The number of stages required will have been included in the resourceCount passed in resourceGroupLoadStarted. */ virtual void worldGeometryStageEnded(void) = 0; /** This event is fired when a resource group finished loading. */ virtual void resourceGroupLoadEnded(const String& groupName) = 0; /** This event is fired when a resource was just created. @param resource Weak reference to the resource created. */ virtual void resourceCreated(const ResourcePtr& resource) { (void)resource; } /** This event is fired when a resource is about to be removed. @param resource Weak reference to the resource removed. */ virtual void resourceRemove(const ResourcePtr& resource) { (void)resource; } }; /** @remarks This class allows users to override resource loading behavior. By overriding this class' methods, you can change how resources are loaded and the behavior for resource name collisions. */ class ResourceLoadingListener { public: virtual ~ResourceLoadingListener() {} /** This event is called when a resource beings loading. */ virtual DataStreamPtr resourceLoading(const String &name, const String &group, Resource *resource) = 0; /** This event is called when a resource stream has been opened, but not processed yet. @remarks You may alter the stream if you wish or alter the incoming pointer to point at another stream if you wish. */ virtual void resourceStreamOpened(const String &name, const String &group, Resource *resource, DataStreamPtr& dataStream) = 0; /** This event is called when a resource collides with another existing one in a resource manager */ virtual bool resourceCollision(Resource *resource, ResourceManager *resourceManager) = 0; }; /** This singleton class manages the list of resource groups, and notifying the various resource managers of their obligations to load / unload resources in a group. It also provides facilities to monitor resource loading per group (to do progress bars etc), provided the resources that are required are pre-registered. @par Defining new resource groups, and declaring the resources you intend to use in advance is optional, however it is a very useful feature. In addition, if a ResourceManager supports the definition of resources through scripts, then this is the class which drives the locating of the scripts and telling the ResourceManager to parse them. @par There are several states that a resource can be in (the concept, not the object instance in this case): <ol> <li><b>Undefined</b>. Nobody knows about this resource yet. It might be in the filesystem, but Ogre is oblivious to it at the moment - there is no Resource instance. This might be because it's never been declared (either in a script, or using ResourceGroupManager::declareResource), or it may have previously been a valid Resource instance but has been removed, either individually through ResourceManager::remove or as a group through ResourceGroupManager::clearResourceGroup.</li> <li><b>Declared</b>. Ogre has some forewarning of this resource, either through calling ResourceGroupManager::declareResource, or by declaring the resource in a script file which is on one of the resource locations which has been defined for a group. There is still no instance of Resource, but Ogre will know to create this resource when ResourceGroupManager::initialiseResourceGroup is called (which is automatic if you declare the resource group before Root::initialise).</li> <li><b>Unloaded</b>. There is now a Resource instance for this resource, although it is not loaded. This means that code which looks for this named resource will find it, but the Resource is not using a lot of memory because it is in an unloaded state. A Resource can get into this state by having just been created by ResourceGroupManager::initialiseResourceGroup (either from a script, or from a call to declareResource), by being created directly from code (ResourceManager::create), or it may have previously been loaded and has been unloaded, either individually through Resource::unload, or as a group through ResourceGroupManager::unloadResourceGroup.</li> <li><b>Loaded</b>The Resource instance is fully loaded. This may have happened implicitly because something used it, or it may have been loaded as part of a group.</li> </ol> @see ResourceGroupManager::declareResource @see ResourceGroupManager::initialiseResourceGroup @see ResourceGroupManager::loadResourceGroup @see ResourceGroupManager::unloadResourceGroup @see ResourceGroupManager::clearResourceGroup */ class _OgreExport ResourceGroupManager : public Singleton<ResourceGroupManager>, public ResourceAlloc { public: OGRE_AUTO_MUTEX; // public to allow external locking /// Default resource group name static String DEFAULT_RESOURCE_GROUP_NAME; /// Internal resource group name (should be used by OGRE internal only) static String INTERNAL_RESOURCE_GROUP_NAME; /// Special resource group name which causes resource group to be automatically determined based on searching for the resource in all groups. static String AUTODETECT_RESOURCE_GROUP_NAME; /// The number of reference counts held per resource by the resource system static size_t RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS; /// Nested struct defining a resource declaration struct ResourceDeclaration { String resourceName; String resourceType; ManualResourceLoader* loader; NameValuePairList parameters; }; /// List of resource declarations typedef list<ResourceDeclaration>::type ResourceDeclarationList; typedef map<String, ResourceManager*>::type ResourceManagerMap; typedef MapIterator<ResourceManagerMap> ResourceManagerIterator; /// Resource location entry struct ResourceLocation { /// Pointer to the archive which is the destination Archive* archive; /// Whether this location was added recursively bool recursive; }; /// List of possible file locations typedef list<ResourceLocation*>::type LocationList; protected: /// Map of resource types (strings) to ResourceManagers, used to notify them to load / unload group contents ResourceManagerMap mResourceManagerMap; /// Map of loading order (Real) to ScriptLoader, used to order script parsing typedef multimap<Real, ScriptLoader*>::type ScriptLoaderOrderMap; ScriptLoaderOrderMap mScriptLoaderOrderMap; typedef vector<ResourceGroupListener*>::type ResourceGroupListenerList; ResourceGroupListenerList mResourceGroupListenerList; ResourceLoadingListener *mLoadingListener; /// Resource index entry, resourcename->location typedef map<String, Archive*>::type ResourceLocationIndex; /// List of resources which can be loaded / unloaded typedef list<ResourcePtr>::type LoadUnloadResourceList; /// Resource group entry struct ResourceGroup { enum Status { UNINITIALSED = 0, INITIALISING = 1, INITIALISED = 2, LOADING = 3, LOADED = 4 }; /// General mutex for dealing with group content OGRE_AUTO_MUTEX; /// Status-specific mutex, separate from content-changing mutex OGRE_MUTEX(statusMutex); /// Group name String name; /// Group status Status groupStatus; /// List of possible locations to search LocationList locationList; /// Index of resource names to locations, built for speedy access (case sensitive archives) ResourceLocationIndex resourceIndexCaseSensitive; /// Index of resource names to locations, built for speedy access (case insensitive archives) ResourceLocationIndex resourceIndexCaseInsensitive; /// Pre-declared resources, ready to be created ResourceDeclarationList resourceDeclarations; /// Created resources which are ready to be loaded / unloaded // Group by loading order of the type (defined by ResourceManager) // (e.g. skeletons and materials before meshes) typedef map<Real, LoadUnloadResourceList*>::type LoadResourceOrderMap; LoadResourceOrderMap loadResourceOrderMap; /// Linked world geometry, as passed to setWorldGeometry String worldGeometry; /// Scene manager to use with linked world geometry SceneManager* worldGeometrySceneManager; // in global pool flag - if true the resource will be loaded even a different group was requested in the load method as a parameter. bool inGlobalPool; void addToIndex(const String& filename, Archive* arch); void removeFromIndex(const String& filename, Archive* arch); void removeFromIndex(Archive* arch); }; /// Map from resource group names to groups typedef map<String, ResourceGroup*>::type ResourceGroupMap; ResourceGroupMap mResourceGroupMap; /// Group name for world resources String mWorldGroupName; /** Parses all the available scripts found in the resource locations for the given group, for all ResourceManagers. @remarks Called as part of initialiseResourceGroup */ void parseResourceGroupScripts(ResourceGroup* grp); /** Create all the pre-declared resources. @remarks Called as part of initialiseResourceGroup */ void createDeclaredResources(ResourceGroup* grp); /** Adds a created resource to a group. */ void addCreatedResource(ResourcePtr& res, ResourceGroup& group); /** Get resource group */ ResourceGroup* getResourceGroup(const String& name); /** Drops contents of a group, leave group there, notify ResourceManagers. */ void dropGroupContents(ResourceGroup* grp); /** Delete a group for shutdown - don't notify ResourceManagers. */ void deleteGroup(ResourceGroup* grp); /// Internal find method for auto groups ResourceGroup* findGroupContainingResourceImpl(const String& filename); /// Internal event firing method void fireResourceGroupScriptingStarted(const String& groupName, size_t scriptCount); /// Internal event firing method void fireScriptStarted(const String& scriptName, bool &skipScript); /// Internal event firing method void fireScriptEnded(const String& scriptName, bool skipped); /// Internal event firing method void fireResourceGroupScriptingEnded(const String& groupName); /// Internal event firing method void fireResourceGroupLoadStarted(const String& groupName, size_t resourceCount); /// Internal event firing method void fireResourceLoadStarted(const ResourcePtr& resource); /// Internal event firing method void fireResourceLoadEnded(void); /// Internal event firing method void fireResourceGroupLoadEnded(const String& groupName); /// Internal event firing method void fireResourceGroupPrepareStarted(const String& groupName, size_t resourceCount); /// Internal event firing method void fireResourcePrepareStarted(const ResourcePtr& resource); /// Internal event firing method void fireResourcePrepareEnded(void); /// Internal event firing method void fireResourceGroupPrepareEnded(const String& groupName); /// Internal event firing method void fireResourceCreated(const ResourcePtr& resource); /// Internal event firing method void fireResourceRemove(const ResourcePtr& resource); /** Internal modification time retrieval */ time_t resourceModifiedTime(ResourceGroup* group, const String& filename); /** Find out if the named file exists in a group. Internal use only @param group Pointer to the resource group @param filename Fully qualified name of the file to test for */ bool resourceExists(ResourceGroup* group, const String& filename); /// Stored current group - optimisation for when bulk loading a group ResourceGroup* mCurrentGroup; public: ResourceGroupManager(); virtual ~ResourceGroupManager(); /** Create a resource group. @remarks A resource group allows you to define a set of resources that can be loaded / unloaded as a unit. For example, it might be all the resources used for the level of a game. There is always one predefined resource group called ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, which is typically used to hold all resources which do not need to be unloaded until shutdown. There is another predefined resource group called ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME too, which should be used by OGRE internal only, the resources created in this group aren't supposed to modify, unload or remove by user. You can create additional ones so that you can control the life of your resources in whichever way you wish. There is one other predefined value, ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME; using this causes the group name to be derived at load time by searching for the resource in the resource locations of each group in turn. @par Once you have defined a resource group, resources which will be loaded as part of it are defined in one of 3 ways: <ol> <li>Manually through declareResource(); this is useful for scripted declarations since it is entirely generalised, and does not create Resource instances right away</li> <li>Through the use of scripts; some ResourceManager subtypes have script formats (e.g. .material, .overlay) which can be used to declare resources</li> <li>By calling ResourceManager::create to create a resource manually. This resource will go on the list for it's group and will be loaded and unloaded with that group</li> </ol> You must remember to call initialiseResourceGroup if you intend to use the first 2 types. @param name The name to give the resource group. @param inGlobalPool if true the resource will be loaded even a different group was requested in the load method as a parameter. */ void createResourceGroup(const String& name, const bool inGlobalPool = true); /** Initialises a resource group. @remarks After creating a resource group, adding some resource locations, and perhaps pre-declaring some resources using declareResource(), but before you need to use the resources in the group, you should call this method to initialise the group. By calling this, you are triggering the following processes: <ol> <li>Scripts for all resource types which support scripting are parsed from the resource locations, and resources within them are created (but not loaded yet).</li> <li>Creates all the resources which have just pre-declared using declareResource (again, these are not loaded yet)</li> </ol> So what this essentially does is create a bunch of unloaded Resource entries in the respective ResourceManagers based on scripts, and resources you've pre-declared. That means that code looking for these resources will find them, but they won't be taking up much memory yet, until they are either used, or they are loaded in bulk using loadResourceGroup. Loading the resource group in bulk is entirely optional, but has the advantage of coming with progress reporting as resources are loaded. @par Failure to call this method means that loadResourceGroup will do nothing, and any resources you define in scripts will not be found. Similarly, once you have called this method you won't be able to pick up any new scripts or pre-declared resources, unless you call clearResourceGroup, set up declared resources, and call this method again. @note When you call Root::initialise, all resource groups that have already been created are automatically initialised too. Therefore you do not need to call this method for groups you define and set up before you call Root::initialise. However, since one of the most useful features of resource groups is to set them up after the main system initialisation has occurred (e.g. a group per game level), you must remember to call this method for the groups you create after this. @param name The name of the resource group to initialise */ void initialiseResourceGroup(const String& name); /** Initialise all resource groups which are yet to be initialised. @see ResourceGroupManager::intialiseResourceGroup */ void initialiseAllResourceGroups(void); /** Prepares a resource group. @remarks Prepares any created resources which are part of the named group. Note that resources must have already been created by calling ResourceManager::create, or declared using declareResource() or in a script (such as .material and .overlay). The latter requires that initialiseResourceGroup has been called. When this method is called, this class will callback any ResourceGroupListeners which have been registered to update them on progress. @param name The name of the resource group to prepare. @param prepareMainResources If true, prepares normal resources associated with the group (you might want to set this to false if you wanted to just prepare world geometry in bulk) @param prepareWorldGeom If true, prepares any linked world geometry @see ResourceGroupManager::linkWorldGeometryToResourceGroup */ void prepareResourceGroup(const String& name, bool prepareMainResources = true, bool prepareWorldGeom = true); /** Loads a resource group. @remarks Loads any created resources which are part of the named group. Note that resources must have already been created by calling ResourceManager::create, or declared using declareResource() or in a script (such as .material and .overlay). The latter requires that initialiseResourceGroup has been called. When this method is called, this class will callback any ResourceGroupListeners which have been registered to update them on progress. @param name The name of the resource group to load. @param loadMainResources If true, loads normal resources associated with the group (you might want to set this to false if you wanted to just load world geometry in bulk) @param loadWorldGeom If true, loads any linked world geometry @see ResourceGroupManager::linkWorldGeometryToResourceGroup */ void loadResourceGroup(const String& name, bool loadMainResources = true, bool loadWorldGeom = true); /** Unloads a resource group. @remarks This method unloads all the resources that have been declared as being part of the named resource group. Note that these resources will still exist in their respective ResourceManager classes, but will be in an unloaded state. If you want to remove them entirely, you should use clearResourceGroup or destroyResourceGroup. @param name The name to of the resource group to unload. @param reloadableOnly If set to true, only unload the resource that is reloadable. Because some resources isn't reloadable, they will be unloaded but can't load them later. Thus, you might not want to them unloaded. Or, you might unload all of them, and then populate them manually later. @see Resource::isReloadable for resource is reloadable. */ void unloadResourceGroup(const String& name, bool reloadableOnly = true); /** Unload all resources which are not referenced by any other object. @remarks This method behaves like unloadResourceGroup, except that it only unloads resources in the group which are not in use, ie not referenced by other objects. This allows you to free up some memory selectively whilst still keeping the group around (and the resources present, just not using much memory). @param name The name of the group to check for unreferenced resources @param reloadableOnly If true (the default), only unloads resources which can be subsequently automatically reloaded */ void unloadUnreferencedResourcesInGroup(const String& name, bool reloadableOnly = true); /** Clears a resource group. @remarks This method unloads all resources in the group, but in addition it removes all those resources from their ResourceManagers, and then clears all the members from the list. That means after calling this method, there are no resources declared as part of the named group any more. Resource locations still persist though. @param name The name to of the resource group to clear. */ void clearResourceGroup(const String& name); /** Destroys a resource group, clearing it first, destroying the resources which are part of it, and then removing it from the list of resource groups. @param name The name of the resource group to destroy. */ void destroyResourceGroup(const String& name); /** Checks the status of a resource group. @remarks Looks at the state of a resource group. If initialiseResourceGroup has been called for the resource group return true, otherwise return false. @param name The name to of the resource group to access. */ bool isResourceGroupInitialised(const String& name); /** Checks the status of a resource group. @remarks Looks at the state of a resource group. If loadResourceGroup has been called for the resource group return true, otherwise return false. @param name The name to of the resource group to access. */ bool isResourceGroupLoaded(const String& name); /*** Verify if a resource group exists @param name The name of the resource group to look for */ bool resourceGroupExists(const String& name); /** Method to add a resource location to for a given resource group. @remarks Resource locations are places which are searched to load resource files. When you choose to load a file, or to search for valid files to load, the resource locations are used. @param name The name of the resource location; probably a directory, zip file, URL etc. @param locType The codename for the resource type, which must correspond to the Archive factory which is providing the implementation. @param resGroup The name of the resource group for which this location is to apply. ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME is the default group which always exists, and can be used for resources which are unlikely to be unloaded until application shutdown. Otherwise it must be the name of a group; if it has not already been created with createResourceGroup then it is created automatically. @param recursive Whether subdirectories will be searched for files when using a pattern match (such as *.material), and whether subdirectories will be indexed. This can slow down initial loading of the archive and searches. When opening a resource you still need to use the fully qualified name, this allows duplicate names in alternate paths. */ void addResourceLocation(const String& name, const String& locType, const String& resGroup = DEFAULT_RESOURCE_GROUP_NAME, bool recursive = false, bool readOnly = true); /** Removes a resource location from the search path. */ void removeResourceLocation(const String& name, const String& resGroup = DEFAULT_RESOURCE_GROUP_NAME); /** Verify if a resource location exists for the given group. */ bool resourceLocationExists(const String& name, const String& resGroup = DEFAULT_RESOURCE_GROUP_NAME); /** Declares a resource to be a part of a resource group, allowing you to load and unload it as part of the group. @remarks By declaring resources before you attempt to use them, you can more easily control the loading and unloading of those resources by their group. Declaring them also allows them to be enumerated, which means events can be raised to indicate the loading progress (@see ResourceGroupListener). Note that another way of declaring resources is to use a script specific to the resource type, if available (e.g. .material). @par Declared resources are not created as Resource instances (and thus are not available through their ResourceManager) until initialiseResourceGroup is called, at which point all declared resources will become created (but unloaded) Resource instances, along with any resources declared in scripts in resource locations associated with the group. @param name The resource name. @param resourceType The type of the resource. Ogre comes preconfigured with a number of resource types: <ul> <li>Font</li> <li>GpuProgram</li> <li>HighLevelGpuProgram</li> <li>Material</li> <li>Mesh</li> <li>Skeleton</li> <li>Texture</li> </ul> .. but more can be added by plugin ResourceManager classes. @param groupName The name of the group to which it will belong. @param loadParameters A list of name / value pairs which supply custom parameters to the resource which will be required before it can be loaded. These are specific to the resource type. */ void declareResource(const String& name, const String& resourceType, const String& groupName = DEFAULT_RESOURCE_GROUP_NAME, const NameValuePairList& loadParameters = NameValuePairList()); /** Declares a resource to be a part of a resource group, allowing you to load and unload it as part of the group. @remarks By declaring resources before you attempt to use them, you can more easily control the loading and unloading of those resources by their group. Declaring them also allows them to be enumerated, which means events can be raised to indicate the loading progress (@see ResourceGroupListener). Note that another way of declaring resources is to use a script specific to the resource type, if available (e.g. .material). @par Declared resources are not created as Resource instances (and thus are not available through their ResourceManager) until initialiseResourceGroup is called, at which point all declared resources will become created (but unloaded) Resource instances, along with any resources declared in scripts in resource locations associated with the group. @param name The resource name. @param resourceType The type of the resource. Ogre comes preconfigured with a number of resource types: <ul> <li>Font</li> <li>GpuProgram</li> <li>HighLevelGpuProgram</li> <li>Material</li> <li>Mesh</li> <li>Skeleton</li> <li>Texture</li> </ul> .. but more can be added by plugin ResourceManager classes. @param groupName The name of the group to which it will belong. @param loader Pointer to a ManualResourceLoader implementation which will be called when the Resource wishes to load. If supplied, the resource is manually loaded, otherwise it'll loading from file automatic. @note We don't support declare manually loaded resource without loader here, since it's meaningless. @param loadParameters A list of name / value pairs which supply custom parameters to the resource which will be required before it can be loaded. These are specific to the resource type. */ void declareResource(const String& name, const String& resourceType, const String& groupName, ManualResourceLoader* loader, const NameValuePairList& loadParameters = NameValuePairList()); /** Undeclare a resource. @remarks Note that this will not cause it to be unloaded if it is already loaded, nor will it destroy a resource which has already been created if initialiseResourceGroup has been called already. Only unloadResourceGroup / clearResourceGroup / destroyResourceGroup will do that. @param name The name of the resource. @param groupName The name of the group this resource was declared in. */ void undeclareResource(const String& name, const String& groupName); /** Open a single resource by name and return a DataStream pointing at the source of the data. @param resourceName The name of the resource to locate. Even if resource locations are added recursively, you must provide a fully qualified name to this method. You can find out the matching fully qualified names by using the find() method if you need to. @param groupName The name of the resource group; this determines which locations are searched. @param searchGroupsIfNotFound If true, if the resource is not found in the group specified, other groups will be searched. If you're loading a real Resource using this option, you <strong>must</strong> also provide the resourceBeingLoaded parameter to enable the group membership to be changed @param resourceBeingLoaded Optional pointer to the resource being loaded, which you should supply if you want @return Shared pointer to data stream containing the data, will be destroyed automatically when no longer referenced */ DataStreamPtr openResource(const String& resourceName, const String& groupName = DEFAULT_RESOURCE_GROUP_NAME, bool searchGroupsIfNotFound = true, Resource* resourceBeingLoaded = 0); /** Open all resources matching a given pattern (which can contain the character '*' as a wildcard), and return a collection of DataStream objects on them. @param pattern The pattern to look for. If resource locations have been added recursively, subdirectories will be searched too so this does not need to be fully qualified. @param groupName The resource group; this determines which locations are searched. @return Shared pointer to a data stream list , will be destroyed automatically when no longer referenced */ DataStreamListPtr openResources(const String& pattern, const String& groupName = DEFAULT_RESOURCE_GROUP_NAME); /** List all file or directory names in a resource group. @note This method only returns filenames, you can also retrieve other information using listFileInfo. @param groupName The name of the group @param dirs If true, directory names will be returned instead of file names @return A list of filenames matching the criteria, all are fully qualified */ StringVectorPtr listResourceNames(const String& groupName, bool dirs = false); /** List all files in a resource group with accompanying information. @param groupName The name of the group @param dirs If true, directory names will be returned instead of file names @return A list of structures detailing quite a lot of information about all the files in the archive. */ FileInfoListPtr listResourceFileInfo(const String& groupName, bool dirs = false); /** Find all file or directory names matching a given pattern in a resource group. @note This method only returns filenames, you can also retrieve other information using findFileInfo. @param groupName The name of the group @param pattern The pattern to search for; wildcards (*) are allowed @param dirs Set to true if you want the directories to be listed instead of files @return A list of filenames matching the criteria, all are fully qualified */ StringVectorPtr findResourceNames(const String& groupName, const String& pattern, bool dirs = false); /** Find out if the named file exists in a group. @param group The name of the resource group @param filename Fully qualified name of the file to test for */ bool resourceExists(const String& group, const String& filename); /** Find out if the named file exists in any group. @param filename Fully qualified name of the file to test for */ bool resourceExistsInAnyGroup(const String& filename); /** Find the group in which a resource exists. @param filename Fully qualified name of the file the resource should be found as @return Name of the resource group the resource was found in. An exception is thrown if the group could not be determined. */ const String& findGroupContainingResource(const String& filename); /** Find all files or directories matching a given pattern in a group and get some detailed information about them. @param group The name of the resource group @param pattern The pattern to search for; wildcards (*) are allowed @param dirs Set to true if you want the directories to be listed instead of files @return A list of file information structures for all files matching the criteria. */ FileInfoListPtr findResourceFileInfo(const String& group, const String& pattern, bool dirs = false); /** Retrieve the modification time of a given file */ time_t resourceModifiedTime(const String& group, const String& filename); /** List all resource locations in a resource group. @param groupName The name of the group @return A list of resource locations matching the criteria */ StringVectorPtr listResourceLocations(const String& groupName); /** Find all resource location names matching a given pattern in a resource group. @param groupName The name of the group @param pattern The pattern to search for; wildcards (*) are allowed @return A list of resource locations matching the criteria */ StringVectorPtr findResourceLocation(const String& groupName, const String& pattern); /** Create a new resource file in a given group. @remarks This method creates a new file in a resource group and passes you back a writeable stream. @param filename The name of the file to create @param groupName The name of the group in which to create the file @param overwrite If true, an existing file will be overwritten, if false an error will occur if the file already exists @param locationPattern If the resource group contains multiple locations, then usually the file will be created in the first writable location. If you want to be more specific, you can include a location pattern here and only locations which match that pattern (as determined by StringUtil::match) will be considered candidates for creation. */ DataStreamPtr createResource(const String& filename, const String& groupName = DEFAULT_RESOURCE_GROUP_NAME, bool overwrite = false, const String& locationPattern = StringUtil::BLANK); /** Delete a single resource file. @param filename The name of the file to delete. @param groupName The name of the group in which to search @param locationPattern If the resource group contains multiple locations, then usually first matching file found in any location will be deleted. If you want to be more specific, you can include a location pattern here and only locations which match that pattern (as determined by StringUtil::match) will be considered candidates for deletion. */ void deleteResource(const String& filename, const String& groupName = DEFAULT_RESOURCE_GROUP_NAME, const String& locationPattern = StringUtil::BLANK); /** Delete all matching resource files. @param filePattern The pattern (see StringUtil::match) of the files to delete. @param groupName The name of the group in which to search @param locationPattern If the resource group contains multiple locations, then usually all matching files in any location will be deleted. If you want to be more specific, you can include a location pattern here and only locations which match that pattern (as determined by StringUtil::match) will be considered candidates for deletion. */ void deleteMatchingResources(const String& filePattern, const String& groupName = DEFAULT_RESOURCE_GROUP_NAME, const String& locationPattern = StringUtil::BLANK); /** Adds a ResourceGroupListener which will be called back during resource loading events. */ void addResourceGroupListener(ResourceGroupListener* l); /** Removes a ResourceGroupListener */ void removeResourceGroupListener(ResourceGroupListener* l); /** Sets the resource group that 'world' resources will use. @remarks This is the group which should be used by SceneManagers implementing world geometry when looking for their resources. Defaults to the DEFAULT_RESOURCE_GROUP_NAME but this can be altered. */ void setWorldResourceGroupName(const String& groupName) {mWorldGroupName = groupName;} /// Gets the resource group that 'world' resources will use. const String& getWorldResourceGroupName(void) const { return mWorldGroupName; } /** Associates some world geometry with a resource group, causing it to be loaded / unloaded with the resource group. @remarks You would use this method to essentially defer a call to SceneManager::setWorldGeometry to the time when the resource group is loaded. The advantage of this is that compatible scene managers will include the estimate of the number of loading stages for that world geometry when the resource group begins loading, allowing you to include that in a loading progress report. @param group The name of the resource group @param worldGeometry The parameter which should be passed to setWorldGeometry @param sceneManager The SceneManager which should be called */ void linkWorldGeometryToResourceGroup(const String& group, const String& worldGeometry, SceneManager* sceneManager); /** Clear any link to world geometry from a resource group. @remarks Basically undoes a previous call to linkWorldGeometryToResourceGroup. */ void unlinkWorldGeometryFromResourceGroup(const String& group); /** Checks the status of a resource group. @remarks Looks at the state of a resource group. If loadResourceGroup has been called for the resource group return true, otherwise return false. @param name The name to of the resource group to access. */ bool isResourceGroupInGlobalPool(const String& name); /** Shutdown all ResourceManagers, performed as part of clean-up. */ void shutdownAll(void); /** Internal method for registering a ResourceManager (which should be a singleton). Creators of plugins can register new ResourceManagers this way if they wish. @remarks ResourceManagers that wish to parse scripts must also call _registerScriptLoader. @param resourceType String identifying the resource type, must be unique. @param rm Pointer to the ResourceManager instance. */ void _registerResourceManager(const String& resourceType, ResourceManager* rm); /** Internal method for unregistering a ResourceManager. @remarks ResourceManagers that wish to parse scripts must also call _unregisterScriptLoader. @param resourceType String identifying the resource type. */ void _unregisterResourceManager(const String& resourceType); /** Get an iterator over the registered resource managers. */ ResourceManagerIterator getResourceManagerIterator() { return ResourceManagerIterator( mResourceManagerMap.begin(), mResourceManagerMap.end()); } /** Internal method for registering a ScriptLoader. @remarks ScriptLoaders parse scripts when resource groups are initialised. @param su Pointer to the ScriptLoader instance. */ void _registerScriptLoader(ScriptLoader* su); /** Internal method for unregistering a ScriptLoader. @param su Pointer to the ScriptLoader instance. */ void _unregisterScriptLoader(ScriptLoader* su); /** Method used to directly query for registered script loaders. @param pattern The specific script pattern (e.g. *.material) the script loader handles */ ScriptLoader *_findScriptLoader(const String &pattern); /** Internal method for getting a registered ResourceManager. @param resourceType String identifying the resource type. */ ResourceManager* _getResourceManager(const String& resourceType); /** Internal method called by ResourceManager when a resource is created. @param res Weak reference to resource */ void _notifyResourceCreated(ResourcePtr& res); /** Internal method called by ResourceManager when a resource is removed. @param res Weak reference to resource */ void _notifyResourceRemoved(ResourcePtr& res); /** Internal method to notify the group manager that a resource has changed group (only applicable for autodetect group) */ void _notifyResourceGroupChanged(const String& oldGroup, Resource* res); /** Internal method called by ResourceManager when all resources for that manager are removed. @param manager Pointer to the manager for which all resources are being removed */ void _notifyAllResourcesRemoved(ResourceManager* manager); /** Notify this manager that one stage of world geometry loading has been started. @remarks Custom SceneManagers which load custom world geometry should call this method the number of times equal to the value they return from SceneManager::estimateWorldGeometry while loading their geometry. */ void _notifyWorldGeometryStageStarted(const String& description); /** Notify this manager that one stage of world geometry loading has been completed. @remarks Custom SceneManagers which load custom world geometry should call this method the number of times equal to the value they return from SceneManager::estimateWorldGeometry while loading their geometry. */ void _notifyWorldGeometryStageEnded(void); /** Get a list of the currently defined resource groups. @note This method intentionally returns a copy rather than a reference in order to avoid any contention issues in multithreaded applications. @return A copy of list of currently defined groups. */ StringVector getResourceGroups(void); /** Get the list of resource declarations for the specified group name. @note This method intentionally returns a copy rather than a reference in order to avoid any contention issues in multithreaded applications. @param groupName The name of the group @return A copy of list of currently defined resources. */ ResourceDeclarationList getResourceDeclarationList(const String& groupName); /** Get the list of resource locations for the specified group name. @param groupName The name of the group @return The list of resource locations associated with the given group. */ const LocationList& getResourceLocationList(const String& groupName); /// Sets a new loading listener void setLoadingListener(ResourceLoadingListener *listener); /// Returns the current loading listener ResourceLoadingListener *getLoadingListener(); /** Override standard Singleton retrieval. @remarks Why do we do this? Well, it's because the Singleton implementation is in a .h file, which means it gets compiled into anybody who includes it. This is needed for the Singleton template to work, but we actually only want it compiled into the implementation of the class based on the Singleton, not all of them. If we don't change this, we get link errors when trying to use the Singleton-based class from an outside dll. @par This method just delegates to the template version anyway, but the implementation stays in this single compilation unit, preventing link errors. */ static ResourceGroupManager& getSingleton(void); /** Override standard Singleton retrieval. @remarks Why do we do this? Well, it's because the Singleton implementation is in a .h file, which means it gets compiled into anybody who includes it. This is needed for the Singleton template to work, but we actually only want it compiled into the implementation of the class based on the Singleton, not all of them. If we don't change this, we get link errors when trying to use the Singleton-based class from an outside dll. @par This method just delegates to the template version anyway, but the implementation stays in this single compilation unit, preventing link errors. */ static ResourceGroupManager* getSingletonPtr(void); }; /** @} */ /** @} */ } #include "OgreHeaderSuffix.h" #endif
412
0.798298
1
0.798298
game-dev
MEDIA
0.487472
game-dev
0.772977
1
0.772977
AthenaModel/athena
3,698
lib/athena/tactics/tactic_violence.tcl
#----------------------------------------------------------------------- # TITLE: # tactic_violence.tcl # # AUTHOR: # Will Duquette # # DESCRIPTION: # athena(n): Mark II Tactic, VIOLENCE event # # This module implements the VIOLENCE tactic. # #----------------------------------------------------------------------- #------------------------------------------------------------------- # Tactic: VIOLENCE ::athena::tactic define VIOLENCE "Violence Event" {system actor} { #------------------------------------------------------------------- # Instance Variables # Editable Parameters variable n ;# Neighborhood in which to create violence variable coverage ;# Coverage fraction #------------------------------------------------------------------- # Constructor constructor {pot_ args} { next $pot_ # Initialize state variables set n "" set coverage 0.5 # Initial state is invalid (no n) my set state invalid my configure {*}$args } #------------------------------------------------------------------- # Operations # No ObligateResources method is required; the tactic uses no resources. method SanityCheck {errdict} { if {$n eq ""} { dict set errdict n "No neighborhood selected." } elseif {$n ni [[my adb] nbhood names]} { dict set errdict n "No such neighborhood: \"$n\"." } return [next $errdict] } method narrative {} { set narr "" set s(n) [::athena::link make nbhood $n] set s(coverage) [format "%.2f" $coverage] set narr "VIOLENCE abstract event in $s(n) " append narr "(cov=$s(coverage))." return $narr } method execute {} { set owner [my agent] set s(n) [::athena::link make nbhood $n] set s(coverage) [format "%.2f" $coverage] # NEXT, log execution set objects [list $owner $n] set msg "VIOLENCE([my id]): [my narrative]" [my adb] sigevent log 2 tactic $msg {*}$objects # NEXT, create the violence. [my adb] abevent add VIOLENCE $n $coverage } } # TACTIC:VIOLENCE # # Creates/Updates VIOLENCE tactic. ::athena::orders define TACTIC:VIOLENCE { meta title "Tactic: Violence Event" meta sendstates PREP meta parmlist {tactic_id name n coverage} meta form { rcc "Tactic ID" -for tactic_id text tactic_id -context yes \ -loadcmd {$order_ beanload} rcc "Name:" -for name text name -width 20 rcc "Neighborhood:" -for n nbhood n rcc "Coverage:" -for coverage frac coverage } method _validate {} { # FIRST, prepare the parameters my prepare tactic_id -required \ -with [list $adb strategy valclass ::athena::tactic::VIOLENCE] my returnOnError set tactic [$adb bean get $parms(tactic_id)] # Validation of initially invalid items or contingent items # takes place on sanity check. my prepare name -toupper -with [list $tactic valName] my prepare n -toupper my prepare coverage -num -type rfraction my returnOnError my checkon coverage { if {$parms(coverage) == 0.0} { my reject coverage "Coverage must be greater than 0." } } } method _execute {{flunky ""}} { set tactic [$adb bean get $parms(tactic_id)] my setundo [$tactic update_ { name n coverage } [array get parms]] } }
412
0.897866
1
0.897866
game-dev
MEDIA
0.626115
game-dev
0.846151
1
0.846151
Irrelon/ige
5,886
other/projects/starFlight/app/component/ui/AbilityButton.ts
import type { IgeAudioController } from "@/engine/audio"; import { isServer } from "@/engine/clientServer"; import { IgeUiEntity } from "@/engine/core/IgeUiEntity"; import { ige } from "@/engine/exports"; import { IgeUiButton } from "@/engine/ui/IgeUiButton"; import { IgeUiLabel } from "@/engine/ui/IgeUiLabel"; import type { EntityAbilityModuleDefinition } from "../../../types/EntityAbilityModuleDefinition"; import type { IgeCanvasRenderingContext2d } from "@/types/IgeCanvasRenderingContext2d"; export interface AbilityButtonOptions { abilityId: string; label: string; module: EntityAbilityModuleDefinition; } export class AbilityButton extends IgeUiEntity { classId = "AbilityButton"; _abilityId: string; _button: IgeUiButton; _module: EntityAbilityModuleDefinition; _label: IgeUiLabel; _timerCircle: IgeUiEntity; constructor (options: AbilityButtonOptions) { if (isServer) { throw new Error("This module should never be instantiated server-side!"); } super(); if (ige.app.abilityCounter === undefined) { ige.app.abilityCounter = 0; } this._abilityId = options.abilityId; this._module = options.module; this._module.active = false; this._module.cooldown = false; // Define an ability button for this module this._button = new IgeUiButton() .id("abilityButton_" + options.abilityId) .width(50) .height(50); // this._button._windowGradient = (ige.engine._ctx as IgeCanvasRenderingContext2d).createLinearGradient(0, 0, this._button.width(), this._button.height()); // this._button._windowGradient.addColorStop(0.0, "#04b7f9"); // this._button._windowGradient.addColorStop(0.5, "#005066"); // this._button._windowGradient.addColorStop(1.0, "#04b7f9"); this._button .layer(0) .texture(ige.textures.get("infoWindow")) .cache(true) .left(0) .top(60 * ige.app.abilityCounter) .mount(this); this._label = new IgeUiLabel() .layer(1) .font("8px Verdana") .width(this._button.width()) .height(this._button.height()) .center(0) .middle(0) .textAlignX(1) .textAlignY(1) .textLineSpacing(12) .color("#7bdaf1") .value(options.label) .cache(true) .mount(this._button); this._timerCircle = new IgeUiEntity() .texture(ige.textures.get("timerCircle")) .width(this._button.width()) .height(this._button.height()) .center(0) .middle(0) .opacity(0.5) .mount(this._button); this._button.pointerUp(() => { this.requestActivation(); }); ige.input.on("keyUp", (ev, code) => { //console.log("Key up, code", code, `Digit${options.abilityId}`); if (code === `Digit${options.abilityId}`) { this.requestActivation(); } }); ige.app.abilityCounter++; } active (val?: boolean) { if (val !== undefined) { if (val && !this._module.active) { // Make module active this._module._activeStartTime = ige.engine._currentTime; } else if (!val && this._module.active) { // Enable cooldown timer this.cooldown(true, ige.engine._currentTime); } this._module.active = val; return this; } return this._module.active; } /** * Gets / sets the cooldown flag for this ability. When called * without a value to set (in getter mode) the method will check * remaining cooldown period to see if cooldown has been deactivated * or not before giving its answer. * @param {Boolean=} val The boolean value to set. * @param startTime * @returns {*} */ cooldown (val?: boolean, startTime?: number) { if (val !== undefined) { if (val && !this._module.cooldown) { if (!this._module.cooldownDuration) { // Do nothing, there is no cooldown duration so never // enable cooldown period return this; } this._module._cooldownStartTime = startTime; } this._module.cooldown = val; return this; } return this._module.cooldown; } /** * Sends a request to the server asking for this ability to * be activated, via the useAbility() method on the player's * entity instance. */ requestActivation () { if (this._disabled || this._module.active || this._module.cooldown) { return (ige.audio as IgeAudioController).play("actionDenied"); } ige.app.playerEntity.useAbility(this._abilityId); } update (ctx: IgeCanvasRenderingContext2d, tickDelta: number) { let activeTime, beenInCooldownFor, playerTargetData; super.update(ctx, tickDelta); if (this._module.active) { this._timerCircle._timerColor = "#ffffff"; // Check if we have finished being active activeTime = ige.engine._currentTime - (this._module._activeStartTime || 0); this._timerCircle._timerValue = (1 / this._module.activeDuration) * activeTime; if (activeTime >= this._module.activeDuration) { this.active(false); beenInCooldownFor = activeTime - this._module.activeDuration; this.cooldown(true, ige.engine._currentTime - beenInCooldownFor); } } else if (this._module.cooldown) { // Check if we have finished cooldown activeTime = ige.engine._currentTime - (this._module._cooldownStartTime || 0); this._timerCircle._timerValue = (1 / this._module.cooldownDuration) * activeTime; this._timerCircle._timerColor = "#ff0000"; if (activeTime >= this._module.cooldownDuration) { this.cooldown(false); this._timerCircle._timerValue = 0; } } else { // Ability is not active or on cooldown, check distance from // target to determine if it is in range of this ability playerTargetData = ige.app.playerEntity.target; if ( this._module.range && this._module.requiresTarget && playerTargetData && playerTargetData._targetEntity ) { if (playerTargetData._distance > this._module.range) { // Disable this ability button this.disabled(true); this.opacity(0.5); } else { // Enable this ability button this.disabled(false); this.opacity(1); } } } } }
412
0.682541
1
0.682541
game-dev
MEDIA
0.721163
game-dev,web-frontend
0.873366
1
0.873366
project-topaz/topaz
1,587
scripts/zones/Western_Adoulin/npcs/Nikkhail.lua
----------------------------------- -- Area: Western Adoulin -- NPC: Nikkhail -- Type: Standard NPC and Quest NPC -- Involved With Quest: 'A Thirst for the Ages' -- !pos -101 3 9 256 ----------------------------------- require("scripts/globals/missions") require("scripts/globals/quests") require("scripts/globals/keyitems") local ID = require("scripts/zones/Western_Adoulin/IDs") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) local ATFTA = player:getQuestStatus(ADOULIN, tpz.quest.id.adoulin.A_THIRST_FOR_THE_AGES) local ATFTA_Need_KI = ((player:getCharVar("ATFTA_Status") < 2) and (not player:hasKeyItem(tpz.ki.COPY_OF_THE_ALLIANCE_AGREEMENT))) local SOA_Mission = player:getCurrentMission(SOA) if (SOA_Mission >= tpz.mission.id.soa.LIFE_ON_THE_FRONTIER) then if ((ATFTA == QUEST_ACCEPTED) and ATFTA_Need_KI) then -- Progresses Quest: 'A Thirst for the Ages' player:startEvent(5053) else -- Standard dialogue, after joining colonization effort player:startEvent(584) end else -- Dialogue prior to joining colonization effort player:startEvent(510) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if (csid == 5053) then -- Progresses Quest: 'A Thirst for the Ages' player:addKeyItem(tpz.ki.COPY_OF_THE_ALLIANCE_AGREEMENT) player:messageSpecial(ID.text.KEYITEM_OBTAINED, tpz.ki.COPY_OF_THE_ALLIANCE_AGREEMENT) end end
412
0.880288
1
0.880288
game-dev
MEDIA
0.995306
game-dev
0.878892
1
0.878892
dot42/dot42
2,868
Sources/CompilerLib/RL/Transformations/EliminateDeadCodeTransformation.cs
using System; using System.Collections.Generic; using System.Linq; using Dot42.CompilerLib.RL.Extensions; using Dot42.DexLib; namespace Dot42.CompilerLib.RL.Transformations { /// <summary> /// Remove code that cannot be reached. /// </summary> internal sealed class EliminateDeadCodeTransformation : IRLTransformation { public bool Transform(Dex target, MethodBody body) { bool hasChanges = false; #if DEBUG //return; #endif var instructions = body.Instructions; bool[] reachable = new bool[instructions.Count]; MarkReachable(0, instructions, reachable, body); for (int i = instructions.Count - 1; i > 0 ; --i) { // the nop-remover will also correcly remove exception handlers. if (!reachable[i] && instructions[i].Code != RCode.Nop) { instructions[i].ConvertToNop(); hasChanges = true; } } return hasChanges; } private void MarkReachable(int index, InstructionList instructions, bool[] reachable, MethodBody body) { for (;index < instructions.Count; ++index) { if (reachable[index]) return; // marked before. var ins = instructions[index]; reachable[index] = true; foreach (var ex in body.Exceptions.Where(p => p.TryStart.Index <= index && p.TryEnd.Index >= index)) { ex.Catches.ForEach(c => MarkReachable(c.Instruction.Index, instructions, reachable, body)); if (ex.CatchAll != null) MarkReachable(ex.CatchAll.Index, instructions, reachable, body); } if (ins.Code.IsReturn() || ins.Code == RCode.Throw) return; if (ins.Code == RCode.Goto) { MarkReachable(((Instruction) ins.Operand).Index, instructions, reachable, body); return; } if (ins.Code == RCode.Packed_switch) { foreach (var target in (Instruction[]) ins.Operand) MarkReachable(target.Index, instructions, reachable, body); } else if (ins.Code == RCode.Sparse_switch) { foreach (var target in (IList<Tuple<int,Instruction>>)ins.Operand) MarkReachable(target.Item2.Index, instructions, reachable, body); } else if (ins.Code.IsBranch()) { MarkReachable(((Instruction) ins.Operand).Index, instructions, reachable, body); } } } } }
412
0.926266
1
0.926266
game-dev
MEDIA
0.512967
game-dev
0.837485
1
0.837485
ehmatthes/pcc
6,329
chapter_13/game_functions.py
import sys from time import sleep import pygame from bullet import Bullet from alien import Alien def check_keydown_events(event, ai_settings, screen, ship, bullets): """Respond to keypresses.""" if event.key == pygame.K_RIGHT: ship.moving_right = True elif event.key == pygame.K_LEFT: ship.moving_left = True elif event.key == pygame.K_SPACE: fire_bullet(ai_settings, screen, ship, bullets) elif event.key == pygame.K_q: sys.exit() def check_keyup_events(event, ship): """Respond to key releases.""" if event.key == pygame.K_RIGHT: ship.moving_right = False elif event.key == pygame.K_LEFT: ship.moving_left = False def check_events(ai_settings, screen, ship, bullets): """Respond to keypresses and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: check_keydown_events(event, ai_settings, screen, ship, bullets) elif event.type == pygame.KEYUP: check_keyup_events(event, ship) def fire_bullet(ai_settings, screen, ship, bullets): """Fire a bullet, if limit not reached yet.""" # Create a new bullet, add to bullets group. if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet) def update_screen(ai_settings, screen, ship, aliens, bullets): """Update images on the screen, and flip to the new screen.""" # Redraw the screen, each pass through the loop. screen.fill(ai_settings.bg_color) # Redraw all bullets, behind ship and aliens. for bullet in bullets.sprites(): bullet.draw_bullet() ship.blitme() aliens.draw(screen) # Make the most recently drawn screen visible. pygame.display.flip() def update_bullets(ai_settings, screen, ship, aliens, bullets): """Update position of bullets, and get rid of old bullets.""" # Update bullet positions. bullets.update() # Get rid of bullets that have disappeared. for bullet in bullets.copy(): if bullet.rect.bottom <= 0: bullets.remove(bullet) check_bullet_alien_collisions(ai_settings, screen, ship, aliens, bullets) def check_bullet_alien_collisions(ai_settings, screen, ship, aliens, bullets): """Respond to bullet-alien collisions.""" # Remove any bullets and aliens that have collided. collisions = pygame.sprite.groupcollide(bullets, aliens, True, True) if len(aliens) == 0: # Destroy existing bullets, and create new fleet. bullets.empty() create_fleet(ai_settings, screen, ship, aliens) def check_fleet_edges(ai_settings, aliens): """Respond appropriately if any aliens have reached an edge.""" for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(ai_settings, aliens) break def change_fleet_direction(ai_settings, aliens): """Drop the entire fleet, and change the fleet's direction.""" for alien in aliens.sprites(): alien.rect.y += ai_settings.fleet_drop_speed ai_settings.fleet_direction *= -1 def ship_hit(ai_settings, stats, screen, ship, aliens, bullets): """Respond to ship being hit by alien.""" if stats.ships_left > 0: # Decrement ships_left. stats.ships_left -= 1 else: stats.game_active = False # Empty the list of aliens and bullets. aliens.empty() bullets.empty() # Create a new fleet, and center the ship. create_fleet(ai_settings, screen, ship, aliens) ship.center_ship() # Pause. sleep(0.5) def check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets): """Check if any aliens have reached the bottom of the screen.""" screen_rect = screen.get_rect() for alien in aliens.sprites(): if alien.rect.bottom >= screen_rect.bottom: # Treat this the same as if the ship got hit. ship_hit(ai_settings, stats, screen, ship, aliens, bullets) break def update_aliens(ai_settings, stats, screen, ship, aliens, bullets): """ Check if the fleet is at an edge, then update the postions of all aliens in the fleet. """ check_fleet_edges(ai_settings, aliens) aliens.update() # Look for alien-ship collisions. if pygame.sprite.spritecollideany(ship, aliens): ship_hit(ai_settings, stats, screen, ship, aliens, bullets) # Look for aliens hitting the bottom of the screen. check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets) def get_number_aliens_x(ai_settings, alien_width): """Determine the number of aliens that fit in a row.""" available_space_x = ai_settings.screen_width - 2 * alien_width number_aliens_x = int(available_space_x / (2 * alien_width)) return number_aliens_x def get_number_rows(ai_settings, ship_height, alien_height): """Determine the number of rows of aliens that fit on the screen.""" available_space_y = (ai_settings.screen_height - (3 * alien_height) - ship_height) number_rows = int(available_space_y / (2 * alien_height)) return number_rows def create_alien(ai_settings, screen, aliens, alien_number, row_number): """Create an alien, and place it in the row.""" alien = Alien(ai_settings, screen) alien_width = alien.rect.width alien.x = alien_width + 2 * alien_width * alien_number alien.rect.x = alien.x alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number aliens.add(alien) def create_fleet(ai_settings, screen, ship, aliens): """Create a full fleet of aliens.""" # Create an alien, and find number of aliens in a row. alien = Alien(ai_settings, screen) number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width) number_rows = get_number_rows(ai_settings, ship.rect.height, alien.rect.height) # Create the fleet of aliens. for row_number in range(number_rows): for alien_number in range(number_aliens_x): create_alien(ai_settings, screen, aliens, alien_number, row_number)
412
0.720725
1
0.720725
game-dev
MEDIA
0.938358
game-dev
0.72077
1
0.72077
Forairaaaaa/Chappie-II
2,827
Firmware/src/ChappieUI/Apps/App_Dino/Dino/src/Dino.cpp
// #include "Dino.h" // #include "assets/sprites.h" #include "../include/Dino.h" #include "../include/assets/sprites.h" Dino::Dino(uint8_t const x, uint8_t const baseline) : _x(x) , _y(baseline - DINO_HEIGHT) , _vy(0) , _baseline(baseline) , _jumping(false) , _frame(0) {} SQ7x8 const Dino::y() const { return _y; } bool const Dino::jumping() const { return _jumping; } void Dino::reset() { _y = _baseline - DINO_HEIGHT; _vy = 0; _jumping = false; _frame = 0; } void Dino::jump() { _vy = -_JUMP; _jumping = true; } void Dino::wait() { static uint8_t flip = 0; if (((millis() >> 7) & 0x1) == flip) { _frame++; if (_frame == DINO_WAIT_FRAMES) _frame = 0; flip = !flip; } } bool const Dino::collidingWith(int8_t const x, uint8_t const y, uint8_t const size) const { return _x + 2 < x + size && _x + DINO_WIDTH - 2 > x && _y < y + size && _y + DINO_HEIGHT - 1 > y; } void Dino::update(SQ15x16 const speed) { _y += _vy; _vy += _GRAVITY; if (_y + DINO_HEIGHT > _baseline) { _y = _baseline - DINO_HEIGHT; _vy = 0; _jumping = false; } static uint8_t counter = 0; static uint8_t start_frame = DINO_WAIT_FRAMES; static uint8_t end_frame = start_frame + DINO_RUN_FRAMES; if (++counter * speed > 6) { counter = 0; _frame++; if (_frame < end_frame) return; _frame = start_frame; } } void Dino::draw(LGFX_Sprite * const framebuffer) const { framebuffer->pushImage( static_cast<uint8_t>(_x), static_cast<int8_t>(_y), DINO_WIDTH, DINO_HEIGHT, DINO + (_jumping ? DINO_JUMP_FRAME : _frame) * DINO_FRAME_SIZE, TRANS_COLOR ); } /** * ---------------------------------------------------------------------------- * Dino Game * ---------------------------------------------------------------------------- * Copyright (c) 2022 Stéphane Calderoni (https://github.com/m1cr0lab) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * ---------------------------------------------------------------------------- */
412
0.888779
1
0.888779
game-dev
MEDIA
0.844641
game-dev
0.96275
1
0.96275
lua9520/source-engine-2018-cstrike15_src
18,330
game/client/cstrike15/gameui/urlbutton.cpp
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: Basic button control // // $NoKeywords: $ //=============================================================================// #include <stdio.h> #include <utlsymbol.h> #include <vgui/IBorder.h> #include <vgui/IInput.h> #include <vgui/IScheme.h> #include <vgui/ISurface.h> #include <vgui/ISystem.h> #include <vgui/IVGui.h> #include <vgui/MouseCode.h> #include <vgui/KeyCode.h> #include <keyvalues.h> #include "urlbutton.h" #include <vgui_controls/FocusNavGroup.h> // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> using namespace vgui; DECLARE_BUILD_FACTORY_DEFAULT_TEXT( URLButton, URLButton ); //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- URLButton::URLButton(Panel *parent, const char *panelName, const char *text, Panel *pActionSignalTarget, const char *pCmd ) : Label(parent, panelName, text) { Init(); if ( pActionSignalTarget && pCmd ) { AddActionSignalTarget( pActionSignalTarget ); SetCommand( pCmd ); } } //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- URLButton::URLButton(Panel *parent, const char *panelName, const wchar_t *wszText, Panel *pActionSignalTarget, const char *pCmd ) : Label(parent, panelName, wszText) { Init(); if ( pActionSignalTarget && pCmd ) { AddActionSignalTarget( pActionSignalTarget ); SetCommand( pCmd ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void URLButton::Init() { _buttonFlags.SetFlag( USE_CAPTURE_MOUSE | BUTTON_BORDER_ENABLED ); _mouseClickMask = 0; _actionMessage = NULL; m_bSelectionStateSaved = false; SetTextInset(0, 0); SetMouseClickEnabled( MOUSE_LEFT, true ); SetButtonActivationType(ACTIVATE_ONPRESSEDANDRELEASED); // labels have this off by default, but we need it on SetPaintBackgroundEnabled( true ); } //----------------------------------------------------------------------------- // Purpose: Destructor //----------------------------------------------------------------------------- URLButton::~URLButton() { if (_actionMessage) { _actionMessage->deleteThis(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void URLButton::SetButtonActivationType(ActivationType_t activationType) { _activationType = activationType; } //----------------------------------------------------------------------------- // Purpose: Set button border attribute enabled. //----------------------------------------------------------------------------- void URLButton::SetButtonBorderEnabled( bool state ) { if ( state != _buttonFlags.IsFlagSet( BUTTON_BORDER_ENABLED ) ) { _buttonFlags.SetFlag( BUTTON_BORDER_ENABLED, state ); InvalidateLayout(false); } } //----------------------------------------------------------------------------- // Purpose: Set button selected state. //----------------------------------------------------------------------------- void URLButton::SetSelected( bool state ) { if ( _buttonFlags.IsFlagSet( SELECTED ) != state ) { _buttonFlags.SetFlag( SELECTED, state ); RecalculateDepressedState(); InvalidateLayout(false); } } //----------------------------------------------------------------------------- // Purpose: Set button force depressed state. //----------------------------------------------------------------------------- void URLButton::ForceDepressed(bool state) { if ( _buttonFlags.IsFlagSet( FORCE_DEPRESSED ) != state ) { _buttonFlags.SetFlag( FORCE_DEPRESSED, state ); RecalculateDepressedState(); InvalidateLayout(false); } } //----------------------------------------------------------------------------- // Purpose: Set button depressed state with respect to the force depressed state. //----------------------------------------------------------------------------- void URLButton::RecalculateDepressedState( void ) { bool newState; if (!IsEnabled()) { newState = false; } else { newState = _buttonFlags.IsFlagSet( FORCE_DEPRESSED ) ? true : (_buttonFlags.IsFlagSet(ARMED) && _buttonFlags.IsFlagSet( SELECTED ) ); } _buttonFlags.SetFlag( DEPRESSED, newState ); } //----------------------------------------------------------------------------- // Purpose: Sets whether or not the button captures all mouse input when depressed // Defaults to true // Should be set to false for things like menu items where there is a higher-level mouse capture //----------------------------------------------------------------------------- void URLButton::SetUseCaptureMouse( bool state ) { _buttonFlags.SetFlag( USE_CAPTURE_MOUSE, state ); } //----------------------------------------------------------------------------- // Purpose: Check if mouse capture is enabled. // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool URLButton::IsUseCaptureMouseEnabled( void ) { return _buttonFlags.IsFlagSet( USE_CAPTURE_MOUSE ); } //----------------------------------------------------------------------------- // Purpose: Set armed state. //----------------------------------------------------------------------------- void URLButton::SetArmed(bool state) { if ( _buttonFlags.IsFlagSet( ARMED ) != state ) { _buttonFlags.SetFlag( ARMED, state ); RecalculateDepressedState(); InvalidateLayout(false); } } //----------------------------------------------------------------------------- // Purpose: Check armed state //----------------------------------------------------------------------------- bool URLButton::IsArmed() { return _buttonFlags.IsFlagSet( ARMED ); } KeyValues *URLButton::GetActionMessage() { return _actionMessage->MakeCopy(); } //----------------------------------------------------------------------------- // Purpose: Activate a button click. //----------------------------------------------------------------------------- void URLButton::DoClick() { SetSelected(true); FireActionSignal(); SetSelected(false); } //----------------------------------------------------------------------------- // Purpose: Check selected state //----------------------------------------------------------------------------- bool URLButton::IsSelected() { return _buttonFlags.IsFlagSet( SELECTED ); } //----------------------------------------------------------------------------- // Purpose: Check depressed state //----------------------------------------------------------------------------- bool URLButton::IsDepressed() { return _buttonFlags.IsFlagSet( DEPRESSED ); } //----------------------------------------------------------------------------- // Drawing focus box? //----------------------------------------------------------------------------- bool URLButton::IsDrawingFocusBox() { return _buttonFlags.IsFlagSet( DRAW_FOCUS_BOX ); } void URLButton::DrawFocusBox( bool bEnable ) { _buttonFlags.SetFlag( DRAW_FOCUS_BOX, bEnable ); } //----------------------------------------------------------------------------- // Purpose: Paint button on screen //----------------------------------------------------------------------------- void URLButton::Paint(void) { BaseClass::Paint(); int x, y; int controlWidth, controlHeight, textWidth, textHeight; GetSize(controlWidth, controlHeight); GetContentSize(textWidth, textHeight); x = textWidth; y = controlHeight - 4; surface()->DrawSetColor(GetButtonFgColor()); surface()->DrawLine(0, y, x, y); } //----------------------------------------------------------------------------- // Purpose: Perform graphical layout of button. //----------------------------------------------------------------------------- void URLButton::PerformLayout() { // set our color SetFgColor(GetButtonFgColor()); SetBgColor(GetButtonBgColor()); BaseClass::PerformLayout(); } //----------------------------------------------------------------------------- // Purpose: Get button foreground color // Output : Color //----------------------------------------------------------------------------- Color URLButton::GetButtonFgColor() { return _defaultFgColor; } //----------------------------------------------------------------------------- // Purpose: Get button background color //----------------------------------------------------------------------------- Color URLButton::GetButtonBgColor() { return _defaultBgColor; } //----------------------------------------------------------------------------- // Purpose: Called when key focus is received //----------------------------------------------------------------------------- void URLButton::OnSetFocus() { InvalidateLayout(false); BaseClass::OnSetFocus(); } //----------------------------------------------------------------------------- // Purpose: Respond when focus is killed //----------------------------------------------------------------------------- void URLButton::OnKillFocus() { InvalidateLayout(false); BaseClass::OnKillFocus(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void URLButton::ApplySchemeSettings(IScheme *pScheme) { BaseClass::ApplySchemeSettings(pScheme); _defaultFgColor = GetSchemeColor("Button.TextColor", Color(255, 255, 255, 255), pScheme); _defaultBgColor = GetSchemeColor("Button.BgColor", Color(0, 0, 0, 255), pScheme); InvalidateLayout(); } //----------------------------------------------------------------------------- // Purpose: Set button to be mouse clickable or not. //----------------------------------------------------------------------------- void URLButton::SetMouseClickEnabled(MouseCode code,bool state) { if(state) { //set bit to 1 _mouseClickMask|=1<<((int)(code+1)); } else { //set bit to 0 _mouseClickMask&=~(1<<((int)(code+1))); } } //----------------------------------------------------------------------------- // Purpose: sets the command to send when the button is pressed //----------------------------------------------------------------------------- void URLButton::SetCommand( const char *command ) { SetCommand(new KeyValues("Command", "command", command)); } //----------------------------------------------------------------------------- // Purpose: sets the message to send when the button is pressed //----------------------------------------------------------------------------- void URLButton::SetCommand( KeyValues *message ) { // delete the old message if (_actionMessage) { _actionMessage->deleteThis(); } _actionMessage = message; } //----------------------------------------------------------------------------- // Purpose: Peeks at the message to send when button is pressed // Input : - // Output : KeyValues //----------------------------------------------------------------------------- KeyValues *URLButton::GetCommand() { return _actionMessage; } //----------------------------------------------------------------------------- // Purpose: Message targets that the button has been pressed //----------------------------------------------------------------------------- void URLButton::FireActionSignal() { // message-based action signal if (_actionMessage) { // see if it's a url if (!stricmp(_actionMessage->GetName(), "command") && StringHasPrefix(_actionMessage->GetString("command", ""), "url " ) && strstr(_actionMessage->GetString("command", ""), "://")) { // it's a command to launch a url, run it system()->ShellExecute("open", _actionMessage->GetString("command", " ") + 4); } PostActionSignal(_actionMessage->MakeCopy()); } } //----------------------------------------------------------------------------- // Purpose: gets info about the button //----------------------------------------------------------------------------- bool URLButton::RequestInfo(KeyValues *outputData) { if (!stricmp(outputData->GetName(), "GetState")) { outputData->SetInt("state", IsSelected()); return true; } else if ( !stricmp( outputData->GetName(), "GetCommand" )) { if ( _actionMessage ) { outputData->SetString( "command", _actionMessage->GetString( "command", "" ) ); } else { outputData->SetString( "command", "" ); } return true; } return BaseClass::RequestInfo(outputData); } //----------------------------------------------------------------------------- // Purpose: Get control settings for editing //----------------------------------------------------------------------------- void URLButton::GetSettings( KeyValues *outResourceData ) { BaseClass::GetSettings(outResourceData); if (_actionMessage) { outResourceData->SetString("command", _actionMessage->GetString("command", "")); } outResourceData->SetInt("default", _buttonFlags.IsFlagSet( DEFAULT_BUTTON ) ); if ( m_bSelectionStateSaved ) { outResourceData->SetInt( "selected", IsSelected() ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void URLButton::ApplySettings( KeyValues *inResourceData ) { BaseClass::ApplySettings(inResourceData); const char *cmd = inResourceData->GetString("command", ""); if (*cmd) { // add in the command SetCommand(cmd); } // saved selection state int iSelected = inResourceData->GetInt( "selected", -1 ); if ( iSelected != -1 ) { SetSelected( iSelected != 0 ); m_bSelectionStateSaved = true; } } //----------------------------------------------------------------------------- // Purpose: Describes editing details //----------------------------------------------------------------------------- const char *URLButton::GetDescription( void ) { static char buf[1024]; Q_snprintf(buf, sizeof(buf), "%s, string command, int default", BaseClass::GetDescription()); return buf; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void URLButton::OnSetState(int state) { SetSelected(state ? true : false); Repaint(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void URLButton::OnCursorEntered() { if (IsEnabled()) { SetArmed(true); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void URLButton::OnCursorExited() { if ( !_buttonFlags.IsFlagSet( BUTTON_KEY_DOWN ) ) { SetArmed(false); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void URLButton::OnMousePressed(MouseCode code) { if (!IsEnabled()) return; if (_activationType == ACTIVATE_ONPRESSED) { if ( IsKeyBoardInputEnabled() ) { RequestFocus(); } DoClick(); return; } if (IsUseCaptureMouseEnabled() && _activationType == ACTIVATE_ONPRESSEDANDRELEASED) { { if ( IsKeyBoardInputEnabled() ) { RequestFocus(); } SetSelected(true); Repaint(); } // lock mouse input to going to this button input()->SetMouseCapture(GetVPanel()); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void URLButton::OnMouseDoublePressed(MouseCode code) { OnMousePressed(code); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void URLButton::OnMouseReleased(MouseCode code) { // ensure mouse capture gets released if (IsUseCaptureMouseEnabled()) { input()->SetMouseCapture(NULL); } if (_activationType == ACTIVATE_ONPRESSED) return; if (!IsSelected() && _activationType == ACTIVATE_ONPRESSEDANDRELEASED) return; // it has to be both enabled and (mouse over the button or using a key) to fire if ( IsEnabled() && ( GetVPanel() == input()->GetMouseOver() || _buttonFlags.IsFlagSet( BUTTON_KEY_DOWN ) ) ) { DoClick(); } else { SetSelected(false); } // make sure the button gets unselected Repaint(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void URLButton::OnKeyCodePressed(KeyCode code) { if (code == KEY_SPACE || code == KEY_ENTER) { SetArmed(true); _buttonFlags.SetFlag( BUTTON_KEY_DOWN ); OnMousePressed(MOUSE_LEFT); if (IsUseCaptureMouseEnabled()) // undo the mouse capture since its a fake mouse click! { input()->SetMouseCapture(NULL); } } else { _buttonFlags.ClearFlag( BUTTON_KEY_DOWN ); BaseClass::OnKeyCodePressed(code); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void URLButton::OnKeyCodeReleased(KeyCode code) { if (_buttonFlags.IsFlagSet( BUTTON_KEY_DOWN ) && (code == KEY_SPACE || code == KEY_ENTER)) { SetArmed(true); OnMouseReleased(MOUSE_LEFT); } else { BaseClass::OnKeyCodeReleased(code); } _buttonFlags.ClearFlag( BUTTON_KEY_DOWN ); SetArmed(false); } //----------------------------------------------------------------------------- // Purpose: Size the object to its button and text. - only works from in ApplySchemeSettings or PerformLayout() //----------------------------------------------------------------------------- void URLButton::SizeToContents() { int wide, tall; GetContentSize(wide, tall); SetSize(wide + Label::Content, tall + Label::Content); }
412
0.593241
1
0.593241
game-dev
MEDIA
0.505323
game-dev
0.654002
1
0.654002
neverlosecc/source2sdk
2,227
sdk/include/source2sdk/modellib/SkeletonAnimCapture_t_FrameStamp_t.hpp
#pragma once #include "source2sdk/source2gen/source2gen.hpp" #include <cstddef> #include <cstdint> // ///////////////////////////////////////////////////////////// // Module: modellib // Created using source2gen - github.com/neverlosecc/source2gen // ///////////////////////////////////////////////////////////// namespace source2sdk { namespace modellib { // Registered alignment: 0x4 // Alignment: 0x4 // Standard-layout class: true // Size: 0x1c // Has Trivial Destructor // // static metadata: MGetKV3ClassDefaults #pragma pack(push, 1) struct SkeletonAnimCapture_t_FrameStamp_t { public: float m_flTime; // 0x0 float m_flEntitySimTime; // 0x4 bool m_bTeleportTick; // 0x8 bool m_bPredicted; // 0x9 uint8_t _pad000a[0x2]; // 0xa float m_flCurTime; // 0xc float m_flRealTime; // 0x10 std::int32_t m_nFrameCount; // 0x14 std::int32_t m_nTickCount; // 0x18 }; #pragma pack(pop) static_assert(offsetof(source2sdk::modellib::SkeletonAnimCapture_t_FrameStamp_t, m_flTime) == 0x0); static_assert(offsetof(source2sdk::modellib::SkeletonAnimCapture_t_FrameStamp_t, m_flEntitySimTime) == 0x4); static_assert(offsetof(source2sdk::modellib::SkeletonAnimCapture_t_FrameStamp_t, m_bTeleportTick) == 0x8); static_assert(offsetof(source2sdk::modellib::SkeletonAnimCapture_t_FrameStamp_t, m_bPredicted) == 0x9); static_assert(offsetof(source2sdk::modellib::SkeletonAnimCapture_t_FrameStamp_t, m_flCurTime) == 0xc); static_assert(offsetof(source2sdk::modellib::SkeletonAnimCapture_t_FrameStamp_t, m_flRealTime) == 0x10); static_assert(offsetof(source2sdk::modellib::SkeletonAnimCapture_t_FrameStamp_t, m_nFrameCount) == 0x14); static_assert(offsetof(source2sdk::modellib::SkeletonAnimCapture_t_FrameStamp_t, m_nTickCount) == 0x18); static_assert(sizeof(source2sdk::modellib::SkeletonAnimCapture_t_FrameStamp_t) == 0x1c); }; };
412
0.800847
1
0.800847
game-dev
MEDIA
0.615419
game-dev
0.552022
1
0.552022
Flo56958/MineTinker
3,691
src/main/java/de/flo56958/minetinker/modifiers/types/Vigilant.java
package de.flo56958.minetinker.modifiers.types; import de.flo56958.minetinker.MineTinker; import de.flo56958.minetinker.api.events.MTEntityDamageByEntityEvent; import de.flo56958.minetinker.data.ToolType; import de.flo56958.minetinker.modifiers.Modifier; import de.flo56958.minetinker.utils.ConfigurationManager; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeModifier; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.inventory.EquipmentSlotGroup; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.jetbrains.annotations.NotNull; import java.io.File; import java.util.Collections; import java.util.List; public class Vigilant extends Modifier implements Listener { private static Vigilant instance; private double percentile; private Vigilant() { super(MineTinker.getPlugin()); customModelData = 10_061; } public static Vigilant instance() { synchronized (Vigilant.class) { if (instance == null) instance = new Vigilant(); } return instance; } @Override public String getKey() { return "Vigilant"; } @Override public List<ToolType> getAllowedTools() { return Collections.singletonList(ToolType.CHESTPLATE); } @Override public void reload() { FileConfiguration config = getConfig(); config.options().copyDefaults(true); config.addDefault("Allowed", true); config.addDefault("Color", "%GRAY%"); config.addDefault("MaxLevel", 3); config.addDefault("SlotCost", 1); config.addDefault("ModifierItemMaterial", Material.GOLDEN_APPLE.name()); config.addDefault("EnchantCost", 10); config.addDefault("Enchantable", true); config.addDefault("MinimumToolLevelRequirement", 1); config.addDefault("AmountDamageAsShield", 0.33); config.addDefault("Recipe.Enabled", false); ConfigurationManager.saveConfig(config); ConfigurationManager.loadConfig("Modifiers" + File.separator, getFileName()); init(); this.percentile = config.getDouble("AmountDamageAsShield", 0.33); this.description = this.description.replaceAll("%amount", Math.round(this.percentile * 100) + "%"); } private void effect(@NotNull final Player player, final double damage) { if (!player.hasPermission(getUsePermission())) return; if (player.getAbsorptionAmount() >= 0.5) return; final ItemStack chestplate = player.getInventory().getChestplate(); if (!modManager.isArmorViable(chestplate)) return; if (!modManager.hasMod(chestplate, this)) return; final int level = modManager.getModLevel(chestplate, this); final double absorption = damage * this.percentile * level; // Make sure the player can receive the absorption final ItemMeta meta = chestplate.getItemMeta(); if (meta == null) return; meta.removeAttributeModifier(Attribute.MAX_ABSORPTION); // Overwrite the old values meta.addAttributeModifier(Attribute.MAX_ABSORPTION, new AttributeModifier( new NamespacedKey(MineTinker.getPlugin(), "generic.max_absorption"), absorption, AttributeModifier.Operation.ADD_NUMBER, EquipmentSlotGroup.CHEST)); chestplate.setItemMeta(meta); // Add absorption player.setAbsorptionAmount(absorption); } @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void onDamage(@NotNull MTEntityDamageByEntityEvent event) { // Player was damaged if (event.getPlayer().equals(event.getEvent().getEntity())) effect(event.getPlayer(), Math.max(0.0d, event.getEvent().getFinalDamage())); } }
412
0.984537
1
0.984537
game-dev
MEDIA
0.973631
game-dev
0.99125
1
0.99125
kunitoki/yup
4,508
thirdparty/rive/source/animation/blend_state_1d_instance.cpp
#include "rive/animation/blend_state_1d_input.hpp" #include "rive/animation/blend_state_1d_instance.hpp" #include "rive/animation/blend_state_1d_viewmodel.hpp" #include "rive/animation/state_machine_input_instance.hpp" #include "rive/data_bind/bindable_property_number.hpp" #include "rive/animation/layer_state_flags.hpp" using namespace rive; BlendState1DInstance::BlendState1DInstance(const BlendState1D* blendState, ArtboardInstance* instance) : BlendStateInstance<BlendState1D, BlendAnimation1D>(blendState, instance) { if ((static_cast<LayerStateFlags>(blendState->flags()) & LayerStateFlags::Reset) == LayerStateFlags::Reset) { auto animations = std::vector<const LinearAnimation*>(); for (auto blendAnimation : blendState->animations()) { animations.push_back(blendAnimation->animation()); } m_AnimationReset = AnimationResetFactory::fromAnimations(animations, instance, true); } } BlendState1DInstance::~BlendState1DInstance() { if (m_AnimationReset != nullptr) { AnimationResetFactory::release(std::move(m_AnimationReset)); } } int BlendState1DInstance::animationIndex(float value) { int idx = 0; int mid = 0; float closestValue = 0; int start = 0; int end = static_cast<int>(m_AnimationInstances.size()) - 1; while (start <= end) { mid = (start + end) >> 1; closestValue = m_AnimationInstances[mid].blendAnimation()->value(); if (closestValue < value) { start = mid + 1; } else if (closestValue > value) { end = mid - 1; } else { idx = start = mid; break; } idx = start; } return idx; } void BlendState1DInstance::apply(ArtboardInstance* instance, float mix) { if (m_AnimationReset != nullptr) { m_AnimationReset->apply(instance); } BlendStateInstance::apply(instance, mix); } void BlendState1DInstance::advance(float seconds, StateMachineInstance* stateMachineInstance) { BlendStateInstance<BlendState1D, BlendAnimation1D>::advance( seconds, stateMachineInstance); float value = 0.0f; if (state()->is<BlendState1DInput>()) { auto blendState = state()->as<BlendState1DInput>(); if (blendState->hasValidInputId()) { // TODO: https://github.com/rive-app/rive-cpp/issues/229 auto inputInstance = stateMachineInstance->input(blendState->inputId()); auto numberInput = static_cast<const SMINumber*>(inputInstance); value = numberInput->value(); } } else if (state()->is<BlendState1DViewModel>()) { auto blendState = state()->as<BlendState1DViewModel>(); auto bindablePropertyInstance = stateMachineInstance->bindablePropertyInstance( blendState->bindableProperty()); if (bindablePropertyInstance->is<BindablePropertyNumber>()) { value = bindablePropertyInstance->as<BindablePropertyNumber>() ->propertyValue(); } } int index = animationIndex(value); auto animationsCount = static_cast<int>(m_AnimationInstances.size()); m_To = index >= 0 && index < animationsCount ? &m_AnimationInstances[index] : nullptr; m_From = index - 1 >= 0 && index - 1 < animationsCount ? &m_AnimationInstances[index - 1] : nullptr; float mix, mixFrom; auto toValue = m_To == nullptr ? 0.0f : m_To->blendAnimation()->value(); auto fromValue = m_From == nullptr ? 0.0f : m_From->blendAnimation()->value(); if (m_To == nullptr || m_From == nullptr || toValue == fromValue) { mix = mixFrom = 1.0f; } else { mix = (value - fromValue) / (toValue - fromValue); mixFrom = 1.0f - mix; } for (auto& animation : m_AnimationInstances) { auto animationValue = animation.blendAnimation()->value(); if (m_To != nullptr && animationValue == toValue) { animation.mix(mix); } else if (m_From != nullptr && animationValue == fromValue) { animation.mix(mixFrom); } else { animation.mix(0.0f); } } }
412
0.904158
1
0.904158
game-dev
MEDIA
0.549047
game-dev,graphics-rendering
0.935732
1
0.935732
marinbenc/ReactiveWeatherExample
1,804
Pods/RxSwift/RxSwift/Observables/Implementations/Scan.swift
// // Scan.swift // RxSwift // // Created by Krunoslav Zaher on 6/14/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class ScanSink<ElementType, Accumulate, O: ObserverType where O.E == Accumulate> : Sink<O>, ObserverType { typealias Parent = Scan<ElementType, Accumulate> typealias E = ElementType private let _parent: Parent private var _accumulate: Accumulate init(parent: Parent, observer: O) { _parent = parent _accumulate = parent._seed super.init(observer: observer) } func on(event: Event<ElementType>) { switch event { case .Next(let element): do { _accumulate = try _parent._accumulator(_accumulate, element) forwardOn(.Next(_accumulate)) } catch let error { forwardOn(.Error(error)) dispose() } case .Error(let error): forwardOn(.Error(error)) dispose() case .Completed: forwardOn(.Completed) dispose() } } } class Scan<Element, Accumulate>: Producer<Accumulate> { typealias Accumulator = (Accumulate, Element) throws -> Accumulate private let _source: Observable<Element> private let _seed: Accumulate private let _accumulator: Accumulator init(source: Observable<Element>, seed: Accumulate, accumulator: Accumulator) { _source = source _seed = seed _accumulator = accumulator } override func run<O : ObserverType where O.E == Accumulate>(observer: O) -> Disposable { let sink = ScanSink(parent: self, observer: observer) sink.disposable = _source.subscribe(sink) return sink } }
412
0.92065
1
0.92065
game-dev
MEDIA
0.443941
game-dev,mobile
0.889452
1
0.889452
qcdong2016/QCEditor
4,078
cocos2d/external/bullet/include/bullet/BulletDynamics/ConstraintSolver/btGearConstraint.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2012 Advanced Micro Devices, Inc. http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_GEAR_CONSTRAINT_H #define BT_GEAR_CONSTRAINT_H #include "BulletDynamics/ConstraintSolver/btTypedConstraint.h" #ifdef BT_USE_DOUBLE_PRECISION #define btGearConstraintData btGearConstraintDoubleData #define btGearConstraintDataName "btGearConstraintDoubleData" #else #define btGearConstraintData btGearConstraintFloatData #define btGearConstraintDataName "btGearConstraintFloatData" #endif //BT_USE_DOUBLE_PRECISION ///The btGeatConstraint will couple the angular velocity for two bodies around given local axis and ratio. ///See Bullet/Demos/ConstraintDemo for an example use. class btGearConstraint : public btTypedConstraint { protected: btVector3 m_axisInA; btVector3 m_axisInB; bool m_useFrameA; btScalar m_ratio; public: btGearConstraint(btRigidBody& rbA, btRigidBody& rbB, const btVector3& axisInA,const btVector3& axisInB, btScalar ratio=1.f); virtual ~btGearConstraint (); ///internal method used by the constraint solver, don't use them directly virtual void getInfo1 (btConstraintInfo1* info); ///internal method used by the constraint solver, don't use them directly virtual void getInfo2 (btConstraintInfo2* info); void setAxisA(btVector3& axisA) { m_axisInA = axisA; } void setAxisB(btVector3& axisB) { m_axisInB = axisB; } void setRatio(btScalar ratio) { m_ratio = ratio; } const btVector3& getAxisA() const { return m_axisInA; } const btVector3& getAxisB() const { return m_axisInB; } btScalar getRatio() const { return m_ratio; } virtual void setParam(int num, btScalar value, int axis = -1) { (void) num; (void) value; (void) axis; btAssert(0); } ///return the local value of parameter virtual btScalar getParam(int num, int axis = -1) const { (void) num; (void) axis; btAssert(0); return 0.f; } virtual int calculateSerializeBufferSize() const; ///fills the dataBuffer and returns the struct name (and 0 on failure) virtual const char* serialize(void* dataBuffer, btSerializer* serializer) const; }; ///do not change those serialization structures, it requires an updated sBulletDNAstr/sBulletDNAstr64 struct btGearConstraintFloatData { btTypedConstraintFloatData m_typeConstraintData; btVector3FloatData m_axisInA; btVector3FloatData m_axisInB; float m_ratio; char m_padding[4]; }; struct btGearConstraintDoubleData { btTypedConstraintDoubleData m_typeConstraintData; btVector3DoubleData m_axisInA; btVector3DoubleData m_axisInB; double m_ratio; }; SIMD_FORCE_INLINE int btGearConstraint::calculateSerializeBufferSize() const { return sizeof(btGearConstraintData); } ///fills the dataBuffer and returns the struct name (and 0 on failure) SIMD_FORCE_INLINE const char* btGearConstraint::serialize(void* dataBuffer, btSerializer* serializer) const { btGearConstraintData* gear = (btGearConstraintData*)dataBuffer; btTypedConstraint::serialize(&gear->m_typeConstraintData,serializer); m_axisInA.serialize( gear->m_axisInA ); m_axisInB.serialize( gear->m_axisInB ); gear->m_ratio = m_ratio; return btGearConstraintDataName; } #endif //BT_GEAR_CONSTRAINT_H
412
0.886294
1
0.886294
game-dev
MEDIA
0.981165
game-dev
0.799331
1
0.799331
CalamityTeam/CalamityModPublic
4,082
Projectiles/Ranged/SurgeDriverHoldout.cs
using CalamityMod.Items.Weapons.Ranged; using CalamityMod.Sounds; using Microsoft.Xna.Framework; using Terraria; using Terraria.Audio; using Terraria.Localization; using Terraria.ModLoader; namespace CalamityMod.Projectiles.Ranged { public class SurgeDriverHoldout : ModProjectile { public override LocalizedText DisplayName => CalamityUtils.GetItemName<SurgeDriver>(); public Player Owner => Main.player[Projectile.owner]; public ref float ShootCountdown => ref Projectile.ai[0]; public override void SetDefaults() { Projectile.width = 192; Projectile.height = 52; Projectile.friendly = true; Projectile.penetrate = -1; Projectile.tileCollide = false; Projectile.DamageType = DamageClass.Ranged; Projectile.ignoreWater = true; } public override void AI() { Vector2 armPosition = Owner.RotatedRelativePoint(Owner.MountedCenter, true); armPosition += Projectile.velocity.SafeNormalize(Owner.direction * Vector2.UnitX) * 32f; armPosition.Y -= 12f; UpdateProjectileHeldVariables(armPosition); ManipulatePlayerVariables(); // Prevent spam clicking by letting the animation run if the player just stops holding if (Owner.CantUseHoldout() && ShootCountdown < 0f) Projectile.Kill(); // Can't shoot on frame 1 as it can't use ammo yet else if (ShootCountdown < 0f && Owner.HasAmmo(Owner.ActiveItem())) { if (Main.myPlayer == Projectile.owner) { ShootProjectiles(armPosition); ShootCountdown = Owner.ActiveItem().useAnimation - 1; Projectile.netUpdate = true; } SoundEngine.PlaySound(CommonCalamitySounds.LaserCannonSound, Projectile.Center); } ShootCountdown--; } public void ShootProjectiles(Vector2 armPosition) { if (Main.myPlayer != Projectile.owner) return; Item heldItem = Owner.ActiveItem(); Owner.PickAmmo(heldItem, out int projectileType, out float shootSpeed, out int damage, out float knockback, out _); damage *= 4; shootSpeed = heldItem.shootSpeed * Projectile.scale * 0.64f; projectileType = ModContent.ProjectileType<PrismaticEnergyBlast>(); knockback = Owner.GetWeaponKnockback(heldItem, knockback); Vector2 shootDirection = (Main.MouseWorld - Projectile.Center).SafeNormalize(-Vector2.UnitY); Vector2 shootVelocity = shootDirection * shootSpeed; // Sync if the shoot direction changes. if (shootDirection.X != Projectile.velocity.X || shootDirection.Y != Projectile.velocity.Y) Projectile.netUpdate = true; Vector2 gunTip = armPosition + shootDirection * heldItem.scale * 130f; Projectile.NewProjectile(Projectile.GetSource_FromThis(), gunTip, shootVelocity, projectileType, damage, knockback, Projectile.owner, 0f, 0f); Projectile.velocity = shootDirection; } public void UpdateProjectileHeldVariables(Vector2 armPosition) { Projectile.position = armPosition - Projectile.Size * 0.5f; Projectile.rotation = Projectile.velocity.ToRotation(); if (Projectile.spriteDirection == -1) Projectile.rotation += MathHelper.Pi; Projectile.spriteDirection = Projectile.direction; Projectile.timeLeft = 2; } public void ManipulatePlayerVariables() { Owner.ChangeDir(Projectile.direction); Owner.heldProj = Projectile.whoAmI; Owner.itemTime = 2; Owner.itemAnimation = 2; Owner.itemRotation = (Projectile.velocity * Projectile.direction).ToRotation(); } public override bool? CanDamage() => false; } }
412
0.873113
1
0.873113
game-dev
MEDIA
0.99754
game-dev
0.803207
1
0.803207
sebas77/Svelto.MiniExamples
1,881
Example2-Unity Hybrid-Survival/Packages/com.sebaslab.svelto.common/DataStructures/Arrays/FasterListExtension.cs
#if NEW_C_SHARP || !UNITY_5_3_OR_NEWER using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Svelto.DataStructures { public static class FasterListExtension { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<byte> ToByteSpan<T>(this FasterList<T> list) where T : unmanaged { T[] array = list.ToArrayFast(out var count); Span<T> spanT = array.AsSpan(0, count); Span<byte> span = MemoryMarshal.AsBytes(spanT); return span; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> ToSpan<T>(this FasterList<T> list) where T : unmanaged { T[] array = list.ToArrayFast(out var count); Span<T> spanT = array.AsSpan(0, count); return spanT; } #if IF_THE_OTHER_SOLUTION_FAILS internal readonly ref struct DisposableHandle { public DisposableHandle(GCHandle gcHandle) { _gcHandle = gcHandle; } public void Dispose() { _gcHandle.Free(); } readonly GCHandle _gcHandle; } public static DisposableHandle ToSpan<T>(this FasterList<T> list, out ReadOnlySpan<byte> readOnlySpan) where T : unmanaged { unsafe { T[] array = list.ToArrayFast(out var count); var handle = GCHandle.Alloc(array, GCHandleType.Pinned); var intPtr = handle.AddrOfPinnedObject(); var sizeOf = UnsafeUtility.SizeOf<T>(); readOnlySpan = new ReadOnlySpan<byte>((void*)intPtr, count * sizeOf); return new DisposableHandle(handle); } } #endif } } #endif
412
0.957232
1
0.957232
game-dev
MEDIA
0.173211
game-dev
0.92063
1
0.92063
cheyao/2d-minecraft
13,088
src/components/furnace.cpp
#include "components/furnace.hpp" #include "game.hpp" #include "items.hpp" #include "managers/eventManager.hpp" #include "managers/systemManager.hpp" #include "opengl/mesh.hpp" #include "opengl/texture.hpp" #include "registers.hpp" #include "scene.hpp" #include "systems/UISystem.hpp" #include <SDL3/SDL.h> #include <algorithm> #include <cstddef> #include <cstdint> // Crafting table FurnaceInventory::FurnaceInventory(struct furnace_t) : Inventory(Eigen::Vector2f(8, 8), "ui/furnace.png"), mSmeltingItems(3, Components::AIR()), mSmeltingCount(3, 0), mFuelTime(0), mFuelLeft(0), mRecipieTime(0), mLastRecipie(Components::AIR()) { mCountRegister[getID<FurnaceInventory>()] = &mSmeltingCount; mItemRegister[getID<FurnaceInventory>()] = &mSmeltingItems; } bool FurnaceInventory::update(class Scene* const scene, const float delta) { SystemManager* const systemManager = mGame->getSystemManager(); const Eigen::Vector2f dimensions = systemManager->getDemensions(); float sx, sy; float ox, oy; float scale; if (dimensions.x() <= dimensions.y()) { sx = dimensions.x() / 4 * 3; sy = sx / INVENTORY_TEXTURE_WIDTH * INVENTORY_TEXTURE_HEIGHT; ox = sx / 6; oy = (dimensions.y() - sy) / 2; scale = sx / INVENTORY_TEXTURE_WIDTH; } else { sy = dimensions.y() / 4 * 3; sx = sy / INVENTORY_TEXTURE_HEIGHT * INVENTORY_TEXTURE_WIDTH; ox = (dimensions.x() - sx) / 2; oy = sy / 6; scale = sy / INVENTORY_TEXTURE_HEIGHT; } // BOTL of inv // 98x114 ox += (INVENTORY_SLOTS_OFFSET_X + mFuelOffsetX) * scale - (INVENTORY_SLOT_X * scale - sx / INVENTORY_INV_SCALE); oy += (INVENTORY_SLOTS_OFFSET_Y + mFuelOffsetY) * scale - (INVENTORY_SLOT_Y * scale - sy / INVENTORY_INV_SCALE); const float slotx = INVENTORY_SLOT_X * scale; const float sloty = INVENTORY_SLOT_Y * scale; float mouseX, mouseY; SDL_GetMouseState(&mouseX, &mouseY); mouseY = dimensions.y() - mouseY; // Test if player is placing inside grid const auto placeGrid = [&mouseX, &mouseY, &slotx, &sloty, &scene, this](float ox, float oy, int slot) { if (mouseX < ox || mouseY < oy || mouseX > (ox + slotx) || mouseY > (oy + sloty)) { return; } if ((scene->getSignal(EventManager::LEFT_HOLD_SIGNAL) || scene->getSignal(EventManager::RIGHT_HOLD_SIGNAL)) && slot != 2) { mLeftLongClick = scene->getSignal(EventManager::LEFT_HOLD_SIGNAL); // This is long click // Now note the slots if (scene->mMouse.count != 0 && (mSmeltingCount[slot] == 0 || mSmeltingItems[slot] == scene->mMouse.item)) { typename decltype(mPath)::value_type pair = {getID<FurnaceInventory>(), slot}; if (std::ranges::find(mPath, pair) == std::end(mPath)) { mPath.emplace_back(pair); } } } static std::uint64_t lastClick; static std::int64_t lastClickPos; if (scene->getSignal(EventManager::LEFT_CLICK_DOWN_SIGNAL)) { if ((mSmeltingCount[slot] == 0 && scene->mMouse.count != 0 && lastClickPos == slot && (scene->getSignal(EventManager::LEFT_CLICK_DOWN_SIGNAL) - lastClick) < 300ul)) { SDL_assert(scene->mMouse.item != Components::AIR()); // Here we get all stuff together for (const auto [i, inv] : mItemRegister) { for (std::size_t s = 0; s < inv->size(); ++s) { if ((*inv)[s] != scene->mMouse.item) { continue; } auto& count = (*mCountRegister[i])[s]; scene->mMouse.count += count; count = 0; (*inv)[s] = Components::AIR(); } } scene->getSignal(DOUBLE_CLICK_SIGNAL) = false; return; } // Normalize the buttons to grid cords if (scene->mMouse.count == 0 || mSmeltingCount[slot] == 0 || (mSmeltingItems[slot] != scene->mMouse.item)) { if (slot != 2 || scene->mMouse.count == 0) { std::swap(scene->mMouse.count, mSmeltingCount[slot]); std::swap(scene->mMouse.item, mSmeltingItems[slot]); } } else if (mSmeltingItems[slot] == scene->mMouse.item && slot != 2) { mSmeltingCount[slot] += scene->mMouse.count; mSmeltingItems[slot] = scene->mMouse.item; scene->mMouse.item = Components::AIR(); scene->mMouse.count = 0; } lastClickPos = slot; lastClick = SDL_GetTicks(); scene->getSignal(EventManager::LEFT_CLICK_DOWN_SIGNAL) = false; } else if (scene->getSignal(EventManager::RIGHT_CLICK_DOWN_SIGNAL) && mPath.empty()) { // Not empty hand on empty slot if (scene->mMouse.count == 0 && mSmeltingCount[slot] == 0) { return; } if (slot != 2) { // 3 types of actions // One of the slot are empty: place half if (scene->mMouse.count == 0 && mSmeltingCount[slot] != 0) { const auto half = (scene->mMouse.count ? scene->mMouse.count : mSmeltingCount[slot]) / 2; const auto round = (scene->mMouse.count ? scene->mMouse.count : mSmeltingCount[slot]) % 2; const auto item = scene->mMouse.item != Components::AIR() ? scene->mMouse.item : mSmeltingItems[slot]; scene->mMouse.item = mSmeltingItems[slot] = item; scene->mMouse.count = mSmeltingCount[slot] = half; scene->mMouse.count += round; if (scene->mMouse.count == 0) { scene->mMouse.item = Components::AIR(); } // Same block: add one to stack } else if (mSmeltingCount[slot] == 0 || mSmeltingItems[slot] == scene->mMouse.item) { mSmeltingCount[slot] += 1; mSmeltingItems[slot] = scene->mMouse.item; scene->mMouse.count -= 1; if (scene->mMouse.count == 0) { scene->mMouse.item = Components::AIR(); } // different blocks in slot & hand: change } else if (mSmeltingItems[slot] != scene->mMouse.item) { std::swap(scene->mMouse.count, mSmeltingCount[slot]); std::swap(scene->mMouse.item, mSmeltingItems[slot]); } } else { if (mSmeltingItems[slot] != scene->mMouse.item && scene->mMouse.item == Components::AIR()) { std::swap(scene->mMouse.count, mSmeltingCount[slot]); std::swap(scene->mMouse.item, mSmeltingItems[slot]); } } scene->getSignal(EventManager::RIGHT_CLICK_DOWN_SIGNAL) = false; } const auto select = [this, &scene, &slot](const SDL_Scancode s, const std::int64_t n) { if (scene->getSignal(s) && (slot != 2 || mItems[n] == Components::AIR())) { std::swap(mSmeltingCount[slot], mCount[n]); std::swap(mSmeltingItems[slot], mItems[n]); scene->getSignal(s) = false; } }; select(SDL_SCANCODE_1, 0); select(SDL_SCANCODE_2, 1); select(SDL_SCANCODE_3, 2); select(SDL_SCANCODE_4, 3); select(SDL_SCANCODE_5, 4); select(SDL_SCANCODE_6, 5); select(SDL_SCANCODE_7, 6); select(SDL_SCANCODE_8, 7); select(SDL_SCANCODE_9, 8); }; // Uhh placeGrid(ox, oy, 0); ox += mBX * scale; oy += mBY * scale; placeGrid(ox, oy, 1); ox += mOutX * scale; oy += mOutY * scale; placeGrid(ox, oy, 2); return Inventory::update(scene, delta); } void FurnaceInventory::tick(class Scene* const, float delta) { if (registers::SMELTING_RECIPIE.contains(mSmeltingItems[COOK_SLOT])) { const std::pair<double, Components::Item>& recipie = registers::SMELTING_RECIPIE.at(mSmeltingItems[COOK_SLOT]); if (mSmeltingItems[OUTPUT_SLOT] != Components::AIR() && mSmeltingItems[OUTPUT_SLOT] != recipie.second) { mRecipieTime = 0; goto processFuel; } if (mFuelLeft <= 0 && !(mSmeltingCount[FUEL_SLOT] >= 1 && registers::BURNING_TIME.contains(mSmeltingItems[FUEL_SLOT]))) { mFuelTime = 0; mFuelLeft = 0; mRecipieTime = 0; return; } // Here the recipie is valid if (mLastRecipie != recipie.second) { mRecipieTime = 0; mLastRecipie = recipie.second; } mRecipieTime += delta; // First check progress, then deduct fuel // I'm feeling generous if (mRecipieTime >= recipie.first) { mSmeltingCount[COOK_SLOT]--; if (mSmeltingCount[COOK_SLOT] == 0) { mSmeltingItems[COOK_SLOT] = Components::AIR(); } mSmeltingItems[OUTPUT_SLOT] = recipie.second; mSmeltingCount[OUTPUT_SLOT]++; mRecipieTime = 0; } } else { mRecipieTime = 0; } processFuel: mFuelLeft -= delta; if (mFuelLeft < 0) { // Oh no! No more fuel, get some more or abort if (mSmeltingCount[FUEL_SLOT] >= 1 && registers::BURNING_TIME.contains(mSmeltingItems[FUEL_SLOT]) && registers::SMELTING_RECIPIE.contains(mSmeltingItems[COOK_SLOT]) && (mSmeltingItems[OUTPUT_SLOT] == Components::AIR() || mSmeltingItems[OUTPUT_SLOT] == registers::SMELTING_RECIPIE.at(mSmeltingItems[COOK_SLOT]).second)) { mFuelLeft = mFuelTime = registers::BURNING_TIME.at(mSmeltingItems[FUEL_SLOT]); mSmeltingCount[FUEL_SLOT]--; if (mSmeltingCount[FUEL_SLOT] == 0) { mSmeltingItems[FUEL_SLOT] = Components::AIR(); } registers::TEXTURES[Components::Item::FURNACE] = "blocks/furnace-on.png"; } else { mFuelTime = 0; mFuelLeft = 0; mRecipieTime = 0; registers::TEXTURES[Components::Item::FURNACE] = "blocks/furnace.png"; return; } } } void FurnaceInventory::draw(class Scene* scene) { Inventory::drawInventory(scene); Inventory::drawItems(scene); SystemManager* const systemManager = mGame->getSystemManager(); const Eigen::Vector2f dimensions = systemManager->getDemensions(); Shader* const shader = systemManager->getShader("ui.vert", "ui.frag"); Mesh* const mesh = systemManager->getUISystem()->getMesh(); float sx, sy; float ox, oy; float scale; if (dimensions.x() <= dimensions.y()) { sx = dimensions.x() / 4 * 3; sy = sx / INVENTORY_TEXTURE_WIDTH * INVENTORY_TEXTURE_HEIGHT; ox = sx / 6; oy = (dimensions.y() - sy) / 2; scale = sx / INVENTORY_TEXTURE_WIDTH; } else { sy = dimensions.y() / 4 * 3; sx = sy / INVENTORY_TEXTURE_HEIGHT * INVENTORY_TEXTURE_WIDTH; ox = (dimensions.x() - sx) / 2; oy = sy / 6; scale = sy / INVENTORY_TEXTURE_HEIGHT; } ox += (INVENTORY_SLOTS_OFFSET_X + mFuelOffsetX) * scale - (INVENTORY_SLOT_X * scale - sx / INVENTORY_INV_SCALE); oy += (INVENTORY_SLOTS_OFFSET_Y + mFuelOffsetY) * scale - (INVENTORY_SLOT_Y * scale - sy / INVENTORY_INV_SCALE); shader->activate(); shader->set("texture_diffuse"_u, 0); shader->set("size"_u, sx / INVENTORY_INV_SCALE, sy / INVENTORY_INV_SCALE); const bool virtItems = scene->getSignal(EventManager::RIGHT_HOLD_SIGNAL) || scene->getSignal(EventManager::LEFT_HOLD_SIGNAL); std::uint64_t vcount = 0; if (scene->getSignal(EventManager::LEFT_HOLD_SIGNAL)) { if (!mPath.empty()) { vcount = scene->mMouse.count / mPath.size(); } } else { vcount = 1; } const auto drawSlot = [&](float ox, float oy, std::uint64_t slot) { if (!(mSmeltingCount[slot] == 0 && !virtItems)) { auto type = mSmeltingItems[slot]; auto count = mSmeltingCount[slot]; if (virtItems) { if (auto s = std::ranges::find(mPath, std::make_pair(getID<FurnaceInventory>(), slot)); s != mPath.end()) { count += vcount; type = scene->mMouse.item; } else if (count == 0) { // This slot isn't in our path return; } } Texture* const texture = systemManager->getTexture(registers::TEXTURES.at(type)); texture->activate(0); shader->set("offset"_u, ox + 5, oy); mesh->draw(shader); if (count > 1) { mGame->getSystemManager()->getTextSystem()->draw( std::to_string(count), Eigen::Vector2f(ox + INVENTORY_SLOT_X / 2 * scale - 2, oy - 5), false); } shader->activate(); } }; // Fuel spot drawSlot(ox, oy, 0); // Item spot ox += mBX * scale; oy += mBY * scale; drawSlot(ox, oy, 1); // Draw output slot ox += mOutX * scale; oy += mOutY * scale; drawSlot(ox, oy, 2); // Now draw the process & stuff ox -= mOutX * scale; oy -= mOutY * scale; oy -= (INVENTORY_SLOT_Y + 1) * scale; ox -= 1 * scale; // 1. Fuel fire if (mFuelLeft > 0 && mFuelTime != 0) { const float percentage = mFuelLeft / mFuelTime; Texture* const fireTexture = mGame->getSystemManager()->getTexture("ui/lit-progress.png"); Shader* const percentShader = mGame->getSystemManager()->getShader("percentage.vert", "ui.frag"); const Eigen::Vector2f size = fireTexture->getSize() / 7 * scale; percentShader->activate(); percentShader->set("texture_diffuse"_u, 0); percentShader->set("size"_u, size); percentShader->set("offset"_u, ox, oy); percentShader->set("percent"_u, percentage); percentShader->set("vertical"_u, true); fireTexture->activate(0); mesh->draw(percentShader); } ox += 23 * scale; // 2. Recipie time left if (mRecipieTime > 0) { const float percentage = mRecipieTime / registers::SMELTING_RECIPIE.at(mSmeltingItems[COOK_SLOT]).first; Texture* const progressTexture = mGame->getSystemManager()->getTexture("ui/burn-progress.png"); Shader* const percentShader = mGame->getSystemManager()->getShader("percentage.vert", "ui.frag"); const Eigen::Vector2f size = progressTexture->getSize() / 7 * scale; percentShader->activate(); percentShader->set("texture_diffuse"_u, 0); percentShader->set("size"_u, size); percentShader->set("offset"_u, ox, oy); percentShader->set("percent"_u, percentage); percentShader->set("vertical"_u, false); progressTexture->activate(0); mesh->draw(percentShader); } shader->activate(); Inventory::drawMouse(scene); }
412
0.918243
1
0.918243
game-dev
MEDIA
0.805929
game-dev
0.979336
1
0.979336
mrvux/dx11-vvvv
6,435
Nodes/VVVV.DX11.Nodes.MSKinect/Nodes/KinectMSInteractionNode.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using VVVV.PluginInterfaces.V2; using VVVV.PluginInterfaces.V1; using VVVV.MSKinect.Lib; using Microsoft.Kinect.Toolkit.Interaction; using Microsoft.Kinect; using System.ComponentModel.Composition; using VVVV.Core.Logging; using System.IO; namespace VVVV.DX11.Nodes.Nodes { public class InteractionClientTest : IInteractionClient { public InteractionInfo GetInteractionInfoAtLocation(int skeletonTrackingId, InteractionHandType handType, double x, double y) { InteractionInfo info = new InteractionInfo(); info.IsGripTarget = false; info.IsPressTarget = false; info.PressTargetControlId = 2; info.PressAttractionPointX = x; info.PressAttractionPointY = y; return info; } } [PluginInfo(Name="Interaction",Category="Kinect",Version="Microsoft",Author="vux")] public class KinectMSInteractionNode : IPluginEvaluate, IPluginConnections { [Input("Kinect Runtime")] protected Pin<KinectRuntime> FInRuntime; [Output("User Info")] protected ISpread<UserInfo> FOutUI; [Output("Skeleton Id")] protected ISpread<int> FOutSkelId; private bool FInvalidateConnect = false; private InteractionStream stream; private KinectRuntime runtime; private UserInfo[] infos = new UserInfo[InteractionStream.FrameUserInfoArrayLength]; [Import()] protected ILogger log; public KinectMSInteractionNode() { Register(); } private static bool registered = false; private static void Register() { if (!registered) { string path = Path.GetDirectoryName(typeof(KinectMSInteractionNode).Assembly.Location); string varpath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Process); varpath += ";" + path; Environment.SetEnvironmentVariable("Path", varpath, EnvironmentVariableTarget.Process); registered = true; } } public void Evaluate(int SpreadMax) { if (this.FInvalidateConnect) { if (this.FInRuntime.IsConnected) { stream = new InteractionStream(this.FInRuntime[0].Runtime, new InteractionClientTest()); stream.InteractionFrameReady += stream_InteractionFrameReady; this.runtime = this.FInRuntime[0]; this.runtime.SkeletonFrameReady += runtime_SkeletonFrameReady; this.runtime.DepthFrameReady += this.runtime_DepthFrameReady; } else { if (stream != null) { this.runtime.SkeletonFrameReady -= runtime_SkeletonFrameReady; this.runtime.DepthFrameReady -= this.runtime_DepthFrameReady; stream.InteractionFrameReady -= stream_InteractionFrameReady; stream.Dispose(); stream = null; this.runtime = null; } } this.FInvalidateConnect = false; } List<UserInfo> infs = new List<UserInfo>(); for (int i = 0; i < this.infos.Length;i++) { if (this.infos[i] != null) { if (this.infos[i].SkeletonTrackingId != 0) { infs.Add(this.infos[i]); } } } this.FOutSkelId.SliceCount = infs.Count; this.FOutUI.SliceCount = infs.Count; for (int i = 0; i < infs.Count; i++) { UserInfo ui = infs[i]; this.FOutSkelId[i] = ui.SkeletonTrackingId; this.FOutUI[i] = ui; } } void runtime_SkeletonFrameReady(object sender, Microsoft.Kinect.SkeletonFrameReadyEventArgs e) { Skeleton[] skels = null; long ts = 0; using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame()) { if (skeletonFrame != null) { skels = new Skeleton[skeletonFrame.SkeletonArrayLength]; skeletonFrame.CopySkeletonDataTo(skels); ts = skeletonFrame.Timestamp; } } if (skels != null) { Vector4 accel = this.runtime.Runtime.AccelerometerGetCurrentReading(); stream.ProcessSkeleton(skels, accel, ts); } } void runtime_DepthFrameReady(object sender, Microsoft.Kinect.DepthImageFrameReadyEventArgs e) { using (DepthImageFrame frame = e.OpenDepthImageFrame()) { if (frame != null) { try { // Hand data to Interaction framework to be processed this.stream.ProcessDepth(frame.GetRawPixelData(), frame.Timestamp); } catch { // DepthFrame functions may throw when the sensor gets // into a bad state. Ignore the frame in that case. } } } } void stream_InteractionFrameReady(object sender, InteractionFrameReadyEventArgs e) { using (InteractionFrame interactionFrame = e.OpenInteractionFrame()) { if (interactionFrame != null) { interactionFrame.CopyInteractionDataTo(this.infos); } } } public void ConnectPin(IPluginIO pin) { if (pin == this.FInRuntime.PluginIO) { this.FInvalidateConnect = true; } } public void DisconnectPin(IPluginIO pin) { if (pin == this.FInRuntime.PluginIO) { this.FInvalidateConnect = true; } } } }
412
0.731985
1
0.731985
game-dev
MEDIA
0.695621
game-dev
0.868025
1
0.868025
PaperMC/Paper-archive
8,238
patches/server/0079-EntityPathfindEvent.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Aikar <aikar@aikar.co> Date: Mon, 28 Mar 2016 21:22:26 -0400 Subject: [PATCH] EntityPathfindEvent Fires when an Entity decides to start moving to a location. diff --git a/src/main/java/net/minecraft/world/entity/ai/navigation/FlyingPathNavigation.java b/src/main/java/net/minecraft/world/entity/ai/navigation/FlyingPathNavigation.java index b81a5149720daf23d3d33f0aaae51216121ea2e2..2bd66da93227d4e4fc2ec4df47ae94b17f4d39d3 100644 --- a/src/main/java/net/minecraft/world/entity/ai/navigation/FlyingPathNavigation.java +++ b/src/main/java/net/minecraft/world/entity/ai/navigation/FlyingPathNavigation.java @@ -39,7 +39,7 @@ public class FlyingPathNavigation extends PathNavigation { @Override public Path createPath(Entity entity, int distance) { - return this.createPath(entity.blockPosition(), distance); + return this.createPath(entity.blockPosition(), entity, distance); // Paper - EntityPathfindEvent } @Override diff --git a/src/main/java/net/minecraft/world/entity/ai/navigation/GroundPathNavigation.java b/src/main/java/net/minecraft/world/entity/ai/navigation/GroundPathNavigation.java index 90a7940bf8b32cb245e9253d957cb437fa600857..2796df7af365c452b28373adfd7daf1d6730bac5 100644 --- a/src/main/java/net/minecraft/world/entity/ai/navigation/GroundPathNavigation.java +++ b/src/main/java/net/minecraft/world/entity/ai/navigation/GroundPathNavigation.java @@ -41,7 +41,7 @@ public class GroundPathNavigation extends PathNavigation { } @Override - public Path createPath(BlockPos target, int distance) { + public Path createPath(BlockPos target, @javax.annotation.Nullable Entity entity, int distance) { // Paper - EntityPathfindEvent LevelChunk levelChunk = this.level .getChunkSource() .getChunkNow(SectionPos.blockToSectionCoord(target.getX()), SectionPos.blockToSectionCoord(target.getZ())); @@ -56,7 +56,7 @@ public class GroundPathNavigation extends PathNavigation { } if (mutableBlockPos.getY() > this.level.getMinY()) { - return super.createPath(mutableBlockPos.above(), distance); + return super.createPath(mutableBlockPos.above(), entity, distance); // Paper - EntityPathfindEvent } mutableBlockPos.setY(target.getY() + 1); @@ -69,7 +69,7 @@ public class GroundPathNavigation extends PathNavigation { } if (!levelChunk.getBlockState(target).isSolid()) { - return super.createPath(target, distance); + return super.createPath(target, entity, distance); // Paper - EntityPathfindEvent } else { BlockPos.MutableBlockPos mutableBlockPos2 = target.mutable().move(Direction.UP); @@ -77,14 +77,14 @@ public class GroundPathNavigation extends PathNavigation { mutableBlockPos2.move(Direction.UP); } - return super.createPath(mutableBlockPos2.immutable(), distance); + return super.createPath(mutableBlockPos2.immutable(), entity, distance); // Paper - EntityPathfindEvent } } } @Override public Path createPath(Entity entity, int distance) { - return this.createPath(entity.blockPosition(), distance); + return this.createPath(entity.blockPosition(), entity, distance); // Paper - EntityPathfindEvent } private int getSurfaceY() { diff --git a/src/main/java/net/minecraft/world/entity/ai/navigation/PathNavigation.java b/src/main/java/net/minecraft/world/entity/ai/navigation/PathNavigation.java index 7d3cb358fe543253e988531df3434ae1274814d3..1d5ce4caf99a3fb376b350968a6bd1ac8471ffec 100644 --- a/src/main/java/net/minecraft/world/entity/ai/navigation/PathNavigation.java +++ b/src/main/java/net/minecraft/world/entity/ai/navigation/PathNavigation.java @@ -125,7 +125,13 @@ public abstract class PathNavigation { @Nullable public Path createPath(BlockPos target, int distance) { - return this.createPath(ImmutableSet.of(target), 8, false, distance); + // Paper start - EntityPathfindEvent + return this.createPath(target, null, distance); + } + @Nullable + public Path createPath(BlockPos target, @Nullable Entity entity, int distance) { + return this.createPath(ImmutableSet.of(target), entity, 8, false, distance); + // Paper end - EntityPathfindEvent } @Nullable @@ -135,7 +141,7 @@ public abstract class PathNavigation { @Nullable public Path createPath(Entity entity, int distance) { - return this.createPath(ImmutableSet.of(entity.blockPosition()), 16, true, distance); + return this.createPath(ImmutableSet.of(entity.blockPosition()), entity, 16, true, distance); // Paper - EntityPathfindEvent } @Nullable @@ -145,6 +151,17 @@ public abstract class PathNavigation { @Nullable protected Path createPath(Set<BlockPos> positions, int range, boolean useHeadPos, int distance, float followRange) { + // Paper start - EntityPathfindEvent + return this.createPath(positions, null, range, useHeadPos, distance, followRange); + } + + @Nullable + protected Path createPath(Set<BlockPos> positions, @Nullable Entity target, int range, boolean useHeadPos, int distance) { + return this.createPath(positions, target, range, useHeadPos, distance, (float) this.mob.getAttributeValue(Attributes.FOLLOW_RANGE)); + } + + @Nullable protected Path createPath(Set<BlockPos> positions, @Nullable Entity target, int range, boolean useHeadPos, int distance, float followRange) { + // Paper end - EntityPathfindEvent if (positions.isEmpty()) { return null; } else if (this.mob.getY() < (double)this.level.getMinY()) { @@ -154,6 +171,23 @@ public abstract class PathNavigation { } else if (this.path != null && !this.path.isDone() && positions.contains(this.targetPos)) { return this.path; } else { + // Paper start - EntityPathfindEvent + boolean copiedSet = false; + for (BlockPos possibleTarget : positions) { + if (!new com.destroystokyo.paper.event.entity.EntityPathfindEvent(this.mob.getBukkitEntity(), + io.papermc.paper.util.MCUtil.toLocation(this.mob.level(), possibleTarget), target == null ? null : target.getBukkitEntity()).callEvent()) { + if (!copiedSet) { + copiedSet = true; + positions = new java.util.HashSet<>(positions); + } + // note: since we copy the set this remove call is safe, since we're iterating over the old copy + positions.remove(possibleTarget); + if (positions.isEmpty()) { + return null; + } + } + } + // Paper end - EntityPathfindEvent ProfilerFiller profilerFiller = Profiler.get(); profilerFiller.push("pathfind"); BlockPos blockPos = useHeadPos ? this.mob.blockPosition().above() : this.mob.blockPosition(); diff --git a/src/main/java/net/minecraft/world/entity/ai/navigation/WallClimberNavigation.java b/src/main/java/net/minecraft/world/entity/ai/navigation/WallClimberNavigation.java index 1a1bc30b425858d82dbfb84b4a94d7793cab7125..5bbfa43d1e97970f035fcb101c3252c01ffead0d 100644 --- a/src/main/java/net/minecraft/world/entity/ai/navigation/WallClimberNavigation.java +++ b/src/main/java/net/minecraft/world/entity/ai/navigation/WallClimberNavigation.java @@ -16,9 +16,9 @@ public class WallClimberNavigation extends GroundPathNavigation { } @Override - public Path createPath(BlockPos target, int distance) { + public Path createPath(BlockPos target, @Nullable Entity entity, int distance) { // Paper - EntityPathfindEvent this.pathToPosition = target; - return super.createPath(target, distance); + return super.createPath(target, entity, distance); // Paper - EntityPathfindEvent } @Override
412
0.536892
1
0.536892
game-dev
MEDIA
0.946845
game-dev
0.81075
1
0.81075
Esteemed-Innovation/Esteemed-Innovation
2,319
src/main/java/eiteam/esteemedinnovation/tools/steam/upgrades/ItemInternalProcessingUnitUpgrade.java
package eiteam.esteemedinnovation.tools.steam.upgrades; import eiteam.esteemedinnovation.api.SmasherRegistry; import eiteam.esteemedinnovation.api.SteamChargable; import eiteam.esteemedinnovation.api.tool.SteamToolSlot; import eiteam.esteemedinnovation.commons.util.OreDictHelper; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.event.entity.player.PlayerEvent; import net.minecraftforge.event.world.BlockEvent; import org.apache.commons.lang3.tuple.Pair; import javax.annotation.Nonnull; import java.util.List; import static eiteam.esteemedinnovation.tools.ToolsModule.upgradeResource; public class ItemInternalProcessingUnitUpgrade extends ItemSteamToolUpgrade { public ItemInternalProcessingUnitUpgrade() { super(SteamToolSlot.DRILL_CORE, upgradeResource("processor"), null, 0); } @Override public void onPlayerHarvestDropsWithTool(BlockEvent.HarvestDropsEvent event, @Nonnull ItemStack toolStack, @Nonnull ItemStack thisUpgradeStack) { World world = event.getWorld(); IBlockState state = event.getState(); Block block = state.getBlock(); Item blockItem = Item.getItemFromBlock(block); int meta = block.getMetaFromState(state); if (OreDictHelper.cobblestones.contains(Pair.of(blockItem, meta))) { return; } SteamChargable drill = (SteamChargable) toolStack.getItem(); List<ItemStack> out = SmasherRegistry.getOutput(new ItemStack(block, 1, meta), world); if (!out.isEmpty()) { for (int i = 0; i < event.getDrops().size(); i++) { ItemStack drop = event.getDrops().get(i); if (drop.getItem() == blockItem && drop.getItemDamage() == meta) { event.getDrops().remove(i); } } event.getDrops().addAll(out); drill.addSteam(toolStack, -(2 * drill.steamPerDurability()), event.getHarvester()); } } @Override public void onUpdateBreakSpeedWithTool(PlayerEvent.BreakSpeed event, @Nonnull ItemStack toolStack, @Nonnull ItemStack thisUpgradeStack) { event.setNewSpeed(event.getNewSpeed() / 2); } }
412
0.88595
1
0.88595
game-dev
MEDIA
0.99725
game-dev
0.945022
1
0.945022
microsoft/MRDL_Unity_PeriodicTable
11,262
Assets/MRTK/Tests/EditModeTests/Tools/MigrationToolTests.cs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.UI.BoundsControl; using Microsoft.MixedReality.Toolkit.Utilities; using Microsoft.MixedReality.Toolkit.UI; using NUnit.Framework; using System; using System.Collections.Generic; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.SceneManagement; using Object = UnityEngine.Object; namespace Microsoft.MixedReality.Toolkit.Tests.EditMode { public class MigrationToolTests { private readonly MigrationTool migrationTool = new MigrationTool(); private readonly HashSet<string> assetsForDeletion = new HashSet<string>(); private readonly string scenePath = "Assets/_migration.unity"; private readonly string prefabPath = "Assets/_migration.prefab"; private struct MigrationTypes { public Type oldType; public Type newType; public Type handler; public MigrationTypes(Type oldT, Type newT, Type mHandler) { oldType = oldT; newType = newT; handler = mHandler; } } private List<MigrationTypes> migrationList = new List<MigrationTypes>(); [SetUp] public void Setup() { migrationList.Add(new MigrationTypes(typeof(ManipulationHandler), typeof(ObjectManipulator), typeof(ObjectManipulatorMigrationHandler))); migrationList.Add(new MigrationTypes(typeof(BoundingBox), typeof(BoundsControl), typeof(BoundsControlMigrationHandler))); } /// <summary> /// Deletes all assets created during tests /// </summary> [TearDown] public void TearDown() { foreach (var assetPath in assetsForDeletion) { if (AssetDatabase.LoadMainAssetAtPath(assetPath)) { AssetDatabase.DeleteAsset(assetPath); } } AssetDatabase.Refresh(); } /// <summary> /// Tests that the Button Migration tool works properly /// </summary> [Test] public void ButtonMigrationTest() { Type migrationHandlerType = typeof(ButtonConfigHelperMigrationHandler); Material testMat = AssetDatabase.LoadAssetAtPath<Material>("Assets/MRTK/SDK/Features/UX/Interactable/Materials/HolographicButtonIconHome.mat"); Material testDefaultMat = AssetDatabase.LoadAssetAtPath<Material>("Assets/MRTK/SDK/Features/UX/Interactable/Materials/HolographicButtonIconStar.mat"); GameObject buttonGameObject = SetUpGameObjectWithComponentOfType(typeof(ButtonConfigHelper)); GameObject buttonQuad = GameObject.CreatePrimitive(PrimitiveType.Quad); buttonQuad.transform.parent = buttonGameObject.transform; MeshRenderer quadRenderer = buttonQuad.GetComponent<MeshRenderer>(); quadRenderer.sharedMaterial = testMat; ButtonConfigHelper buttonConfig = buttonGameObject.GetComponent<ButtonConfigHelper>(); ButtonIconSet testIconSet = new ButtonIconSet(); buttonConfig.IconStyle = ButtonIconStyle.Quad; buttonConfig.IconSet = testIconSet; buttonConfig.EditorSetDefaultIconSet(testIconSet); buttonConfig.EditorSetIconQuadRenderer(quadRenderer); buttonConfig.EditorSetDefaultQuadMaterial(testDefaultMat); migrationTool.TryAddObjectForMigration(migrationHandlerType, buttonGameObject); string testCustomIconSetFolder = System.IO.Path.Combine("Assets", "MixedRealityToolkit.Generated.Test"); AssetDatabase.DeleteAsset(testCustomIconSetFolder); AssetDatabase.CreateFolder("Assets", "MixedRealityToolkit.Generated.Test"); buttonConfig.EditorUpgradeCustomIcon(null, testCustomIconSetFolder, true); AssetDatabase.Refresh(); ButtonIconSet generatedIconSet = AssetDatabase.LoadAssetAtPath<ButtonIconSet>(System.IO.Path.Combine("Assets", "MixedRealityToolkit.Generated.Test", "CustomIconSets", "CustomIconSet.asset")); Assert.IsNotNull(generatedIconSet); Assert.IsTrue(generatedIconSet.QuadIcons.Length == 1); AssetDatabase.DeleteAsset(testCustomIconSetFolder); } /// <summary> /// Checks if MigrationTool can process migration on a game object containing a deprecated component with a compatible migration handler. /// </summary> [Test] public void GameObjectCanBeMigrated() { foreach (var entry in migrationList) { Type oldType = entry.oldType; Type newType = entry.newType; Type migrationHandlerType = entry.handler; GameObject gameObject = SetUpGameObjectWithComponentOfType(oldType); migrationTool.TryAddObjectForMigration(migrationHandlerType, gameObject); migrationTool.MigrateSelection(migrationHandlerType, false); Assert.IsNull(gameObject.GetComponent(oldType), $"Migrated Component of type {oldType.Name} could not be removed"); Assert.IsNotNull(gameObject.GetComponent(newType), $"Migrated Component of type {newType.Name} could not be added"); Object.DestroyImmediate(gameObject); } } /// <summary> /// Checks if MigrationTool can process migration on a prefab containing a deprecated component with a compatible migration handler. /// </summary> [Test] public void PrefabCanBeMigrated() { foreach (var entry in migrationList) { Type oldType = entry.oldType; Type newType = entry.newType; Type migrationHandlerType = entry.handler; GameObject gameObject = SetUpGameObjectWithComponentOfType(oldType); PrefabUtility.SaveAsPrefabAsset(gameObject, prefabPath); assetsForDeletion.Add(prefabPath); migrationTool.TryAddObjectForMigration(migrationHandlerType, AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject))); migrationTool.MigrateSelection(migrationHandlerType, false); GameObject prefabGameObject = PrefabUtility.LoadPrefabContents(prefabPath); Assert.IsNull(prefabGameObject.GetComponent(oldType), $"Migrated Component of type {oldType.Name} could not be removed"); Assert.IsNotNull(prefabGameObject.GetComponent(newType), $"Migrated Component of type {newType.Name} could not be added"); Object.DestroyImmediate(gameObject); } } /// <summary> /// Checks if MigrationTool can process migration on a scene root game object that contains a deprecated component with a compatible migration handler. /// </summary> [Test] public void SceneCanBeMigrated() { foreach (var entry in migrationList) { Type oldType = entry.oldType; Type newType = entry.newType; Type migrationHandlerType = entry.handler; Scene scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); GameObject gameObject = SetUpGameObjectWithComponentOfType(oldType); EditorSceneManager.SaveScene(scene, scenePath); assetsForDeletion.Add(scenePath); migrationTool.TryAddObjectForMigration(migrationHandlerType, AssetDatabase.LoadAssetAtPath(scenePath, typeof(SceneAsset))); migrationTool.MigrateSelection(migrationHandlerType, false); var openScene = EditorSceneManager.OpenScene(scenePath); foreach (var sceneGameObject in openScene.GetRootGameObjects()) { Assert.IsNull(sceneGameObject.GetComponent(oldType), $"Migrated component of type {oldType.Name} could not be removed"); Assert.IsNotNull(sceneGameObject.GetComponent(newType), $"Migrated component of type {newType.Name} could not be added"); Object.DestroyImmediate(sceneGameObject); } Object.DestroyImmediate(gameObject); } } /// <summary> /// Checks if MigrationTool can process migration on a inactive scene root game object that contains an inactive deprecated component with a compatible migration handler. /// Active state of both game object and component must be kept. /// </summary> [Test] public void MigrationKeepObjectAndComponentActiveState() { foreach (var entry in migrationList) { Type oldType = entry.oldType; Type newType = entry.newType; Type migrationHandlerType = entry.handler; Scene scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); GameObject gameObject = SetUpGameObjectWithComponentOfType(oldType); MonoBehaviour oldTypeComponent = (MonoBehaviour)gameObject.GetComponent(oldType); oldTypeComponent.enabled = false; gameObject.SetActive(false); EditorSceneManager.SaveScene(scene, scenePath); assetsForDeletion.Add(scenePath); migrationTool.TryAddObjectForMigration(migrationHandlerType, AssetDatabase.LoadAssetAtPath(scenePath, typeof(SceneAsset))); migrationTool.MigrateSelection(migrationHandlerType, false); var openScene = EditorSceneManager.OpenScene(scenePath); foreach (var sceneGameObject in openScene.GetRootGameObjects()) { Assert.IsNull(sceneGameObject.GetComponent(oldType), $"Migrated component of type {oldType.Name} could not be removed"); Assert.IsNotNull(sceneGameObject.GetComponent(newType), $"Migrated component of type {newType.Name} could not be added"); // Active state of game object and component is kept Assert.IsFalse(sceneGameObject.activeSelf, $"Active state of migrated game object was not kept during migration with type {migrationHandlerType.Name}"); Assert.IsFalse(((MonoBehaviour)sceneGameObject.GetComponent(newType)).enabled, $"Active state of migrated component was not kept during migration with type { migrationHandlerType.Name}"); Object.DestroyImmediate(sceneGameObject); } Object.DestroyImmediate(gameObject); } } private static GameObject SetUpGameObjectWithComponentOfType(Type type) { GameObject go = new GameObject(); if (typeof(Component).IsAssignableFrom(type)) { go.AddComponent(type); } Assert.IsNotNull(go.GetComponent(type), $"Component of type {type.Name} could not be added to GameObject"); return go; } } }
412
0.9239
1
0.9239
game-dev
MEDIA
0.919143
game-dev
0.951171
1
0.951171
PowerNukkitX/PowerNukkitX
1,780
src/main/java/cn/nukkit/entity/ai/executor/WardenSniffExecutor.java
package cn.nukkit.entity.ai.executor; import cn.nukkit.entity.EntityIntelligent; import cn.nukkit.entity.data.EntityFlag; import cn.nukkit.entity.mob.EntityWarden; import cn.nukkit.level.Sound; public class WardenSniffExecutor implements IBehaviorExecutor { protected int angerAddition; protected int duration;//gt protected int endTime; public WardenSniffExecutor(int duration, int angerAddition) { this.duration = duration; this.angerAddition = angerAddition; } @Override public boolean execute(EntityIntelligent entity) { if (entity.getLevel().getTick() >= this.endTime) { sniff(entity); return false; } else { return true; } } @Override public void onStart(EntityIntelligent entity) { this.endTime = entity.getLevel().getTick() + this.duration; entity.setDataFlag(EntityFlag.SNIFFING, true); entity.setDataFlagExtend(EntityFlag.SNIFFING, true); entity.level.addSound(entity.clone(), Sound.MOB_WARDEN_SNIFF); } @Override public void onStop(EntityIntelligent entity) { entity.setDataFlag(EntityFlag.SNIFFING, false); entity.setDataFlagExtend(EntityFlag.SNIFFING, false); } @Override public void onInterrupt(EntityIntelligent entity) { entity.setDataFlag(EntityFlag.SNIFFING, false); entity.setDataFlagExtend(EntityFlag.SNIFFING, false); } protected void sniff(EntityIntelligent entity) { if (!(entity instanceof EntityWarden warden)) return; for (var other : entity.level.getEntities()) { if (!warden.isValidAngerEntity(other, true)) continue; warden.addEntityAngerValue(other, this.angerAddition); } } }
412
0.835607
1
0.835607
game-dev
MEDIA
0.97107
game-dev
0.869612
1
0.869612
cybergarage/cybergarage-upnp
2,898
core/src/main/java/org/cybergarage/upnp/control/QueryRequest.java
/****************************************************************** * * CyberUPnP for Java * * Copyright (C) Satoshi Konno 2002 * * File: QueryRequest.java * * Revision; * * 01/29/03 * - first revision. * 09/02/03 * - Giordano Sassaroli <sassarol@cefriel.it> * - Error : redundant code, the setRequest method in QueryRequest invokes setURI even if after a couple of rows setRequestHost is invoked * ******************************************************************/ package org.cybergarage.upnp.control; import org.cybergarage.http.*; import org.cybergarage.xml.*; import org.cybergarage.soap.*; import org.cybergarage.upnp.*; public class QueryRequest extends ControlRequest { //////////////////////////////////////////////// // Constructor //////////////////////////////////////////////// public QueryRequest() {} public QueryRequest(HTTPRequest httpReq) { set(httpReq); } //////////////////////////////////////////////// // Qyery //////////////////////////////////////////////// private Node getVarNameNode() { Node bodyNode = getBodyNode(); if (bodyNode == null) return null; if (bodyNode.hasNodes() == false) return null; Node queryStateVarNode = bodyNode.getNode(0); if (queryStateVarNode == null) return null; if (queryStateVarNode.hasNodes() == false) return null; return queryStateVarNode.getNode(0); } public String getVarName() { Node node = getVarNameNode(); if (node == null) return ""; return node.getValue(); } //////////////////////////////////////////////// // setRequest //////////////////////////////////////////////// public void setRequest(StateVariable stateVar) { Service service = stateVar.getService(); String ctrlURL = service.getControlURL(); setRequestHost(service); setEnvelopeNode(SOAP.createEnvelopeBodyNode()); Node envNode = getEnvelopeNode(); Node bodyNode = getBodyNode(); Node qeuryNode = createContentNode(stateVar); bodyNode.addNode(qeuryNode); setContent(envNode); setSOAPAction(Control.QUERY_SOAPACTION); } //////////////////////////////////////////////// // Contents //////////////////////////////////////////////// private Node createContentNode(StateVariable stateVar) { Node queryVarNode = new Node(); queryVarNode.setName(Control.NS, Control.QUERY_STATE_VARIABLE); queryVarNode.setNameSpace(Control.NS, Control.XMLNS); Node varNode = new Node(); varNode.setName(Control.NS, Control.VAR_NAME); varNode.setValue(stateVar.getName()); queryVarNode.addNode(varNode); return queryVarNode; } //////////////////////////////////////////////// // post //////////////////////////////////////////////// public QueryResponse post() { SOAPResponse soapRes = postMessage(getRequestHost(), getRequestPort()); return new QueryResponse(soapRes); } }
412
0.813827
1
0.813827
game-dev
MEDIA
0.373362
game-dev
0.782318
1
0.782318
MaximumADHD/Roblox-Client-Tracker
3,010
scripts/CoreScripts/Modules/Settings/Components/RecordingIndicator.lua
local CorePackages = game:GetService("CorePackages") local RunService = game:GetService("RunService") local Roact = require(CorePackages.Packages.Roact) local Otter = require(CorePackages.Packages.Otter) local t = require(CorePackages.Packages.t) local AppFonts = require(CorePackages.Workspace.Packages.Style).AppFonts local RobloxTranslator = require(CorePackages.Workspace.Packages.RobloxTranslator) local SPRING_PARAMS = { frequency = 4, dampingRatio = 1, } local MicOn = RobloxTranslator:FormatByKey("InGame.CommonUI.Label.MicOnRecording") local MicOff = RobloxTranslator:FormatByKey("InGame.CommonUI.Label.MicOff") local VOICE_RECORDING_INDICATOR_FADE_TIME = 5 local RENDER_STEP_NAME = "RoactVoiceRecordingIndicator" local RecordingIndicator = Roact.PureComponent:extend("PermissionsButtons") RecordingIndicator.validateProps = t.strictInterface({ micOn = t.boolean, isSmallTouchScreen = t.optional(t.boolean), }) function RecordingIndicator:init() self:setState({ lastVoiceRecordingIndicatorTextUpdated = tick(), voiceRecordingIndicatorTextMotor = Otter.createSingleMotor(1), textOpacity = 1, }) end function RecordingIndicator:didMount() task.spawn(function() self.state.voiceRecordingIndicatorTextMotor:onStep(function(value) self:setState({ textOpacity = value, }) end) RunService:BindToRenderStep(RENDER_STEP_NAME, Enum.RenderPriority.Last.Value, function() local timeDiff = tick() - self.state.lastVoiceRecordingIndicatorTextUpdated if timeDiff >= VOICE_RECORDING_INDICATOR_FADE_TIME and not self.props.micOn and self.state.textOpacity >= 1 then self.state.voiceRecordingIndicatorTextMotor:setGoal(Otter.spring(0, SPRING_PARAMS)) self.state.voiceRecordingIndicatorTextMotor:start() end end) end) end function RecordingIndicator:willUnmount() self.state.voiceRecordingIndicatorTextMotor:destroy() RunService:UnbindFromRenderStep(RENDER_STEP_NAME) end function RecordingIndicator:shouldUpdate(nextProps, nextState) if self.props.micOn ~= nextProps.micOn then self:setState({ lastVoiceRecordingIndicatorTextUpdated = tick(), }) if nextProps.micOn then self.state.voiceRecordingIndicatorTextMotor:setGoal(Otter.spring(1, SPRING_PARAMS)) self.state.voiceRecordingIndicatorTextMotor:start() end end return self.props.micOn ~= nextProps.micOn or self.state.textOpacity ~= nextState.textOpacity end function RecordingIndicator:render() return Roact.createElement("TextLabel", { Text = if self.props.micOn then MicOn else MicOff, AutomaticSize = Enum.AutomaticSize.XY, Visible = self.props.hasMicPermissions, TextSize = if self.props.isSmallTouchScreen then 10 else 12, Font = AppFonts.default:getMedium(), TextXAlignment = Enum.TextXAlignment.Left, TextYAlignment = Enum.TextYAlignment.Center, TextColor3 = Color3.fromRGB(255, 255, 255), TextTransparency = 1 - self.state.textOpacity, BackgroundTransparency = 1, LayoutOrder = 6, TextWrapped = true, }) end return RecordingIndicator
412
0.884821
1
0.884821
game-dev
MEDIA
0.911025
game-dev
0.972875
1
0.972875
meetric1/gmod-infinite-map
16,767
lua/infmap/sv_inf_detours.lua
// metatable fuckery local EntityMT = FindMetaTable("Entity") local VehicleMT = FindMetaTable("Vehicle") local PhysObjMT = FindMetaTable("PhysObj") local PlayerMT = FindMetaTable("Player") local NextBotMT = FindMetaTable("NextBot") local CLuaLocomotionMT = FindMetaTable("CLuaLocomotion") local CTakeDamageInfoMT = FindMetaTable("CTakeDamageInfo") /*********** Entity Metatable *************/ EntityMT.InfMap_GetPos = EntityMT.InfMap_GetPos or EntityMT.GetPos function EntityMT:GetPos() return InfMap.unlocalize_vector(self:InfMap_GetPos(), self.CHUNK_OFFSET) end EntityMT.InfMap_WorldSpaceCenter = EntityMT.InfMap_WorldSpaceCenter or EntityMT.WorldSpaceCenter function EntityMT:WorldSpaceCenter() return InfMap.unlocalize_vector(self:InfMap_WorldSpaceCenter(), self.CHUNK_OFFSET) end EntityMT.InfMap_WorldSpaceAABB = EntityMT.InfMap_WorldSpaceAABB or EntityMT.WorldSpaceAABB function EntityMT:WorldSpaceAABB() local v1, v2 = self:InfMap_WorldSpaceAABB() return InfMap.unlocalize_vector(v1, self.CHUNK_OFFSET), InfMap.unlocalize_vector(v2, self.CHUNK_OFFSET) end EntityMT.InfMap_SetPos = EntityMT.InfMap_SetPos or EntityMT.SetPos function EntityMT:SetPos(pos) local chunk_pos, chunk_offset = InfMap.localize_vector(pos) if chunk_offset != self.CHUNK_OFFSET then InfMap.prop_update_chunk(self, chunk_offset) end return self:InfMap_SetPos(chunk_pos) end EntityMT.InfMap_LocalToWorld = EntityMT.InfMap_LocalToWorld or EntityMT.LocalToWorld function EntityMT:LocalToWorld(pos) return InfMap.unlocalize_vector(self:InfMap_LocalToWorld(pos), self.CHUNK_OFFSET) end EntityMT.InfMap_WorldToLocal = EntityMT.InfMap_WorldToLocal or EntityMT.WorldToLocal function EntityMT:WorldToLocal(pos) return self:InfMap_WorldToLocal(-InfMap.unlocalize_vector(-pos, self.CHUNK_OFFSET)) end EntityMT.InfMap_EyePos = EntityMT.InfMap_EyePos or EntityMT.EyePos function EntityMT:EyePos() return InfMap.unlocalize_vector(self:InfMap_EyePos(), self.CHUNK_OFFSET) end EntityMT.InfMap_NearestPoint = EntityMT.InfMap_NearestPoint or EntityMT.NearestPoint function EntityMT:NearestPoint(pos) local chunk_pos, chunk_offset = InfMap.localize_vector(pos) return InfMap.unlocalize_vector(self:InfMap_NearestPoint(chunk_pos), chunk_offset) end EntityMT.InfMap_GetAttachment = EntityMT.InfMap_GetAttachment or EntityMT.GetAttachment function EntityMT:GetAttachment(num) local data = self:InfMap_GetAttachment(num) if !data or !data.Pos then return data end data.Pos = InfMap.unlocalize_vector(data.Pos, self.CHUNK_OFFSET) return data end EntityMT.InfMap_GetBonePosition = EntityMT.InfMap_GetBonePosition or EntityMT.GetBonePosition function EntityMT:GetBonePosition(index) local pos, ang = self:InfMap_GetBonePosition(index) pos = InfMap.unlocalize_vector(pos, self.CHUNK_OFFSET) return pos, ang end // get setentity data since theres no GetEntity EntityMT.InfMap_SetEntity = EntityMT.InfMap_SetEntity or EntityMT.SetEntity function EntityMT:SetEntity(str, ent) self.SET_ENTITIES = self.SET_ENTITIES or {} self.SET_ENTITIES[str] = ent self:InfMap_SetEntity(str, ent) end local function unfuck_keyvalue(self, value) if !self:GetKeyValues()[value] then return end self:SetKeyValue(value, tostring(InfMap.unlocalize_vector(Vector(self:GetKeyValues()[value]), -self.CHUNK_OFFSET))) end EntityMT.InfMap_Spawn = EntityMT.InfMap_Spawn or EntityMT.Spawn function EntityMT:Spawn() if IsValid(self) and (self:IsConstraint() or self:GetClass() == "phys_spring" or self:GetClass() == "keyframe_rope") then // elastic isnt considered a constraint..? unfuck_keyvalue(self, "attachpoint") unfuck_keyvalue(self, "springaxis") unfuck_keyvalue(self, "slideaxis") unfuck_keyvalue(self, "hingeaxis") unfuck_keyvalue(self, "axis") unfuck_keyvalue(self, "position2") if self.SET_ENTITIES and self.SET_ENTITIES.EndEntity == game.GetWorld() then unfuck_keyvalue(self, "EndOffset") end self:SetPos(self:InfMap_GetPos()) end return self:InfMap_Spawn() end /************ Physics Object Metatable **************/ PhysObjMT.InfMap_GetPos = PhysObjMT.InfMap_GetPos or PhysObjMT.GetPos function PhysObjMT:GetPos() return InfMap.unlocalize_vector(self:InfMap_GetPos(), self:GetEntity().CHUNK_OFFSET) end PhysObjMT.InfMap_SetPos = PhysObjMT.InfMap_SetPos or PhysObjMT.SetPos function PhysObjMT:SetPos(pos, teleport) local chunk_pos, chunk_offset = InfMap.localize_vector(pos) local ent = self:GetEntity() if chunk_offset != ent.CHUNK_OFFSET then InfMap.prop_update_chunk(ent, chunk_offset) end return self:InfMap_SetPos(chunk_pos, teleport) end PhysObjMT.InfMap_ApplyForceOffset = PhysObjMT.InfMap_ApplyForceOffset or PhysObjMT.ApplyForceOffset function PhysObjMT:ApplyForceOffset(impulse, position) return self:InfMap_ApplyForceOffset(impulse, -InfMap.unlocalize_vector(-position, self:GetEntity().CHUNK_OFFSET)) end PhysObjMT.InfMap_LocalToWorld = PhysObjMT.InfMap_LocalToWorld or PhysObjMT.LocalToWorld function PhysObjMT:LocalToWorld(pos) return InfMap.unlocalize_vector(self:InfMap_LocalToWorld(pos), self:GetEntity().CHUNK_OFFSET) end PhysObjMT.InfMap_CalculateVelocityOffset = PhysObjMT.InfMap_CalculateVelocityOffset or PhysObjMT.CalculateVelocityOffset function PhysObjMT:CalculateVelocityOffset(impulse, position) return self:InfMap_CalculateVelocityOffset(impulse, -InfMap.unlocalize_vector(-position, self:GetEntity().CHUNK_OFFSET)) end PhysObjMT.InfMap_WorldToLocal = PhysObjMT.InfMap_WorldToLocal or PhysObjMT.WorldToLocal function PhysObjMT:WorldToLocal(pos) return self:InfMap_WorldToLocal(pos - InfMap.unlocalize_vector(Vector(), self:GetEntity().CHUNK_OFFSET)) end PhysObjMT.InfMap_ApplyForceOffset = PhysObjMT.InfMap_ApplyForceOffset or PhysObjMT.ApplyForceOffset function PhysObjMT:ApplyForceOffset(impulse, pos) return self:InfMap_ApplyForceOffset(impulse, -InfMap.unlocalize_vector(-pos, self:GetEntity().CHUNK_OFFSET)) end PhysObjMT.InfMap_GetVelocityAtPoint = PhysObjMT.InfMap_GetVelocityAtPoint or PhysObjMT.GetVelocityAtPoint function PhysObjMT:GetVelocityAtPoint(pos) return self:InfMap_GetVelocityAtPoint(-InfMap.unlocalize_vector(-pos, self:GetEntity().CHUNK_OFFSET)) end PhysObjMT.InfMap_CalculateForceOffset = PhysObjMT.InfMap_CalculateForceOffset or PhysObjMT.CalculateForceOffset function PhysObjMT:CalculateForceOffset(impulse, pos) return self:InfMap_CalculateForceOffset(impulse, InfMap.localize_vector(pos)) end PhysObjMT.InfMap_SetMaterial = PhysObjMT.InfMap_SetMaterial or PhysObjMT.SetMaterial function PhysObjMT:SetMaterial(mat) // if a mat is set it will seperate qphysics and vphysics on terrain entities, disable it if IsValid(self:GetEntity()) and !InfMap.disable_pickup[self:GetEntity():GetClass()] then return self:InfMap_SetMaterial(mat) end end /*************** Vehicle Metatable *****************/ // these 3 functions cause stack overflow since vehicle is dirived from the entity metatable //VehicleMT.InfMap_GetPos = VehicleMT.InfMap_GetPos or VehicleMT.GetPos //function VehicleMT:GetPos() // return InfMap.unlocalize_vector(self:InfMap_GetPos(), self.CHUNK_OFFSET) //end //VehicleMT.InfMap_LocalToWorld = VehicleMT.InfMap_LocalToWorld or VehicleMT.LocalToWorld //function VehicleMT:LocalToWorld(pos) // return InfMap.unlocalize_vector(self:InfMap_LocalToWorld(pos), self.CHUNK_OFFSET) //end // //VehicleMT.InfMap_WorldToLocal = VehicleMT.InfMap_WorldToLocal or VehicleMT.WorldToLocal //function VehicleMT:WorldToLocal(pos) // return self:InfMap_WorldToLocal(pos - InfMap.unlocalize_vector(Vector(), self.CHUNK_OFFSET)) //end // im unsure why this is the only exception VehicleMT.InfMap_SetPos = VehicleMT.InfMap_SetPos or VehicleMT.SetPos function VehicleMT:SetPos(pos) local chunk_pos, chunk_offset = InfMap.localize_vector(pos) if chunk_offset != self.CHUNK_OFFSET then InfMap.prop_update_chunk(self, chunk_offset) end return self:InfMap_SetPos(chunk_pos) end /**************** CTakeDamageInfo Metatable *****************/ CTakeDamageInfoMT.InfMap_GetDamagePosition = CTakeDamageInfoMT.InfMap_GetDamagePosition or CTakeDamageInfoMT.GetDamagePosition function CTakeDamageInfoMT:GetDamagePosition() local inflictor = self:GetInflictor() if !IsValid(inflictor) then inflictor = game.GetWorld() end return InfMap.unlocalize_vector(self:InfMap_GetDamagePosition(), inflictor.CHUNK_OFFSET) end /**************** Player Metatable *****************/ PlayerMT.InfMap_GetShootPos = PlayerMT.InfMap_GetShootPos or PlayerMT.GetShootPos function PlayerMT:GetShootPos() return InfMap.unlocalize_vector(self:InfMap_GetShootPos(), self.CHUNK_OFFSET) end /**************** NextBot Metatable *****************/ NextBotMT.InfMap_GetRangeSquaredTo = NextBotMT.InfMap_GetRangeSquaredTo or NextBotMT.GetRangeSquaredTo function NextBotMT:GetRangeSquaredTo(to) if isentity(to) then to = to:GetPos() end return self:GetPos():DistToSqr(to) end NextBotMT.InfMap_GetRangeTo = NextBotMT.InfMap_GetRangeTo or NextBotMT.GetRangeTo function NextBotMT:GetRangeTo(to) return math.sqrt(self:GetRangeSquaredTo(to)) end /*************** CLuaLocomotion Metatable *****************/ CLuaLocomotionMT.InfMap_Approach = CLuaLocomotionMT.InfMap_Approach or CLuaLocomotionMT.Approach function CLuaLocomotionMT:Approach(goal, goalweight) local nb = self:GetNextBot() local dir = (goal - nb:GetPos()):GetNormalized() local pos = InfMap.localize_vector(nb:GetPos() + dir) return CLuaLocomotionMT.InfMap_Approach(self, pos, goalweight) end CLuaLocomotionMT.InfMap_FaceTowards = CLuaLocomotionMT.InfMap_FaceTowards or CLuaLocomotionMT.FaceTowards function CLuaLocomotionMT:FaceTowards(goal) local nb = self:GetNextBot() local dir = (goal - nb:GetPos()):GetNormalized() local pos = InfMap.localize_vector(nb:GetPos() + dir) return CLuaLocomotionMT.InfMap_FaceTowards(self, pos) end /**************** Other Functions ********************/ // infinite map.. nothing can be outside the world! function util.IsInWorld(pos) return true end // faster lookup local istable = istable local IsEntity = IsEntity local function modify_trace_data(orig_data, trace_func, extra) local data = {} for k, v in pairs(orig_data) do data[k] = v end // #1 localize start and end position of trace local start_pos, start_offset = InfMap.localize_vector(data.start) data.start = start_pos data.endpos = data.endpos - InfMap.unlocalize_vector(Vector(), start_offset) // #2 create filter and only hit entities in your chunk local old_filter = data.filter if !old_filter then data.filter = function(e) return e.CHUNK_OFFSET == start_offset end elseif IsEntity(old_filter) then // rip efficiency data.filter = function(e) return e.CHUNK_OFFSET == start_offset and e != old_filter end elseif istable(old_filter) then data.filter = function(e) for i = 1, #old_filter do if e == old_filter[i] then return false end end return e.CHUNK_OFFSET == start_offset end else // must be function data.filter = function(e) return old_filter(e) and e.CHUNK_OFFSET == start_offset end end // #3, unlocalize hit positions to designated chunks local hit_data = trace_func(data, extra) hit_data.HitPos = InfMap.unlocalize_vector(hit_data.HitPos, start_offset) hit_data.StartPos = InfMap.unlocalize_vector(hit_data.StartPos, start_offset) local hit_ent = hit_data.Entity if IsValid(hit_ent) then if hit_ent:GetClass() == "infmap_clone" and hit_data.REFERENCE_DATA then hit_data.Entity = hit_data.REFERENCE_DATA[1] elseif InfMap.disable_pickup[hit_ent:GetClass()] then hit_data.Entity = game.GetWorld() hit_data.HitWorld = true hit_data.NonHitWorld = false // what the fuck garry? hit_data.HitPos = hit_data.HitPos + hit_data.HitNormal // spawning props sometimes clip end end return hit_data end // no need to detour GetEyeTrace or util.GetPlayerTrace as it uses the already detoured functions InfMap.TraceLine = InfMap.TraceLine or util.TraceLine function util.TraceLine(data) return modify_trace_data(data, InfMap.TraceLine) end InfMap.TraceHull = InfMap.TraceHull or util.TraceHull function util.TraceHull(data) return modify_trace_data(data, InfMap.TraceHull) end InfMap.TraceEntity = InfMap.TraceEntity or util.TraceEntity function util.TraceEntity(data, ent) return modify_trace_data(data, InfMap.TraceEntity, ent) end // blast damage is internal to C++, convert to local space InfMap.BlastDamage = InfMap.BlastDamage or util.BlastDamage function util.BlastDamage(inflictor, attacker, damageOrigin, ...) local chunk_pos, chunk_offset = InfMap.localize_vector(damageOrigin) return InfMap.BlastDamage(inflictor, attacker, chunk_pos, ...) end // M: Find functions Courtesy of LiddulBOFH! Thanks bro! // This and below are potentially usable, faster than running FindInBox on a single chunk (provided the entities to search are tracked by chunk updates) InfMap.FindInBox = InfMap.FindInBox or ents.FindInBox function ents.FindInBox(v1, v2) local entlist = ents.GetAll() local results = {} for _, ent in ipairs(entlist) do if ent:WorldSpaceCenter():WithinAABox(v1,v2) then table.insert(results,ent) end end return results end InfMap.FindInSphere = InfMap.FindInSphere or ents.FindInSphere function ents.FindInSphere(pos, radius) local entlist = ents.GetAll() local results = {} local radSqr = radius * radius for k, v in ipairs(entlist) do if v:WorldSpaceCenter():DistToSqr(pos) <= radSqr then table.insert(results,v) end end return results end InfMap.FindInCone = InfMap.FindInCone or ents.FindInCone function ents.FindInCone(pos, normal, radius, angle_cos) // not sure why, but findincone uses a box instead of sphere local entlist = ents.FindInBox(pos - Vector(radius, radius, radius), pos + Vector(radius, radius, radius)) local results = {} for k,v in ipairs(entlist) do local dot = normal:Dot((v:GetPos() - pos):GetNormalized()) if dot >= angle_cos then table.insert(results, v) end end return results end InfMap.ShouldSaveEntity = InfMap.ShouldSaveEntity or gmsave.ShouldSaveEntity function gmsave.ShouldSaveEntity(ent, t) return InfMap.ShouldSaveEntity(ent, t) and !InfMap.disable_pickup[t.classname] end // network serverside particle effects to client InfMap.ParticleEffect = InfMap.ParticleEffect or ParticleEffect function ParticleEffect(name, pos, ang, parent) InfMap.ParticleEffect(name, Vector(0, 0, -math.huge), ang, parent) // cache the particle (this is stupid) // send particle to client after cached timer.Simple(0, function() for _, ply in ipairs(player.GetAll()) do local localpos = InfMap.unlocalize_vector(pos, -ply.CHUNK_OFFSET) //convert world to client local net.Start("infmap_particle", true) net.WriteString(name) net.WriteFloat(localpos[1]) // networking vectors are stupid and have overflow issues net.WriteFloat(localpos[2]) net.WriteFloat(localpos[3]) net.WriteAngle(ang) net.WriteEntity(parent) net.Send(ply) end end) end // wiremod internally clamps setpos, lets unclamp it... hook.Add("Initialize", "infmap_wire_detour", function() if WireLib then // wiremod unclamp function WireLib.clampPos(pos) return Vector(pos) end end if SF then //starfall unclamp function SF.clampPos(pos) return pos end end end) /********** Hooks ***********/ // disable picking up weapons/items in other local function can_pickup(ply, ent) // when spawning, player weapons will be nil for 1 tick, allow pickup in all chunks local co1, co2 = ply.CHUNK_OFFSET, ent.CHUNK_OFFSET if (co1 and co2 and co1 != co2) or InfMap.disable_pickup[ent:GetClass()] then return false end end hook.Add("PlayerCanPickupWeapon", "infmap_entdetour", can_pickup) hook.Add("PlayerCanPickupItem", "infmap_entdetour", can_pickup) hook.Add("GravGunPickupAllowed", "infmap_entdetour", can_pickup) // localize the toolgun beam hook.Add("PreRegisterSWEP", "infmap_toolgundetour", function(SWEP, class) if class == "gmod_tool" then SWEP.InfMap_DoShootEffect = SWEP.InfMap_DoShootEffect or SWEP.DoShootEffect function SWEP:DoShootEffect(hitpos, ...) SWEP.InfMap_DoShootEffect(self, hitpos - InfMap.unlocalize_vector(Vector(), self:GetOwner().CHUNK_OFFSET), ...) end end end) // explosions should not damage things in other chunks hook.Add("EntityTakeDamage", "infmap_explodedetour", function(ply, dmg) if !(dmg:IsExplosionDamage() or dmg:IsDamageType(DMG_BURN)) then return end local dmg_offset = dmg:GetInflictor().CHUNK_OFFSET local ply_offset = ply.CHUNK_OFFSET if dmg_offset and ply_offset and dmg_offset != ply_offset then return true end end) // bullets may be created in world space, translate to local hook.Add("EntityFireBullets", "infmap_bulletdetour", function(ent, bullet) local pos, chunk = InfMap.localize_vector(bullet.Src) if chunk != Vector() then bullet.Src = pos return true end end)
412
0.918961
1
0.918961
game-dev
MEDIA
0.910789
game-dev
0.922089
1
0.922089
bitcoin/bitcoin
2,172
src/test/fuzz/script_ops.cpp
// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <script/script.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <cstdint> #include <string> #include <vector> FUZZ_TARGET(script_ops) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); CScript script_mut = ConsumeScript(fuzzed_data_provider); LIMITED_WHILE(fuzzed_data_provider.remaining_bytes() > 0, 1000000) { CallOneOf( fuzzed_data_provider, [&] { CScript s = ConsumeScript(fuzzed_data_provider); script_mut = std::move(s); }, [&] { const CScript& s = ConsumeScript(fuzzed_data_provider); script_mut = s; }, [&] { script_mut << fuzzed_data_provider.ConsumeIntegral<int64_t>(); }, [&] { script_mut << ConsumeOpcodeType(fuzzed_data_provider); }, [&] { script_mut << ConsumeScriptNum(fuzzed_data_provider); }, [&] { script_mut << ConsumeRandomLengthByteVector(fuzzed_data_provider); }, [&] { script_mut.clear(); }); } const CScript& script = script_mut; (void)script.GetSigOpCount(false); (void)script.GetSigOpCount(true); (void)script.GetSigOpCount(script); (void)script.HasValidOps(); (void)script.IsPayToScriptHash(); (void)script.IsPayToWitnessScriptHash(); (void)script.IsPushOnly(); (void)script.IsUnspendable(); { CScript::const_iterator pc = script.begin(); opcodetype opcode; (void)script.GetOp(pc, opcode); std::vector<uint8_t> data; (void)script.GetOp(pc, opcode, data); (void)script.IsPushOnly(pc); } { int version; std::vector<uint8_t> program; (void)script.IsWitnessProgram(version, program); } }
412
0.558047
1
0.558047
game-dev
MEDIA
0.20466
game-dev
0.517965
1
0.517965
mamontov-cpp/saddy-graphics-engine-2d
3,212
include/pipeline/pipelinedelegate.h
/*! \file pipelinedelegate.h Describes a simple delegate, used to determine common call of pipeline process and tasks */ #pragma once namespace sad { namespace pipeline { /*! Pipeline delegate used to determine call method of pipeline process and tasks */ class Delegate { public: /*! Invokes a delegate */ virtual void call() = 0; /*! Changes object for all method call. Object is casted down to method \param[in] o object for method call */ virtual void changeObject(void * o); /*! A pipeline delegate is a base class for all kinds of delegates */ virtual ~Delegate(); }; /* Determines callable function as null-ary function */ template< typename _Callable > class Function: public Delegate { public: /*! Creates new function delegate \param[in] f a callback */ inline Function(_Callable f) : m_f(f) { } /*! Invokes a delegate */ virtual void call() override { m_f(); } /*! Destroys a function */ virtual ~Function() override { } private: /*! A callable function */ _Callable m_f; }; /*! Defines a method call delegate */ template< typename _Object, typename _Method > class MethodCall: public Delegate { public: /*! Creates new method call \param[in] o an object \param[in] f a method */ inline MethodCall(_Object * o, _Method f) : m_o(o), m_f(f) { } /*! Invokes a delegate */ virtual void call() override { (m_o ->* m_f)(); } /*! Changes object for all method call. Object is casted down to method \param[in] o object for method call */ virtual void changeObject(void * o) override { m_o = static_cast<_Object *>(o); } /*! Destroys a method call */ virtual ~MethodCall() override { } private: /*! An object, which method will be called on */ _Object * m_o; /*! A method, which will be invoked */ _Method m_f; }; /*! Defines a composed method call delegate, which chains two method calls */ template< typename _Object, typename _FirstMethod, typename _SecondMethod > class ComposedMethodCall: public Delegate { public: /*! Creates new composed method call \param[in] o an object \param[in] f a method \param[in] g a second method to be called */ inline ComposedMethodCall(_Object * o, _FirstMethod f, _SecondMethod g) : m_o(o), m_f(f), m_g(g) { } /*! Invokes a delegate */ virtual void call() override { (((m_o ->* m_f)()) ->* m_g)(); } /*! Changes object for all method call. Object is casted down to method \param[in] o object for method call */ virtual void changeObject(void * o) override { m_o = static_cast<_Object *>(o); } /*! Destroys a method call */ virtual ~ComposedMethodCall() override { } private: /*! An object, which method will be called on */ _Object * m_o; /*! A method, which will be invoked */ _FirstMethod m_f; /*! A second applied method */ _SecondMethod m_g; }; } }
412
0.734385
1
0.734385
game-dev
MEDIA
0.324923
game-dev
0.622151
1
0.622151
luoyikun/ThunderFireUXTool-UGUI
2,214
Assets/UXTools/Editor/Tools/UXTools/SettingsEditor/HierarchyManagement/HierarchyManagementSettingEditor.cs
using UnityEditor; using UnityEditorInternal; using UnityEngine; namespace ThunderFireUITool { [CustomEditor(typeof(HierarchyManagementSetting))] public class HierarchyManagementSettingEditor : Editor { //SerializedProperty channelsProperty; //SerializedProperty levelProperty; SerializedProperty tagColorProperty; private ReorderableList reorderableList; private void OnEnable() { //channelsProperty = serializedObject.FindProperty("managementChannelList"); //levelProperty = serializedObject.FindProperty("managementLevelList"); tagColorProperty = serializedObject.FindProperty("tagColors"); reorderableList = new ReorderableList(serializedObject, tagColorProperty, false, true, false, false); reorderableList.drawHeaderCallback = (Rect rect) => { GUI.Label(rect, "TagColors"); }; reorderableList.drawElementCallback = (rect, index, isActive, isFocused) => { DrawTagColor(tagColorProperty, rect, index); }; } private void DrawTagColor(SerializedProperty prop, Rect rect, int index) { var element = prop.GetArrayElementAtIndex(index); EditorGUI.PropertyField(rect, element); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUI.BeginChangeCheck(); //EditorGUILayout.PropertyField(channelsProperty); //EditorGUILayout.PropertyField(levelProperty); reorderableList.DoLayoutList(); if (EditorGUI.EndChangeCheck()) { serializedObject.ApplyModifiedProperties(); HierarchyManagementEvent.SaveSetting(); } //if (GUILayout.Button("Save")) //{ // HierarchyManagementSetting setting = HierarchyManagementEvent.hierarchyManagementSetting; // if (setting != null) // { // JsonAssetManager.SaveAssets(setting); // } //} } } }
412
0.915854
1
0.915854
game-dev
MEDIA
0.61039
game-dev,desktop-app
0.942502
1
0.942502
AllTheMods/ATM-8
6,851
kubejs/server_scripts/postUnify/dust.js
// priority:950 // Written by EnigmaQuip as a post almost unified recipe generation script for missing recipes // Added to by Mitchell52 ServerEvents.recipes(event => { if (global.devLogging) { console.log('Finishing Unifying on Dusts') } let dustCount = { occult: 0, ftbic: 0, immersive: 0 } global.auTags.dusts.forEach(material => { let dust = global.itemFromTag('dusts', material) if (dust.isEmpty()) { console.log(`${material} does not have a dust tag entry`) return } let ingotTag = Ingredient.of(`#forge:ingots/${material}`) let oreTag = Ingredient.of(`#forge:ores/${material}`) let rawTag = Ingredient.of(`#forge:raw_materials/${material}`) // Occultism Crusher if (global.loaded.Occult_Loaded) { let crush = { ingot: false, ore: false, raw: false } event.forEachRecipe({ type: "occultism:crushing" }, recipe => { let recipeJson = recipe.json if (dust.equalsIgnoringCount(Item.of(recipeJson.get('result')))) { let input = recipeJson.get('ingredient') if (ingotTag.test(Ingredient.of(input))) { crush.ingot = true } else if (oreTag.test(Ingredient.of(input))) { crush.ore = true } else if (rawTag.test(Ingredient.of(input))) { crush.raw = true } } }) let recipe = { type: "occultism:crushing", ingredient: {}, result: {}, crushing_time: 200, ignore_crushing_multiplier: true } if (!ingotTag.getFirst().isEmpty() && !crush.ingot) { let ingotRecipe = recipe ingotRecipe.ingredient = ingotTag.toJson() ingotRecipe.result = dust.withCount(1).toJson() event.custom(ingotRecipe).id(`kubejs:occultism/crushing/${material}_dust_from_ingot`) dustCount.occult++ } if (!rawTag.getFirst().isEmpty() && !crush.raw) { let rawRecipe = recipe rawRecipe.ingredient = rawTag.toJson() rawRecipe.result = dust.withCount(2).toJson() rawRecipe.ignore_crushing_multiplier = false event.custom(rawRecipe).id(`kubejs:occultism/crushing/${material}_dust_from_raw_material`) dustCount.occult++ } if (!oreTag.getFirst().isEmpty() && !crush.ore) { let oreRecipe = recipe oreRecipe.ingredient = oreTag.toJson() oreRecipe.result = dust.withCount(2).toJson() oreRecipe.crushing_time = 300 oreRecipe.ignore_crushing_multiplier = false event.custom(oreRecipe).id(`kubejs:occultism/crushing/${material}_dust`) dustCount.occult++ } } // FTBIC Macerating if (global.loaded.FTBIC_Loaded) { let macerate = { ingot: false, ore: false, raw: false, } event.forEachRecipe({ type: 'ftbic:macerating' }, recipe => { let recipeJson = recipe.json recipeJson.get('outputItems').forEach(item => { if (dust.equalsIgnoringCount(Item.of(item))) { recipeJson.get('inputItems').forEach(inputJson => { let input = inputJson.get('ingredient') if (ingotTag.test(Ingredient.of(input))) { macerate.ingot = true } else if (oreTag.test(Ingredient.of(input))) { macerate.ore = true } else if (rawTag.test(Ingredient.of(input))) { macerate.raw = true } }) } }) }) if (!ingotTag.getFirst().isEmpty() && !macerate.ingot) { event.custom({ "type": "ftbic:macerating", "inputItems": [{ count: 1, ingredient: ingotTag.toJson() }], "outputItems": [dust.toJson()] }).id(`kubejs:ftbic/macerating/ingots/${material}_to_dust`) dustCount.ftbic++ } if (!oreTag.getFirst().isEmpty() && !macerate.ore) { event.custom({ "type": "ftbic:macerating", "inputItems": [{ count: 1, ingredient: oreTag.toJson() }], "outputItems": [dust.withCount(2).toJson()] }).id(`kubejs:ftbic/macerating/ores/${material}_to_dust`) dustCount.ftbic++ } if (!rawTag.getFirst().isEmpty() && !macerate.raw) { event.custom({ "type": "ftbic:macerating", "inputItems": [{ count: 1, ingredient: rawTag.toJson() }], "outputItems": [ dust.toJson(), { chance: 0.35, item: dust.id } ] }).id(`kubejs:ftbic/macerating/raw_materials/${material}_to_dust`) dustCount.ftbic++ } } // Immersive Crusher if (global.loaded.IE_Loaded) { let crush = { ingot: false, ore: false, raw: false } event.forEachRecipe({ type: "immersiveengineering:crusher" }, recipe => { let recipeJson = recipe.json if (dust.equalsIgnoringCount(Item.of(recipeJson.get('result')))) { let input = recipeJson.get('ingredient') if (ingotTag.test(Ingredient.of(input))) { crush.ingot = true } else if (oreTag.test(Ingredient.of(input))) { crush.ore = true } else if (rawTag.test(Ingredient.of(input))) { crush.raw = true } } }) let recipe = { type: "immersiveengineering:crusher", energy: {}, input: {}, result: {}, secondaries: [] } if (!ingotTag.getFirst().isEmpty() && !crush.ingot) { let ingotRecipe = recipe ingotRecipe.energy = 3000 ingotRecipe.input = ingotTag.toJson() ingotRecipe.result = dust.withCount(1).toJson() event.custom(ingotRecipe).id(`kubejs:immersiveengineering/crushing/${material}_dust_from_ingot`) dustCount.immersive++ } if (!oreTag.getFirst().isEmpty() && !crush.ore) { let oreRecipe = recipe oreRecipe.energy = 6000 oreRecipe.input = oreTag.toJson() oreRecipe.result = dust.withCount(2).toJson() event.custom(oreRecipe).id(`kubejs:immersiveengineering/crushing/${material}_dust`) dustCount.immersive++ } if (!rawTag.getFirst().isEmpty() && !crush.raw) { let rawRecipe = recipe rawRecipe.energy = 6000 rawRecipe.input = rawTag.toJson() rawRecipe.result = dust.withCount(1).toJson() rawRecipe.secondaries = [{chance: 0.33333334, output: dust.withCount(1).toJson()}] event.custom(rawRecipe).id(`kubejs:immersiveengineering/crushing/${material}_dust_from_raw_material`) dustCount.immersive++ } } }) if (global.devLogging) { console.log(`Added Dust Recipes - FTBIC: ${dustCount.ftbic}, Occultism: ${dustCount.occult}, IE: ${dustCount.immersive},`) // Added Dust Recipes - FTBIC: 60, Occultism: 5 } })
412
0.908983
1
0.908983
game-dev
MEDIA
0.94096
game-dev
0.873225
1
0.873225
earl/llvm-mirror
2,128
test/CodeGen/ARM/load_store_opt_reg_limit.mir
# RUN: llc -mtriple=thumbv7--linux-android -verify-machineinstrs -run-pass=arm-ldst-opt %s -o - | FileCheck %s --check-prefix=CHECK-MERGE #CHECK-MERGE: foo name: foo # CHECK-MERGE: VSTMDIA $r4, 14, $noreg, $d15, $d16, $d17, $d18, $d19, $d20, $d21, $d22, $d23, $d24, $d25, $d26, $d27, $d28, $d29, $d30 # CHECK-MERGE-NEXT: VSTRD $d31, $r4, 32, 14, $noreg :: (store 8) # CHECK-MERGE: VSTMDIA killed $r0, 14, $noreg, $d4, $d5, $d6, $d7, $d8, $d9, $d10, $d11, $d12, $d13, $d14 body: | bb.0: VSTRD $d15, $r4, 0, 14, $noreg :: (store 8) VSTRD $d16, $r4, 2, 14, $noreg :: (store 8) VSTRD $d17, $r4, 4, 14, $noreg :: (store 8) VSTRD $d18, $r4, 6, 14, $noreg :: (store 8) VSTRD $d19, $r4, 8, 14, $noreg :: (store 8) VSTRD $d20, $r4, 10, 14, $noreg :: (store 8) VSTRD $d21, $r4, 12, 14, $noreg :: (store 8) VSTRD $d22, $r4, 14, 14, $noreg :: (store 8) VSTRD $d23, $r4, 16, 14, $noreg :: (store 8) VSTRD $d24, $r4, 18, 14, $noreg :: (store 8) VSTRD $d25, $r4, 20, 14, $noreg :: (store 8) VSTRD $d26, $r4, 22, 14, $noreg :: (store 8) VSTRD $d27, $r4, 24, 14, $noreg :: (store 8) VSTRD $d28, $r4, 26, 14, $noreg :: (store 8) VSTRD $d29, $r4, 28, 14, $noreg :: (store 8) VSTRD $d30, $r4, 30, 14, $noreg :: (store 8) VSTRD $d31, $r4, 32, 14, $noreg :: (store 8) VSTRD $d0, $r4, 34, 14, $noreg :: (store 8) VSTRD $d1, $r4, 36, 14, $noreg :: (store 8) VSTRD $d3, $r4, 38, 14, $noreg :: (store 8) VSTRD $d2, $r4, 40, 14, $noreg :: (store 8) VSTRD $d4, $r4, 42, 14, $noreg :: (store 8) VSTRD $d5, $r4, 44, 14, $noreg :: (store 8) VSTRD $d6, $r4, 46, 14, $noreg :: (store 8) VSTRD $d7, $r4, 48, 14, $noreg :: (store 8) VSTRD $d8, $r4, 50, 14, $noreg :: (store 8) VSTRD $d9, $r4, 52, 14, $noreg :: (store 8) VSTRD $d10, $r4, 54, 14, $noreg :: (store 8) VSTRD $d11, $r4, 56, 14, $noreg :: (store 8) VSTRD $d12, $r4, 58, 14, $noreg :: (store 8) VSTRD $d13, $r4, 60, 14, $noreg :: (store 8) VSTRD $d14, $r4, 62, 14, $noreg :: (store 8)
412
0.599195
1
0.599195
game-dev
MEDIA
0.546549
game-dev
0.574415
1
0.574415
rism-digital/verovio
1,652
include/vrv/cachehorizontallayoutfunctor.h
///////////////////////////////////////////////////////////////////////////// // Name: cachehorizontallayoutfunctor.h // Author: David Bauer // Created: 2023 // Copyright (c) Authors and others. All rights reserved. ///////////////////////////////////////////////////////////////////////////// #ifndef __VRV_CACHEHORIZONTALLAYOUTFUNCTOR_H__ #define __VRV_CACHEHORIZONTALLAYOUTFUNCTOR_H__ #include "functor.h" namespace vrv { //---------------------------------------------------------------------------- // CacheHorizontalLayoutFunctor //---------------------------------------------------------------------------- /** * This class caches or restores cached horizontal layout for faster layout redoing. */ class CacheHorizontalLayoutFunctor : public DocFunctor { public: /** * @name Constructors, destructors */ ///@{ CacheHorizontalLayoutFunctor(Doc *doc); virtual ~CacheHorizontalLayoutFunctor() = default; ///@} /* * Abstract base implementation */ bool ImplementsEndInterface() const override { return false; } /* * Set the restore flag */ void SetRestore(bool restore) { m_restore = restore; } /* * Functor interface */ ///@{ FunctorCode VisitArpeg(Arpeg *arpeg) override; FunctorCode VisitLayerElement(LayerElement *layerElement) override; FunctorCode VisitMeasure(Measure *measure) override; ///@} protected: // private: // public: // private: // Indicates if the cache should be stored (default) or restored bool m_restore; }; } // namespace vrv #endif // __VRV_CACHEHORIZONTALLAYOUTFUNCTOR_H__
412
0.954576
1
0.954576
game-dev
MEDIA
0.503
game-dev,graphics-rendering
0.716169
1
0.716169
ggnkua/Atari_ST_Sources
5,769
ASM/Various/Patrick Ruiz/diamonds/diamonds.l
; DIAMONDS ; Version 1.07 ; Dmo style "Jeu de la Vie" en basse rsolution. ; Charge une image ou remplit alatoirement l'cran ; puis affiche les gnrations. ; "Delete": Recommencer. ; "Esc" : Fin du programme. ILABEL GEM.BIB GEM_APP SCRN_GRES tst D0 bne FIN SCRN_GPBASE move.l D0,ECR_N PROG_SUPER #GETPALETTE bsr MSE_OFF SCRN_TEXT #AIDE,0,0 SCRN_TEXT #AIDE2,0,0 CONS_IN #2 choix_f: lea CHEMIN(PC),A3 lea FICHIER(PC),A4 clr.b (A4) bsr MSE_ON FILE_SELECT A3,A4,CHOIX bsr MSE_OFF bsr CLS tst CHOIX beq \1 ;chargement bsr NOUV_CHEMIN tst D3 bne \err FILE_OPEN #FICHIER,#0 move D0,D3 bmi \err move.l #32128,D4 FILE_READ D3,D4,#IMG cmp.l D4,D0 seq DEG_NEO beq \2 cmpi.l #32034,D0 beq \2 cmpi.l #32066,D0 beq \2 \err clr CHOIX bra \1 \2 FILE_CLOSE D3 \1 lea palette(PC),A3 tst CHOIX beq \3 lea IMG+2(PC),A3 tst.b DEG_NEO beq \3 addq #2,A3 \3 SCRN_SPALETTE A3 sf N_M ;initialiser ECR_M lea ECR_M+4+256,A0 move.l A0,D0 andi.l #$3FFF00,D0 move.l D0,ECR_M ;init TAB_N tst CHOIX bne IMAGE HAZARD: lea TAB_N+322+1,A3 move #320/2-1,D3 ;col. move #200-1,D4 ;lign. move #$0F0F,D5 ;masque \1 move #17,-(SP) trap #14 addq #2,SP lsr.l #7,D0 ;allons savoir and D5,D0 move D0,(A3)+ dbra D3,\1 move #320/2-1,D3 addq #2,A3 dbra D4,\1 bra pres IMAGE: ;IMG+34ou128 ---> TAB_N lea IMG+34(PC),A0 ;A0=srce tst.b DEG_NEO beq \1 lea IMG+128(PC),A0 \1 lea TAB_N+322+1,A1 ;A1=dest moveq #16-1,D0 ;D0=pix. move #320/16-1,D1 ;D1=col. de 16 pixels move #200-1,D2 ;D2=lign. \nsp move (A0)+,D3 ;D3=CR0 move (A0)+,D4 ;D4=CR1 move (A0)+,D5 ;D5=CR2 move (A0)+,D6 ;D6=CR3 \2 clr.b D7 ;D7=pixel lsl #1,D6 roxl.b #1,D7 lsl #1,D5 roxl.b #1,D7 lsl #1,D4 roxl.b #1,D7 lsl #1,D3 roxl.b #1,D7 move.b D7,(A1)+ dbra D0,\2 moveq #16-1,D0 dbra D1,\nsp move #320/16-1,D1 addq #2,A1 dbra D2,\nsp pres: bsr SPHERE bsr VOIR CONS_IN #2 DIAMONDS: lea TAB_M,A0 lea TAB_N,A1 tst.b N_M beq \1 lea TAB_N,A0 lea TAB_M,A1 \1 ;A0=TAB srce ;A1=TAB dest movea.l A0,A2 adda #322+1,A2 ;A2=ptr srce movea.l A1,A3 adda #322+1,A3 ;A3=ptr dest move #320-1,D0 ;D0=col. move #200-1,D1 ;D1=lign. moveq #- 1,D2 ;D2=offset G moveq # 1,D3 ;D3=offset D movea # 322,A4 ;A4=offset H movea #-322,A5 ;A5=offset B \np move.b (A2)+,D4 ;D4=coul pixel move.b D4,D5 ;D5=coul nouv pixel moveq #$F,D6 ;D6=masque mod16 addq #1,D5 and.b D6,D5 cmp.b -1(A2,D2),D5 beq \sq ;saut quantique! cmp.b -1(A2,D3),D5 beq \sq cmp.b -1(A2,A4),D5 beq \sq cmp.b -1(A2,A5),D5 beq \sq move.b D4,D5 ;rien de neuf \sq move.b D5,(A3)+ dbra D0,\np addq #2,A2 addq #2,A3 move #320-1,D0 dbra D1,\np bsr SPHERE bsr VOIR attente: CONS_GINSTATE #2 tst D0 beq DIAMONDS CONS_IN #2 cmpi.b #27,D0 seq D3 beq EPILOGUE cmpi.b #127,D0 beq EPILOGUE bra attente EPILOGUE: bsr CLS SCRN_SET #-1,ECR_N,#-1 SCRN_SPALETTE #palette_orig tst.b D3 beq choix_f bsr MSE_ON bra FIN SPHERE: ; report sphrique lea TAB_N,A0 tst.b N_M beq \1 lea TAB_M,A0 \1 ;A0=TAB ;lign. -1 et 200 lea 1(A0),A1 move.l #200*322,D0 move #320-1,D1 \L_1 move.b (A1,D0.L),(A1)+ dbra D1,\L_1 movea.l A0,A1 adda.l #201*322+1,A1 move #320-1,D1 neg.l D0 \L200 move.b (A1,D0.L),(A1)+ dbra D1,\L200 ;col. -1 et 320 lea 322(A0),A1 move #200-1,D1 \C_1 move.b 320(A1),(A1) adda #322,A1 dbra D1,\C_1 lea 322+320+1(A0),A1 move #200-1,D1 \C320 move.b -320(A1),(A1) adda #322,A1 dbra D1,\C320 rts VOIR: ;TAB ---> ECR lea TAB_N,A0 movea.l ECR_N,A1 tst.b N_M beq \1 lea TAB_M,A0 movea.l ECR_M,A1 \1 adda #322+1,A0 ;A0=srce ;A1=dest movea.l A1,A3 ;A3=svg move #320/2-1,D0 ;D0=col. /2 car on traite 2 pixels la fois move #200-1,D1 ;D1=lign. moveq #1,D5 ;D2/D3/D4/D5=plans avec D5 indic. dbordement \nsp move.b (A0)+,D6 ;D6=coul 1er pixel move.b (A0)+,D7 ;D7=coul 2me pixel lsr.b #1,D6 roxl #1,D2 lsr.b #1,D6 roxl #1,D3 lsr.b #1,D6 roxl #1,D4 lsr.b #1,D6 roxl #1,D5 lsr.b #1,D7 roxl #1,D2 lsr.b #1,D7 roxl #1,D3 lsr.b #1,D7 roxl #1,D4 lsr.b #1,D7 roxl #1,D5 dbcs D0,\nsp move D2,(A1)+ ;vidage move D3,(A1)+ move D4,(A1)+ move D5,(A1)+ moveq #1,D5 dbra D0,\nsp addq #2,A0 move #320/2-1,D0 dbra D1,\nsp SCRN_SET #-1,A3,#-1 not.b N_M CONS_OUT #2,#7 ;BELl rts GETPALETTE: lea $FFFF8240,A0 lea palette_orig(PC),A1 moveq #15,D0 \1 move (A0)+,(A1)+ dbra D0,\1 rts MSE_ON: GRAF_MOUSE #257,A0 rts MSE_OFF: GRAF_MOUSE #256,A0 rts CLS: CONS_OUT #2,#27 CONS_OUT #2,#'E' rts NOUV_CHEMIN: ;tenir compte du disque et du chemin ;E:A3=chemin S:D3=erreur cmpi.b #'A',(A3) blo \1 cmpi.b #'P',(A3) bhi \1 clr D0 move.b (A3),D0 subi #'A',D0 DISK_SET D0 tst D0 bmi \err \1 ;chercher '\' movea.l A3,A0 movea.l A0,A1 ;dernier'\' moveq #'\',D0 \3 moveq #12,D1 \4 cmp.b (A0)+,D0 bne \2 lea -1(A0),A1 bra \3 \2 tst.b (A0) dbeq D1,\4 lea PAD(PC),A2 move.l A1,(A2)+ move.b 1(A1),(A2)+ clr.b 1(A1) DISK_SDIR A3 lea PAD(PC),A2 movea.l (A2)+,A0 move.b (A2)+,1(A0) tst D0 bmi \err clr D3 \f rts \err neg D3 bra \f _D AIDE: DC.B 27,"H",10,10,10 DC.B " Charge une image ou ",13,10 DC.B "[Annuler]:Remplissage alatoire. ",13,10,10 DC.B " [Touche]:Dbut. ",13,10,0 AIDE2 DC.B " [Delete]:Recommencer. ",13,10 DC.B " [Esc]:Fin du programme. ",0 CHEMIN: DC.B ".\*.PI1",0 DS.B 64-8+1,0 palette DC.W $000,$200,$300,$400,$500,$600,$700,$732 DC.W $742,$752,$652,$552,$770,$773,$775,$777 _M PAD DS.L 16 ECR_N DS.L 1 palette_orig DS.W 16 FICHIER DS.B 12+1 CHOIX DC.W 0 IMG DS.B 32128 DEG_NEO DS.B 1 ;drap. N_M DS.B 1 ;indicateur Normal/Miroir ECR_M DS.L 1 DS.B 32000+256 DS.B 1 ;"raligner" les TAB TAB_N DS.B (320+2)*(200+2) TAB_M DS.B (320+2)*(200+2) END
412
0.897849
1
0.897849
game-dev
MEDIA
0.337195
game-dev
0.994845
1
0.994845
rscustom/rocksmith-custom-song-toolkit
1,062
RocksmithToolkitCLI/sngwriter/writer.cs
using RocksmithToolkitLib.Sng2014HSL; using RocksmithToolkitLib.Sng; using RocksmithToolkitLib; using System.IO; using System.Text; using MiscUtil.IO; using MiscUtil.Conversion; namespace Writer { public class SngWriter { public static void Main(string[] args) { var xmlfile = args[0]; var sngfile = args[1]; using (FileStream fs = new FileStream(sngfile, FileMode.Create)) { // parse from XML Sng2014File sng = Sng2014File.ConvertSong(xmlfile); // write raw SNG data for diffing and inspection var raw = new FileStream(sngfile + ".raw", FileMode.Create); EndianBitConverter conv = EndianBitConverter.Little; EndianBinaryWriter w = new EndianBinaryWriter(conv, raw); sng.Write(w); // write fully packed SNG Platform platform = new Platform(GamePlatform.Pc, GameVersion.RS2014); sng.writeSng(fs, platform); } } } }
412
0.685618
1
0.685618
game-dev
MEDIA
0.282222
game-dev
0.669645
1
0.669645
codehaus-plexus/plexus-classworlds
3,857
src/main/java/org/codehaus/classworlds/ClassRealmReverseAdapter.java
package org.codehaus.classworlds; /* * Copyright 2001-2010 Codehaus Foundation. * * 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. */ import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; /** * A reverse adapter for ClassRealms * * @author Andrew Williams */ @SuppressWarnings({"UnnecessaryLocalVariable", "rawtypes"}) @Deprecated public class ClassRealmReverseAdapter extends org.codehaus.plexus.classworlds.realm.ClassRealm { public static ClassRealmReverseAdapter getInstance(ClassRealm oldRealm) { ClassRealmReverseAdapter adapter = new ClassRealmReverseAdapter(oldRealm); return adapter; } private final ClassRealm realm; private ClassRealmReverseAdapter(ClassRealm oldRealm) { super(ClassWorldReverseAdapter.getInstance(oldRealm.getWorld()), oldRealm.getId(), oldRealm.getClassLoader()); this.realm = oldRealm; } public String getId() { return realm.getId(); } public org.codehaus.plexus.classworlds.ClassWorld getWorld() { return ClassWorldReverseAdapter.getInstance(realm.getWorld()); } public void importFrom(String realmId, String pkgName) throws org.codehaus.plexus.classworlds.realm.NoSuchRealmException { try { realm.importFrom(realmId, pkgName); } catch (NoSuchRealmException e) { throw new org.codehaus.plexus.classworlds.realm.NoSuchRealmException(getWorld(), e.getId()); } } public void addURL(URL constituent) { realm.addConstituent(constituent); } public org.codehaus.plexus.classworlds.realm.ClassRealm locateSourceRealm(String className) { return getInstance(realm.locateSourceRealm(className)); } public void setParentRealm(org.codehaus.plexus.classworlds.realm.ClassRealm classRealm) { realm.setParent(ClassRealmAdapter.getInstance(classRealm)); } public org.codehaus.plexus.classworlds.realm.ClassRealm createChildRealm(String id) throws org.codehaus.plexus.classworlds.realm.DuplicateRealmException { try { return getInstance(realm.createChildRealm(id)); } catch (DuplicateRealmException e) { throw new org.codehaus.plexus.classworlds.realm.DuplicateRealmException(getWorld(), e.getId()); } } public ClassLoader getClassLoader() { return realm.getClassLoader(); } public org.codehaus.plexus.classworlds.realm.ClassRealm getParentRealm() { return getInstance(realm.getParent()); } public URL[] getURLs() { return realm.getConstituents(); } public Class loadClass(String name) throws ClassNotFoundException { return realm.loadClass(name); } public URL getResource(String name) { return realm.getResource(name); } @SuppressWarnings("unchecked") public Enumeration findResources(String name) throws IOException { return realm.findResources(name); } public InputStream getResourceAsStream(String name) { return realm.getResourceAsStream(name); } public void display() { realm.display(); } public boolean equals(Object o) { if (!(o instanceof ClassRealm)) return false; return getId().equals(((ClassRealm) o).getId()); } }
412
0.584082
1
0.584082
game-dev
MEDIA
0.415319
game-dev,web-backend
0.597919
1
0.597919
sergeyleschev/leetcode-swift
1,387
2501-3000/2531. Make Number of Distinct Characters Equal.swift
class Solution { // Solution by Sergey Leschev // 2531. Make Number of Distinct Characters Equal func insertAndRemove(_ mp: inout [Character: Int], _ toInsert: Character, _ toRemove: Character) { mp[toInsert, default: 0] += 1 mp[toRemove, default: 0] -= 1 if mp[toRemove] == 0 { mp.removeValue(forKey: toRemove) } } func isItPossible(_ word1: String, _ word2: String) -> Bool { var mp1: [Character: Int] = [:] var mp2: [Character: Int] = [:] for w1 in word1 { mp1[w1, default: 0] += 1 } for w2 in word2 { mp2[w2, default: 0] += 1 } for asciiValue in 97...122 { // ASCII values of 'a' to 'z' let c1 = Character(UnicodeScalar(asciiValue)!) for asciiValue2 in 97...122 { let c2 = Character(UnicodeScalar(asciiValue2)!) if mp1[c1] == nil || mp2[c2] == nil { continue } insertAndRemove(&mp1, c2, c1) insertAndRemove(&mp2, c1, c2) if mp1.count == mp2.count { return true } // Reset back the maps insertAndRemove(&mp1, c1, c2) insertAndRemove(&mp2, c2, c1) } } return false } }
412
0.670286
1
0.670286
game-dev
MEDIA
0.300897
game-dev
0.744559
1
0.744559
RS485/LogisticsPipes
12,089
common/logisticspipes/modules/ModuleItemSink.java
package logisticspipes.modules; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Stream; import javax.annotation.Nonnull; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import com.google.common.collect.ImmutableList; import org.jetbrains.annotations.NotNull; import logisticspipes.gui.hud.modules.HUDItemSink; import logisticspipes.interfaces.IClientInformationProvider; import logisticspipes.interfaces.IHUDModuleHandler; import logisticspipes.interfaces.IHUDModuleRenderer; import logisticspipes.interfaces.IModuleInventoryReceive; import logisticspipes.interfaces.IModuleWatchReciver; import logisticspipes.interfaces.IPipeServiceProvider; import logisticspipes.interfaces.ISlotUpgradeManager; import logisticspipes.network.NewGuiHandler; import logisticspipes.network.PacketHandler; import logisticspipes.network.abstractguis.ModuleCoordinatesGuiProvider; import logisticspipes.network.abstractguis.ModuleInHandGuiProvider; import logisticspipes.network.guis.module.inhand.ItemSinkInHand; import logisticspipes.network.guis.module.inpipe.ItemSinkSlot; import logisticspipes.network.packets.hud.HUDStartModuleWatchingPacket; import logisticspipes.network.packets.hud.HUDStopModuleWatchingPacket; import logisticspipes.network.packets.module.ModuleInventory; import logisticspipes.network.packets.modules.ItemSinkDefault; import logisticspipes.pipes.PipeLogisticsChassis.ChassiTargetInformation; import logisticspipes.proxy.MainProxy; import logisticspipes.proxy.computers.interfaces.CCCommand; import logisticspipes.proxy.computers.interfaces.CCType; import logisticspipes.utils.ISimpleInventoryEventHandler; import logisticspipes.utils.PlayerCollectionList; import logisticspipes.utils.SinkReply; import logisticspipes.utils.SinkReply.FixedPriority; import logisticspipes.utils.item.ItemIdentifier; import logisticspipes.utils.item.ItemIdentifierInventory; import logisticspipes.utils.item.ItemIdentifierStack; import logisticspipes.utils.tuples.Pair; import network.rs485.logisticspipes.connection.LPNeighborTileEntityKt; import network.rs485.logisticspipes.inventory.IItemIdentifierInventory; import network.rs485.logisticspipes.module.Gui; import network.rs485.logisticspipes.module.SimpleFilter; import network.rs485.logisticspipes.property.BitSetProperty; import network.rs485.logisticspipes.property.BooleanProperty; import network.rs485.logisticspipes.property.IBitSet; import network.rs485.logisticspipes.property.ItemIdentifierInventoryProperty; import network.rs485.logisticspipes.property.Property; import network.rs485.logisticspipes.util.FuzzyFlag; import network.rs485.logisticspipes.util.FuzzyUtil; @CCType(name = "ItemSink Module") public class ModuleItemSink extends LogisticsModule implements SimpleFilter, IClientInformationProvider, IHUDModuleHandler, IModuleWatchReciver, ISimpleInventoryEventHandler, IModuleInventoryReceive, Gui { public final ItemIdentifierInventoryProperty filterInventory = new ItemIdentifierInventoryProperty( new ItemIdentifierInventory(9, "Requested items", 1), ""); public final BooleanProperty defaultRoute = new BooleanProperty(false, "defaultdestination"); public final BitSetProperty fuzzyFlags = new BitSetProperty( new BitSet(filterInventory.getSizeInventory() * 4), "fuzzyFlags"); private final List<Property<?>> properties = ImmutableList.<Property<?>>builder() .add(filterInventory) .add(defaultRoute) .add(fuzzyFlags) .build(); private final PlayerCollectionList localModeWatchers = new PlayerCollectionList(); private final IHUDModuleRenderer HUD = new HUDItemSink(this); private SinkReply _sinkReply; private SinkReply _sinkReplyDefault; public ModuleItemSink() { filterInventory.addListener(this); } public static String getName() { return "item_sink"; } @Nonnull @Override public String getLPName() { return getName(); } @Nonnull @Override public List<Property<?>> getProperties() { return properties; } @Override @CCCommand(description = "Returns the FilterInventory of this Module") @Nonnull public IItemIdentifierInventory getFilterInventory() { return filterInventory; } @CCCommand(description = "Returns true if the module is a default route") public boolean isDefaultRoute() { return defaultRoute.getValue(); } @CCCommand(description = "Sets the default route status of this module") public void setDefaultRoute(Boolean isDefaultRoute) { defaultRoute.setValue(isDefaultRoute); if (!localModeWatchers.isEmpty()) { MainProxy.sendToPlayerList( PacketHandler.getPacket(ItemSinkDefault.class).setFlag(isDefaultRoute).setModulePos(this), localModeWatchers); } } @Override public void registerPosition(@Nonnull ModulePositionType slot, int positionInt) { super.registerPosition(slot, positionInt); _sinkReply = new SinkReply(FixedPriority.ItemSink, 0, true, false, 1, 0, new ChassiTargetInformation(getPositionInt())); _sinkReplyDefault = new SinkReply(FixedPriority.DefaultRoute, 0, true, true, 1, 0, new ChassiTargetInformation(getPositionInt())); } public Stream<ItemIdentifier> getAdjacentInventoriesItems() { return Objects.requireNonNull(_service) .getAvailableAdjacent() .inventories() .stream() .map(LPNeighborTileEntityKt::getInventoryUtil) .filter(Objects::nonNull) .flatMap(invUtil -> invUtil.getItems().stream()) .distinct(); } @Override public SinkReply sinksItem(@Nonnull ItemStack stack, ItemIdentifier item, int bestPriority, int bestCustomPriority, boolean allowDefault, boolean includeInTransit, boolean forcePassive) { if (defaultRoute.getValue() && !allowDefault) { return null; } if (bestPriority > _sinkReply.fixedPriority.ordinal() || (bestPriority == _sinkReply.fixedPriority.ordinal() && bestCustomPriority >= _sinkReply.customPriority)) { return null; } final IPipeServiceProvider service = _service; if (service == null) return null; if (filterInventory.containsUndamagedItem(item.getUndamaged())) { if (service.canUseEnergy(1)) { return _sinkReply; } return null; } final ISlotUpgradeManager upgradeManager = getUpgradeManager(); if (upgradeManager.isFuzzyUpgrade()) { for (Pair<ItemIdentifierStack, Integer> filter : filterInventory.contents()) { if (filter == null) { continue; } if (filter.getValue1() == null) { continue; } ItemIdentifier ident1 = item; ItemIdentifier ident2 = filter.getValue1().getItem(); IBitSet slotFlags = getSlotFuzzyFlags(filter.getValue2()); if (FuzzyUtil.INSTANCE.get(slotFlags, FuzzyFlag.IGNORE_DAMAGE)) { ident1 = ident1.getIgnoringData(); ident2 = ident2.getIgnoringData(); } if (FuzzyUtil.INSTANCE.get(slotFlags, FuzzyFlag.IGNORE_NBT)) { ident1 = ident1.getIgnoringNBT(); ident2 = ident2.getIgnoringNBT(); } if (ident1.equals(ident2)) { if (service.canUseEnergy(5)) { return _sinkReply; } return null; } } } if (defaultRoute.getValue()) { if (bestPriority > _sinkReplyDefault.fixedPriority.ordinal() || ( bestPriority == _sinkReplyDefault.fixedPriority.ordinal() && bestCustomPriority >= _sinkReplyDefault.customPriority)) { return null; } if (service.canUseEnergy(1)) { return _sinkReplyDefault; } return null; } return null; } @Override public void tick() {} @Override public @Nonnull List<String> getClientInformation() { List<String> list = new ArrayList<>(); list.add("Default: " + (isDefaultRoute() ? "Yes" : "No")); list.add("Filter: "); list.add("<inventory>"); list.add("<that>"); return list; } @Override public void startHUDWatching() { MainProxy.sendPacketToServer(PacketHandler.getPacket(HUDStartModuleWatchingPacket.class).setModulePos(this)); } @Override public void stopHUDWatching() { MainProxy.sendPacketToServer(PacketHandler.getPacket(HUDStopModuleWatchingPacket.class).setModulePos(this)); } @Override public void startWatching(EntityPlayer player) { localModeWatchers.add(player); MainProxy.sendPacketToPlayer(PacketHandler.getPacket(ModuleInventory.class) .setIdentList(ItemIdentifierStack.getListFromInventory(filterInventory)).setModulePos(this), player); MainProxy.sendPacketToPlayer( PacketHandler.getPacket(ItemSinkDefault.class).setFlag(defaultRoute.getValue()).setModulePos(this), player); } @Override public void stopWatching(EntityPlayer player) { localModeWatchers.remove(player); } @Override public void InventoryChanged(IInventory inventory) { MainProxy.runOnServer(getWorld(), () -> () -> MainProxy.sendToPlayerList( PacketHandler.getPacket(ModuleInventory.class) .setIdentList(ItemIdentifierStack.getListFromInventory(inventory)) .setModulePos(this), localModeWatchers ) ); } @Override public IHUDModuleRenderer getHUDRenderer() { return HUD; } @Override public void handleInvContent(@Nonnull Collection<ItemIdentifierStack> list) { filterInventory.handleItemIdentifierList(list); } @Override public boolean hasGenericInterests() { return defaultRoute.getValue(); } @Override public void collectSpecificInterests(@Nonnull Collection<ItemIdentifier> itemIdentifiers) { if (defaultRoute.getValue()) { return; } Map<ItemIdentifier, Integer> mapIC = filterInventory.getItemsAndCount(); itemIdentifiers.addAll(mapIC.keySet()); mapIC.keySet().stream().map(ItemIdentifier::getUndamaged).forEach(itemIdentifiers::add); if (getUpgradeManager().isFuzzyUpgrade()) { for (Pair<ItemIdentifierStack, Integer> stack : filterInventory.contents()) { if (stack.getValue1() == null) { continue; } ItemIdentifier ident = stack.getValue1().getItem(); IBitSet slotFlags = getSlotFuzzyFlags(stack.getValue2()); if (FuzzyUtil.INSTANCE.get(slotFlags, FuzzyFlag.IGNORE_DAMAGE)) { itemIdentifiers.add(ident.getIgnoringData()); } if (FuzzyUtil.INSTANCE.get(slotFlags, FuzzyFlag.IGNORE_NBT)) { itemIdentifiers.add(ident.getIgnoringNBT()); } if (FuzzyUtil.INSTANCE.get(slotFlags, FuzzyFlag.IGNORE_DAMAGE) && FuzzyUtil.INSTANCE.get(slotFlags, FuzzyFlag.IGNORE_NBT)) { itemIdentifiers.add(ident.getIgnoringData().getIgnoringNBT()); } } } } @Override public boolean interestedInAttachedInventory() { return false; // when we are default we are interested in everything anyway, otherwise we're only interested in our filter. } @Override public boolean interestedInUndamagedID() { return false; } @Override public boolean receivePassive() { return true; } public void setFuzzyFlags(BitSet fuzzyFlags) { this.fuzzyFlags.replaceWith(fuzzyFlags); } @Nonnull @Override public ModuleCoordinatesGuiProvider getPipeGuiProvider() { return NewGuiHandler.getGui(ItemSinkSlot.class).setDefaultRoute(defaultRoute.getValue()) .setFuzzyFlags(fuzzyFlags.copyValue()).setHasFuzzyUpgrade(getUpgradeManager().isFuzzyUpgrade()); } @Nonnull @Override public ModuleInHandGuiProvider getInHandGuiProvider() { return NewGuiHandler.getGui(ItemSinkInHand.class); } public IBitSet getSlotFuzzyFlags(int slotId) { final int startBit = slotId * 4; return fuzzyFlags.get(startBit, startBit + 3); } @Override public void readFromNBT(@NotNull NBTTagCompound tag) { super.readFromNBT(tag); // FIXME: remove after 1.12 if (!tag.hasKey("fuzzyFlags") && tag.hasKey("ignoreData") && tag.hasKey("ignoreNBT")) { BitSet ignoreData = BitSet.valueOf(tag.getByteArray("ignoreData")); BitSet ignoreNBT = BitSet.valueOf(tag.getByteArray("ignoreNBT")); for (int i = 0; i < filterInventory.getSizeInventory(); i++) { if (i < ignoreData.size()) { fuzzyFlags.set(i * 4 + FuzzyFlag.IGNORE_DAMAGE.getBit(), ignoreData.get(i)); } if (i < ignoreNBT.size()) { fuzzyFlags.set(i * 4 + FuzzyFlag.IGNORE_NBT.getBit(), ignoreNBT.get(i)); } } } } }
412
0.955815
1
0.955815
game-dev
MEDIA
0.677653
game-dev
0.97207
1
0.97207
s0bvi/goldsvet-opensource
43,614
casino/app/Games/JiXiang8PT/SlotSettings.php
<?php namespace VanguardLTE\Games\JiXiang8PT { 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; private $shop_id = null; public $licenseDK = 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->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->CurrentDenom = $this->game->denomination; $this->scaleMode = 0; $this->numFloat = 0; $this->Paytable['SYM_0'] = [ 0, 0, 0, 8888, 0, 0 ]; $this->Paytable['SYM_1'] = [ 0, 0, 0, 888, 0, 0 ]; $this->Paytable['SYM_2'] = [ 0, 0, 0, 688, 0, 0 ]; $this->Paytable['SYM_3'] = [ 0, 0, 0, 288, 0, 0 ]; $this->Paytable['SYM_4'] = [ 0, 0, 0, 88, 0, 0 ]; $this->Paytable['SYM_5'] = [ 0, 0, 0, 68, 0, 0 ]; $this->Paytable['SYM_6'] = [ 0, 0, 0, 38, 0, 0 ]; $this->Paytable['SYM_7'] = [ 0, 0, 0, 28, 0, 0 ]; $this->Paytable['SYM_8'] = [ 0, 0, 0, 18, 0, 0 ]; $this->Paytable['SYM_9'] = [ 0, 0, 0, 0, 2, 8, 38, 188, 888, 8888 ]; $reel = new GameReel(); foreach( [ 'reelStrip1', 'reelStrip2', 'reelStrip3', 'reelStrip4', 'reelStrip5', 'reelStrip6' ] as $reelStrip ) { if( count($reel->reelsStrip[$reelStrip]) ) { $this->$reelStrip = $reel->reelsStrip[$reelStrip]; } } foreach( [ 'reelStripBonus1', 'reelStripBonus2', 'reelStripBonus3', 'reelStripBonus4', 'reelStripBonus5', 'reelStripBonus6' ] as $reelStrip ) { if( count($reel->reelsStripBonus[$reelStrip]) ) { $this->$reelStrip = $reel->reelsStripBonus[$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 = true; $this->slotFastStop = 1; $this->slotExitUrl = '/'; $this->slotWildMpl = 1; $this->GambleType = 1; $this->slotFreeCount = 15; $this->slotFreeMpl = 3; $this->slotViewState = ($game->slotViewState == '' ? 'Normal' : $game->slotViewState); $this->hideButtons = []; $this->jpgs = \VanguardLTE\JPG::where('shop_id', $this->shop_id)->lockForUpdate()->get(); $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->Balance = $user->balance; $this->SymbolGame = [ '0', '1', 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]; $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]); } } } if( !isset($this->game->advanced) || strlen($this->game->advanced) <= 0 ) { $this->game->advanced = serialize([]); } $this->gameDataStatic = unserialize($this->game->advanced); if( count($this->gameDataStatic) > 0 ) { foreach( $this->gameDataStatic as $key => $vl ) { if( $vl['timelife'] <= time() ) { unset($this->gameDataStatic[$key]); } } } } 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 GetRandomPay() { $allRate = []; foreach( $this->Paytable as $vl ) { foreach( $vl as $vl2 ) { if( $vl2 > 0 ) { $allRate[] = $vl2; } } } shuffle($allRate); if( $this->game->stat_in < ($this->game->stat_out + ($allRate[0] * $this->AllBet)) ) { $allRate[0] = 0; } return $allRate[0]; } 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 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 ) { $tmpLog = json_decode($log->str); if( $tmpLog->responseEvent != 'gambleResult' ) { $this->lastEvent = $log->str; break; } } if( isset($tmpLog) ) { return $tmpLog; } else { return 'NULL'; } } 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() ]); } } $i++; } $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 * $lines * $this->CurrentDenom); } if( $slotState != 'freespin' ) { $game->increment('stat_in', $bet * $lines * $this->CurrentDenom); } $game->increment('stat_out', $win * $this->CurrentDenom); $game->tournament_stat($slotState, $this->user->id, $bet * $lines * $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 * $lines * $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($garantType = 'bet', $bet, $lines) { $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; } if( $garantType != 'bet' ) { $pref = '_bonus'; } else { $pref = ''; } $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] == '12' ) { 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' => [] ]; $seq = [ 0, 0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 ]; foreach( $prs as $index => $value ) { $key = $this->{'reelStrip' . $index}; $rSeq = rand(0, count($seq) - 1); $reel['reel' . $index][0] = $seq[$rSeq]; $reel['rp'][] = $rSeq; $rSeq = rand(0, count($seq) - 1); $reel['reel' . $index][1] = $seq[$rSeq]; $reel['rp'][] = $rSeq; $rSeq = rand(0, count($seq) - 1); $reel['reel' . $index][2] = $seq[$rSeq]; $reel['rp'][] = $rSeq; $reel['reel' . $index][3] = ''; } return $reel; } } }
412
0.623714
1
0.623714
game-dev
MEDIA
0.558198
game-dev
0.819073
1
0.819073
ProjectIgnis/CardScripts
1,440
official/c54514594.lua
--ヴォルカニック・ハンマー --Volcanic Hammerer local s,id=GetID() function s.initial_effect(c) --Inflict damage equal to number of "Volcanic" monsters in your GY x 200 local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_DAMAGE) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetCountLimit(1) e1:SetRange(LOCATION_MZONE) e1:SetCost(s.damcost) e1:SetTarget(s.damtg) e1:SetOperation(s.damop) c:RegisterEffect(e1) end s.listed_series={SET_VOLCANIC} function s.damcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():GetAttackAnnouncedCount()==0 end --Cannot attack this turn local e1=Effect.CreateEffect(e:GetHandler()) e1:SetDescription(3206) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_OATH+EFFECT_FLAG_CLIENT_HINT) e1:SetCode(EFFECT_CANNOT_ATTACK_ANNOUNCE) e1:SetReset(RESETS_STANDARD_PHASE_END) e:GetHandler():RegisterEffect(e1) end function s.damfilter(c) return c:IsMonster() and c:IsSetCard(SET_VOLCANIC) end function s.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(s.damfilter,tp,LOCATION_GRAVE,0,1,nil) end Duel.SetTargetPlayer(1-tp) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,0) end function s.damop(e,tp,eg,ep,ev,re,r,rp) local p=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER) local d=Duel.GetMatchingGroupCount(s.damfilter,tp,LOCATION_GRAVE,0,nil)*200 Duel.Damage(p,d,REASON_EFFECT) end
412
0.895929
1
0.895929
game-dev
MEDIA
0.989359
game-dev
0.802589
1
0.802589
FirstPersonKSP/AvionicsSystems
1,080
GameData/MOARdV/MAS_ASET/RetroButton/MAS_RB_SAS_RadialOut.cfg
PROP { name = MAS_RB_SAS_RadialOut MODEL { model = ASET/ASET_Props/Control/RetroButton/RetroButton } MODULE { name = MASComponent COLLIDER_EVENT { name = Collider collider = ButtonTopObj sound = ASET/ASET_Props/Sounds/buttonbeep volume = 1 onClick = fc.SetSASMode(6) variable = fc.GetSAS() } TRANSLATION { name = Button press translation transform = ButtonGrp startTranslation = 0, 0, 0 endTranslation = 0, -0.0025, 0 blend = true speed = 8.0 variable = fc.GetSASMode() == 6 } ANIMATION { name = Button lighting animation = RetroButtonLightAnim variable = 0.333 * (fc.Select(fc.GetSAS() and (fc.GetSASMode() == 6), 2, 0) + fc.GetPersistentAsNumber("Backlight")) } TEXT_LABEL { name = Label transform = ButtonNameTextObj fontSize = 2.50 lineSpacing = 1.0 font = Liberation Sans style = Bold alignment = Center anchor = MiddleCenter transformOffset = 0.0077, -0.0045 emissive = never passiveColor = COLOR_MOARdV_BlackPrintedText text = RADIAL$$$OUT } } }
412
0.880815
1
0.880815
game-dev
MEDIA
0.557177
game-dev
0.846012
1
0.846012
CardboardPowered/cardboard
2,622
src/main/java/io/papermc/paper/datacomponent/item/consumable/ConsumableTypesBridgeImpl.java
package io.papermc.paper.datacomponent.item.consumable; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import io.papermc.paper.adventure.PaperAdventure; import io.papermc.paper.registry.set.PaperRegistrySets; import io.papermc.paper.registry.set.RegistryKeySet; import java.util.ArrayList; import java.util.List; import net.kyori.adventure.key.Key; import net.minecraft.registry.Registries; import net.minecraft.registry.RegistryKeys; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.cardboardpowered.Registries_Bridge; import org.cardboardpowered.impl.CardboardPotionUtil; import org.jetbrains.annotations.ApiStatus; import org.jspecify.annotations.NullMarked; @ApiStatus.Internal @NullMarked public class ConsumableTypesBridgeImpl implements ConsumableTypesBridge { @Override public ConsumeEffect.ApplyStatusEffects applyStatusEffects(final List<PotionEffect> effectList, final float probability) { Preconditions.checkArgument(0 <= probability && probability <= 1, "probability must be between 0-1, was %s", probability); return new PaperApplyStatusEffects( new net.minecraft.item.consume.ApplyEffectsConsumeEffect( new ArrayList<>(Lists.transform(effectList, CardboardPotionUtil::fromBukkit)), probability ) ); } @Override public ConsumeEffect.RemoveStatusEffects removeStatusEffects(final RegistryKeySet<PotionEffectType> effectTypes) { return new PaperRemoveStatusEffects( new net.minecraft.item.consume.RemoveEffectsConsumeEffect( PaperRegistrySets.convertToNms(RegistryKeys.STATUS_EFFECT, Registries_Bridge.BUILT_IN_CONVERSIONS.lookup(), effectTypes) ) ); } @Override public ConsumeEffect.ClearAllStatusEffects clearAllStatusEffects() { return new PaperClearAllStatusEffects( new net.minecraft.item.consume.ClearAllEffectsConsumeEffect() ); } @Override public ConsumeEffect.PlaySound playSoundEffect(final Key sound) { return new PaperPlaySound( new net.minecraft.item.consume.PlaySoundConsumeEffect(PaperAdventure.resolveSound(sound)) ); } @Override public ConsumeEffect.TeleportRandomly teleportRandomlyEffect(final float diameter) { Preconditions.checkArgument(diameter > 0, "diameter must be positive, was %s", diameter); return new PaperTeleportRandomly( new net.minecraft.item.consume.TeleportRandomlyConsumeEffect(diameter) ); } }
412
0.867003
1
0.867003
game-dev
MEDIA
0.947607
game-dev
0.974629
1
0.974629
Anuken/Mindustry
1,826
core/src/mindustry/logic/LAccess.java
package mindustry.logic; import arc.struct.*; /** Setter/getter enum for logic-controlled objects. */ public enum LAccess{ totalItems, firstItem, totalLiquids, totalPower, itemCapacity, liquidCapacity, powerCapacity, powerNetStored, powerNetCapacity, powerNetIn, powerNetOut, ammo, ammoCapacity, currentAmmoType, memoryCapacity, health, maxHealth, heat, shield, armor, efficiency, progress, timescale, rotation, x, y, velocityX, velocityY, shootX, shootY, cameraX, cameraY, cameraWidth, cameraHeight, displayWidth, displayHeight, bufferSize, operations, size, solid, dead, range, shooting, boosting, mineX, mineY, mining, speed, team, type, flag, controlled, controller, name, payloadCount, payloadType, totalPayload, payloadCapacity, id, //values with parameters are considered controllable enabled("to"), //"to" is standard for single parameter access shoot("x", "y", "shoot"), shootp(true, "unit", "shoot"), config(true, "to"), color("to"); public final String[] params; public final boolean isObj; public static final LAccess[] all = values(), senseable = Seq.select(all, t -> t.params.length <= 1).toArray(LAccess.class), controls = Seq.select(all, t -> t.params.length > 0).toArray(LAccess.class), settable = {x, y, velocityX, velocityY, rotation, speed, armor, health, shield, team, flag, totalPower, payloadType}; LAccess(String... params){ this.params = params; isObj = false; } LAccess(boolean obj, String... params){ this.params = params; isObj = obj; } }
412
0.851255
1
0.851255
game-dev
MEDIA
0.82819
game-dev
0.865409
1
0.865409
IllusionMods/KeelPlugins
1,490
src/Common.Utils/Resource.cs
using System.IO; using System.Reflection; namespace KeelPlugins.Utils { internal static class Resource { public static byte[] GetResourceAsBytes(Assembly assembly, string resourceName) { using(var stream = GetManifestResourceStream(assembly, resourceName)) using(var mem = new MemoryStream()) { CopyTo(stream, mem); return mem.ToArray(); } } public static string GetResourceAsString(Assembly assembly, string resourceName) { using(var stream = GetManifestResourceStream(assembly, resourceName)) using(var reader = new StreamReader(stream)) return reader.ReadToEnd(); } private static Stream GetManifestResourceStream(Assembly assembly, string resourceName) { var resourcePath = $"{assembly.GetName().Name}.{resourceName}"; var res = assembly.GetManifestResourceStream(resourcePath); if(res == null) throw new FileNotFoundException(resourcePath); return res; } private static void CopyTo(Stream input, Stream outputStream) { byte[] buffer = new byte[16 * 1024]; // Fairly arbitrary size int bytesRead; while((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0) { outputStream.Write(buffer, 0, bytesRead); } } } }
412
0.652386
1
0.652386
game-dev
MEDIA
0.32891
game-dev
0.964405
1
0.964405
ProjectSkyfire/SkyFire.406a
11,008
src/server/scripts/Northrend/Nexus/Nexus/boss_ormorok.cpp
/* * Copyright (C) 2011-2019 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2008-2019 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2019 ScriptDev2 <https://github.com/scriptdev2/scriptdev2/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptPCH.h" #include "nexus.h" enum Spells { SPELL_CRYSTAL_SPIKES = 47958, //Don't work, using walkaround H_SPELL_CRYSTAL_SPIKES = 57082, //Don't work, using walkaround SPELL_CRYSTALL_SPIKE_DAMAGE = 47944, H_SPELL_CRYSTALL_SPIKE_DAMAGE = 57067, SPELL_CRYSTAL_SPIKE_PREVISUAL = 50442, MOB_CRYSTAL_SPIKE = 27099, SPELL_SPELL_REFLECTION = 47981, SPELL_TRAMPLE = 48016, H_SPELL_TRAMPLE = 57066, SPELL_FRENZY = 48017, SPELL_SUMMON_CRYSTALLINE_TANGLER = 61564, //summons npc 32665 SPELL_ROOTS = 28858 //proper spell id is unknown }; enum Yells { SAY_AGGRO = -1576020, SAY_DEATH = -1576021, SAY_REFLECT = -1576022, SAY_CRYSTAL_SPIKES = -1576023, SAY_KILL = -1576024 }; enum Creatures { MOB_CRYSTALLINE_TANGLER = 32665 }; #define SPIKE_DISTANCE 5.0f class boss_ormorok : public CreatureScript { public: boss_ormorok() : CreatureScript("boss_ormorok") { } CreatureAI* GetAI(Creature* creature) const { return new boss_ormorokAI (creature); } struct boss_ormorokAI : public ScriptedAI { boss_ormorokAI(Creature* creature) : ScriptedAI(creature) { instance = creature->GetInstanceScript(); } InstanceScript* instance; bool bFrenzy; bool bCrystalSpikes; uint8 uiCrystalSpikesCount; float fBaseX; float fBaseY; float fBaseZ; float fBaseO; float fSpikeXY[4][2]; uint32 uiCrystalSpikesTimer; uint32 uiCrystalSpikesTimer2; uint32 uiTrampleTimer; uint32 uiFrenzyTimer; uint32 uiSpellReflectionTimer; uint32 uiSummonCrystallineTanglerTimer; void Reset() { uiCrystalSpikesTimer = 12*IN_MILLISECONDS; uiTrampleTimer = 10*IN_MILLISECONDS; uiSpellReflectionTimer = 30*IN_MILLISECONDS; uiSummonCrystallineTanglerTimer = 17*IN_MILLISECONDS; bFrenzy = false; bCrystalSpikes = false; if (instance) instance->SetData(DATA_ORMOROK_EVENT, NOT_STARTED); } void EnterCombat(Unit* /*who*/) { DoScriptText(SAY_AGGRO, me); if (instance) instance->SetData(DATA_ORMOROK_EVENT, IN_PROGRESS); } void JustDied(Unit* /*killer*/) { DoScriptText(SAY_DEATH, me); if (instance) instance->SetData(DATA_ORMOROK_EVENT, DONE); } void KilledUnit(Unit* /*victim*/) { DoScriptText(SAY_KILL, me); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) { return; } if (bCrystalSpikes) { if (uiCrystalSpikesTimer2 <= diff) { fSpikeXY[0][0] = fBaseX+(SPIKE_DISTANCE*uiCrystalSpikesCount*cos(fBaseO)); fSpikeXY[0][1] = fBaseY+(SPIKE_DISTANCE*uiCrystalSpikesCount*sin(fBaseO)); fSpikeXY[1][0] = fBaseX-(SPIKE_DISTANCE*uiCrystalSpikesCount*cos(fBaseO)); fSpikeXY[1][1] = fBaseY-(SPIKE_DISTANCE*uiCrystalSpikesCount*sin(fBaseO)); fSpikeXY[2][0] = fBaseX+(SPIKE_DISTANCE*uiCrystalSpikesCount*cos(fBaseO-(M_PI/2))); fSpikeXY[2][1] = fBaseY+(SPIKE_DISTANCE*uiCrystalSpikesCount*sin(fBaseO-(M_PI/2))); fSpikeXY[3][0] = fBaseX-(SPIKE_DISTANCE*uiCrystalSpikesCount*cos(fBaseO-(M_PI/2))); fSpikeXY[3][1] = fBaseY-(SPIKE_DISTANCE*uiCrystalSpikesCount*sin(fBaseO-(M_PI/2))); for (uint8 i = 0; i < 4; ++i) me->SummonCreature(MOB_CRYSTAL_SPIKE, fSpikeXY[i][0], fSpikeXY[i][1], fBaseZ, 0, TEMPSUMMON_TIMED_DESPAWN, 7*IN_MILLISECONDS); if (++uiCrystalSpikesCount >= 13) bCrystalSpikes = false; uiCrystalSpikesTimer2 = 200; } else uiCrystalSpikesTimer2 -= diff; } if (!bFrenzy && HealthBelowPct(25)) { DoCast(me, SPELL_FRENZY); bFrenzy = true; } if (uiTrampleTimer <= diff) { DoCast(me, SPELL_TRAMPLE); uiTrampleTimer = 10*IN_MILLISECONDS; } else uiTrampleTimer -= diff; if (uiSpellReflectionTimer <= diff) { DoScriptText(SAY_REFLECT, me); DoCast(me, SPELL_SPELL_REFLECTION); uiSpellReflectionTimer = 30*IN_MILLISECONDS; } else uiSpellReflectionTimer -= diff; if (uiCrystalSpikesTimer <= diff) { DoScriptText(SAY_CRYSTAL_SPIKES, me); bCrystalSpikes = true; uiCrystalSpikesCount = 1; uiCrystalSpikesTimer2 = 0; fBaseX = me->GetPositionX(); fBaseY = me->GetPositionY(); fBaseZ = me->GetPositionZ(); fBaseO = me->GetOrientation(); uiCrystalSpikesTimer = 20*IN_MILLISECONDS; } else uiCrystalSpikesTimer -= diff; if (IsHeroic() && (uiSummonCrystallineTanglerTimer <= diff)) { Creature* Crystalline_Tangler = me->SummonCreature(MOB_CRYSTALLINE_TANGLER, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), me->GetOrientation(), TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 1000); if (Crystalline_Tangler) { Unit* target = NULL; uint8 Healer = 0; for (uint8 j = 1; j <= 4; j++) { switch (j) { case 1: Healer = CLASS_PRIEST; break; case 2: Healer = CLASS_PALADIN; break; case 3: Healer = CLASS_DRUID; break; case 4: Healer = CLASS_SHAMAN; break; } std::list<HostileReference*>::const_iterator i = me->getThreatManager().getThreatList().begin(); for (; i != me->getThreatManager().getThreatList().end(); ++i) { Unit* temp = Unit::GetUnit(*me, (*i)->getUnitGuid()); if (temp && temp->GetTypeId() == TYPEID_PLAYER && temp->getClass() == Healer) { target = temp; break; } } if (target) break; } if (!target) target = SelectTarget(SELECT_TARGET_RANDOM, 0); if (target) { Crystalline_Tangler->AI()->AttackStart(target); Crystalline_Tangler->getThreatManager().addThreat(target, 1000000000.0f); } } uiSummonCrystallineTanglerTimer = 17*IN_MILLISECONDS; } else uiSummonCrystallineTanglerTimer -= diff; DoMeleeAttackIfReady(); } }; }; class mob_crystal_spike : public CreatureScript { public: mob_crystal_spike() : CreatureScript("mob_crystal_spike") { } CreatureAI* GetAI(Creature* creature) const { return new mob_crystal_spikeAI (creature); } struct mob_crystal_spikeAI : public Scripted_NoMovementAI { mob_crystal_spikeAI(Creature* creature) : Scripted_NoMovementAI(creature) { } uint32 SpellCrystalSpikeDamageTimer; uint32 SpellCrystalSpikePrevisualTimer; void Reset() { SpellCrystalSpikeDamageTimer = 3700; SpellCrystalSpikePrevisualTimer = 1*IN_MILLISECONDS; } void UpdateAI(const uint32 diff) { if (SpellCrystalSpikePrevisualTimer <= diff) { DoCast(me, SPELL_CRYSTAL_SPIKE_PREVISUAL); SpellCrystalSpikePrevisualTimer = 10*IN_MILLISECONDS; } else SpellCrystalSpikePrevisualTimer -= diff; if (SpellCrystalSpikeDamageTimer <= diff) { DoCast(me, SPELL_CRYSTALL_SPIKE_DAMAGE); SpellCrystalSpikeDamageTimer = 10*IN_MILLISECONDS; } else SpellCrystalSpikeDamageTimer -= diff; } }; }; class mob_crystalline_tangler : public CreatureScript { public: mob_crystalline_tangler() : CreatureScript("mob_crystalline_tangler") { } CreatureAI* GetAI(Creature* creature) const { return new mob_crystalline_tanglerAI (creature); } struct mob_crystalline_tanglerAI : public ScriptedAI { mob_crystalline_tanglerAI(Creature* creature) : ScriptedAI(creature) {} uint32 uiRootsTimer; void Reset() { uiRootsTimer = 1*IN_MILLISECONDS; } void UpdateAI(const uint32 diff) { if (uiRootsTimer <= diff) { if (me->IsWithinDist(me->getVictim(), 5.0f, false)) { DoCast(me->getVictim(), SPELL_ROOTS); uiRootsTimer = 15*IN_MILLISECONDS; } } else uiRootsTimer -= diff; } }; }; void AddSC_boss_ormorok() { new boss_ormorok(); new mob_crystal_spike(); new mob_crystalline_tangler(); }
412
0.912424
1
0.912424
game-dev
MEDIA
0.977944
game-dev
0.942439
1
0.942439
barbalet/apesdk
38,262
ltbrief/universe.h
/**************************************************************** universe.h ============================================================= Copyright 1996-2025 Tom Barbalet. All rights reserved. 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. This software is a continuing work of Tom Barbalet, begun on 13 June 1996. No apes or cats were harmed in the writing of this software. ****************************************************************/ #include "toolkit.h" #include "sim.h" #ifndef SIMULATEDAPE_UNIVERSE_H #define SIMULATEDAPE_UNIVERSE_H #define EPISODIC_ON #define TERRITORY_ON /* entity */ #define BRAINCODE_ON /* entity */ #define IMMUNE_ON /* entity */ #define FEATURE_SET #undef DEBUG_LACK_OF_MOVEMENT #define SINGLE_BRAIN (32768) #define DOUBLE_BRAIN (SINGLE_BRAIN*2) #define CHARACTER_WIDTH (8) #define CHARACTER_HEIGHT (14) typedef enum { fc_object_name, fc_n_spacetime, fc_n_byte, fc_n_byte2, fc_end } file_contents; typedef struct { file_contents contents; n_string value; n_int number; } simulated_file_definition; /* This table represents the operator calculation that is used to create the density graphs. The first section of the table shows if a component is added "+", subtracted "-", not used "." or boolean true "X". This is translated to numbers in the second part of the table. This is condensed into the operator number and at the far right what these operator sums represent. */ static const n_byte operators[17][7] = { /*AHWOUS*/ "+.....", /* Area */ ".+....", /* Height */ "..+...", /* Water */ "...+..", /* Moving Sun */ "....+.", /* Total Sun */ ".....+", /* Salt */ /*AHWOUS*/ ".-+.+-", /* Bush */ "..+.+-", /* Grass */ "-++.+-", /* Tree */ "-++.-+", /* Seaweed */ "+.-.-+", /* Rockpool */ "+-+-++", /* Beach */ /*AHWOUS*/ "..+-.-", /* Insect */ "..--.-", /* Mouse */ "..+++-", /* Parrot */ "-+.-.-", /* Lizard */ "..+-+-" /* Eagle */ /*AHWOUS*/ }; #define AGE_IN_DAYS(bei) (land_date() - being_dob(bei)) #define AGE_IN_YEARS(bei) (AGE_IN_DAYS(bei)/TIME_YEAR_DAYS) /* in days, a little young, yes */ #define AGE_OF_MATURITY (30) /*4*/ typedef enum { VARIABLE_VECT_X = ( 3 + 1 ), VARIABLE_VECT_Y, VARIABLE_RANDOM, VARIABLE_WATER_LEVEL, VARIABLE_BIOLOGY_AREA, VARIABLE_BIOLOGY_HEIGHT, VARIABLE_BIOLOGY_WATER, VARIABLE_BIOLOGY_MOVING_SUN, VARIABLE_BIOLOGY_TOTAL_SUN, VARIABLE_BIOLOGY_SALT, VARIABLE_BIOLOGY_BUSH, VARIABLE_BIOLOGY_GRASS, VARIABLE_BIOLOGY_TREE, VARIABLE_BIOLOGY_SEAWEED, VARIABLE_BIOLOGY_ROCKPOOL, VARIABLE_BIOLOGY_BEACH, VARIABLE_BIOLOGY_INSECT, VARIABLE_BIOLOGY_MOUSE, VARIABLE_BIOLOGY_PARROT, VARIABLE_BIOLOGY_LIZARD, VARIABLE_BIOLOGY_EAGLE, VARIABLE_BIOLOGY_OUTPUT, VARIABLE_HUNGRY, VARIABLE_ENERGY, VARIABLE_LOCATION_Z, VARIABLE_TEST_Z, VARIABLE_IS_VISIBLE, VARIABLE_TIME, VARIABLE_DATE, VARIABLE_CURRENT_BEING, VARIABLE_NUMBER_BEINGS, VARIABLE_LOCATION_X, VARIABLE_LOCATION_Y, VARIABLE_STATE, VARIABLE_ID_NUMBER, VARIABLE_DATE_OF_BIRTH, VARIABLE_IS_ERROR, VARIABLE_WEATHER, /* Everything after this value can be both set and get */ VARIABLE_BRAIN_VALUE, /* This is a special case, all the remainder are stored as variables */ VARIABLE_VECT_ANGLE, VARIABLE_FACING, VARIABLE_SPEED, VARIABLE_ENERGY_DELTA, VARIABLE_HONOR, VARIABLE_PARASITES, VARIABLE_HEIGHT, VARIABLE_FIRST_NAME, VARIABLE_FAMILY_NAME_ONE, VARIABLE_FAMILY_NAME_TWO, VARIABLE_GOAL_TYPE, VARIABLE_GOAL_X, VARIABLE_GOAL_Y, VARIABLE_DRIVE_HUNGER, VARIABLE_DRIVE_SOCIAL, VARIABLE_DRIVE_FATIGUE, VARIABLE_DRIVE_SEX, VARIABLE_BRAIN_X, VARIABLE_BRAIN_Y, VARIABLE_BRAIN_Z, VARIABLE_SELECT_BEING, VARIABLE_TEST_X, VARIABLE_TEST_Y, VARIABLE_BIOLOGY_OPERATOR, VARIABLE_POSTURE, VARIABLE_PREFERENCE_MATE_HEIGHT_MALE, VARIABLE_PREFERENCE_MATE_HEIGHT_FEMALE, VARIABLE_PREFERENCE_MATE_PIGMENTATION_MALE, VARIABLE_PREFERENCE_MATE_PIGMENTATION_FEMALE, VARIABLE_PREFERENCE_MATE_HAIR_MALE, VARIABLE_PREFERENCE_MATE_HAIR_FEMALE, VARIABLE_PREFERENCE_MATE_FRAME_MALE, VARIABLE_PREFERENCE_MATE_FRAME_FEMALE, VARIABLE_PREFERENCE_GROOM_MALE, VARIABLE_PREFERENCE_GROOM_FEMALE, VARIABLE_PREFERENCE_ANECDOTE_EVENT_MUTATION, VARIABLE_PREFERENCE_ANECDOTE_AFFECT_MUTATION, VARIABLE_PREFERENCE_CHAT, VARIABLE_ATTENTION_ACTOR_INDEX, VARIABLE_ATTENTION_EPISODE_INDEX, VARIABLE_ATTENTION_BODY_INDEX, VARIABLE_SHOUT_CONTENT, VARIABLE_SHOUT_HEARD, VARIABLE_SHOUT_CTR, VARIABLE_SHOUT_VOLUME, VARIABLE_SHOUT_FAMILY0, VARIABLE_SHOUT_FAMILY1, VARIABLE_SOCIAL_GRAPH_LOCATION_X, VARIABLE_SOCIAL_GRAPH_LOCATION_Y, VARIABLE_SOCIAL_GRAPH_TIME, VARIABLE_SOCIAL_GRAPH_DATE, VARIABLE_SOCIAL_GRAPH_ATTRACTION, VARIABLE_SOCIAL_GRAPH_FOF, VARIABLE_SOCIAL_GRAPH_FAMILIARITY, VARIABLE_MEMORY_FIRST_NAME, VARIABLE_MEMORY_FAMILY_NAME_ONE, VARIABLE_MEMORY_FAMILY_NAME_TWO, VARIABLE_MEMORY_LOCATION_X, VARIABLE_MEMORY_LOCATION_Y, VARIABLE_MEMORY_TIME, VARIABLE_MEMORY_DATE, VARIABLE_MEMORY_FIRST_NAME0, VARIABLE_MEMORY_FAMILY_NAME_ONE0, VARIABLE_MEMORY_FAMILY_NAME_TWO0, VARIABLE_MEMORY_FIRST_NAME1, VARIABLE_MEMORY_FAMILY_NAME_ONE1, VARIABLE_MEMORY_FAMILY_NAME_TWO1, VARIABLE_MEMORY_EVENT, VARIABLE_MEMORY_AFFECT, VARIABLE_BEING /* This is a special case, it is the location where the main code starts */ } SECONDARY_APESCRIPT; typedef enum { BODY_HEAD = 0, BODY_TEETH, BODY_BACK, BODY_FRONT, BODY_LEFT_HAND, BODY_RIGHT_HAND, BODY_LEFT_FOOT, BODY_RIGHT_FOOT, INVENTORY_SIZE } BODY_INVENTORY_TYPES; typedef enum { RELATIONSHIP_SELF = 1, RELATIONSHIP_MOTHER, RELATIONSHIP_FATHER, RELATIONSHIP_DAUGHTER, RELATIONSHIP_SON, RELATIONSHIP_GRANDDAUGHTER, RELATIONSHIP_GRANDSON, RELATIONSHIP_SISTER, RELATIONSHIP_BROTHER, RELATIONSHIP_MATERNAL_GRANDMOTHER, RELATIONSHIP_MATERNAL_GRANDFATHER, RELATIONSHIP_PATERNAL_GRANDMOTHER, RELATIONSHIP_PATERNAL_GRANDFATHER, OTHER_MOTHER, OTHER_FATHER, OTHER_DAUGHTER, OTHER_SON, OTHER_GRANDDAUGHTER, OTHER_GRANDSON, OTHER_SISTER, OTHER_BROTHER, OTHER_MATERNAL_GRANDMOTHER, OTHER_MATERNAL_GRANDFATHER, OTHER_PATERNAL_GRANDMOTHER, OTHER_PATERNAL_GRANDFATHER, RELATIONSHIPS } RELATIONSHIP_TYPES; typedef enum { PREFERENCE_MATE_HEIGHT_MALE = 0, PREFERENCE_MATE_HEIGHT_FEMALE, PREFERENCE_MATE_PIGMENTATION_MALE, PREFERENCE_MATE_PIGMENTATION_FEMALE, PREFERENCE_MATE_HAIR_MALE, PREFERENCE_MATE_HAIR_FEMALE, PREFERENCE_MATE_FRAME_MALE, PREFERENCE_MATE_FRAME_FEMALE, PREFERENCE_GROOM_MALE, PREFERENCE_GROOM_FEMALE, PREFERENCE_ANECDOTE_EVENT_MUTATION, PREFERENCE_ANECDOTE_AFFECT_MUTATION, PREFERENCE_CHAT, PREFERENCE_SOCIAL, PREFERENCES } PREFERENCES_MATE; typedef enum { ATTENTION_EXTERNAL = 0, ATTENTION_ACTOR, ATTENTION_EPISODE, ATTENTION_BODY, ATTENTION_RELATIONSHIP, ATTENTION_TERRITORY, ATTENTION_SIZE } attention_type; typedef enum { INTERVAL_MINS = 0, INTERVAL_HOURS, INTERVAL_DAYS, INTERVAL_MONTHS, INTERVAL_YEARS, INTERVALS } TIME_INTERVALS; static const n_int interval_steps[] = { 1, TIME_HOUR_MINUTES, TIME_DAY_MINUTES, TIME_MONTH_MINUTES, TIME_YEAR_MINUTES}; static const n_constant_string interval_description[] = { " mins", " hours", " days", " months", " years" }; #define FISHING_PROB (1<<8) /* converts a distance in metres to a squared range value */ #define METRES_TO_APESPACE(m) (m*m*80000) /* shouting */ #define SHOUT_RANGE METRES_TO_APESPACE(50) #define SHOUT_REFRACTORY 10 enum shout_elements { SHOUT_CONTENT = 0, SHOUT_HEARD, SHOUT_CTR, SHOUT_VOLUME, SHOUT_FAMILY0, SHOUT_FAMILY1, SHOUT_BYTES }; /* threshold for the sex drive, beyond which the being seeks a preferred mate */ #define THRESHOLD_SEEK_MATE 100 /* During gestation sex drive will be decreased by this amount per cycle */ #define GESTATION_SEX_DRIVE_DECREMENT 16 /* Speed beyond which fatigue drive begins to increase */ #define FATIGUE_SPEED_THRESHOLD 8 /* determines how often anecdotes will be mutated */ #define ANECDOTE_EVENT_MUTATION_RATE 5000 #define ANECDOTE_AFFECT_MUTATION_RATE 5000 /* used in the social graph */ enum being_interaction_social { BEING_MEETER = 0, /* the first person, I/me */ BEING_MET /* the second person, You */ }; /* number of days after which social graph entries may be forgotten */ #define SOCIAL_FORGET_DAYS 10 /* Distance within which social communication can take place. Note that this is a squared value */ #define SOCIAL_RANGE METRES_TO_APESPACE(10) /* range for squabbling */ #define SQUABBLE_RANGE METRES_TO_APESPACE(5) /* Distance within which mating can take place */ #define MATING_RANGE METRES_TO_APESPACE(5) /* Tollerance within which social drive continues to increase */ #define SOCIAL_TOLLERANCE 1 /* Minimum expected neighbours within the social range */ #define MIN_CROWDING 1 /* Maximum expected neighbours within the social range. Beyond this behavioral sink occurs. */ #define MAX_CROWDING 3 /* maximum mass of the being in 10g increments */ #define BEING_MAX_MASS_G 7000 /* maximum body fat in 10g increments */ #define BEING_MAX_MASS_FAT_G (BEING_MAX_MASS_G>>2) #ifndef MIN #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #endif /* calculate the mass of fat in 10g increments */ #define FAT_MASS(frame,energy) (MIN( ((BEING_MAX_MASS_FAT_G*energy*frame)>>(4+12)),BEING_MAX_MASS_FAT_G)) /* returns the amount of body fat in 10g increments */ #define GET_BODY_FAT(bei) (FAT_MASS(GENE_FRAME(being_genetics(bei)),being_energy(bei))) /* maximum height of the being (in millimetres) */ #define BEING_MAX_HEIGHT_MM 2000 /* maximum height of the being (in arbitrary units) */ #define BEING_MAX_HEIGHT 65535 /* returns height in real units (mm) */ #define GET_BEING_HEIGHT(bei) (being_height(bei)*BEING_MAX_HEIGHT_MM/BEING_MAX_HEIGHT) /* the amount of growth for a given energy intake Note that if AGE_OF_MATURITY is changed then this may also need to be changed to have a similar adult growth */ #define ENERGY_TO_GROWTH(b,e) ((e>>3)*3) /* physical characteristics at birth */ #define BIRTH_HEIGHT 2000 #define BIRTH_MASS 100 /* is the given index within a social graph empty? */ #define SOCIAL_GRAPH_ENTRY_EMPTY(graph,index) ((graph[index].first_name[BEING_MET]==0) && (graph[index].family_name[BEING_MET]==0) && (graph[index].relationship<=RELATIONSHIP_SELF)) /* is there a known location for the given social graph entry? */ #define SOCIAL_GRAPH_ENTRY_LOCATION_EXISTS(graph,index) (graph[index].location[0] + graph[index].location[1] > 0) /* is the given social graph entry a family member? */ #define IS_FAMILY_MEMBER(graph,index) ((graph[index].relationship > RELATIONSHIP_SELF) && (graph[index].relationship < OTHER_MOTHER)) #define EVENT_INTENTION (128) /* this possible could be genetic */ #define THROW_ACCURACY (1<<15) #define WHACK_ACCURACY (1<<15) #define PAIR_BOND_THRESHOLD 2 /* minimum level of attraction for mating */ #ifdef FEATURE_SET #define MAX_FEATURESET_SIZE 16 /* max size of a set of features associated with a social graph entry */ /* The maximum hit counter value for each feature within a set */ #define MAX_FEATURE_FREQUENCY 2048 /* the maximum number of matches of a stereotype */ #define MAX_FEATURESET_OBSERVATIONS 2048 #endif #define SOCIAL_SIZE 12 /* maximum size of the social network */ #define SOCIAL_SIZE_BEINGS (SOCIAL_SIZE>>1) /* max number of specific beings within the social graph */ #define EPISODIC_SIZE 12 /* maximum number of episodic memories */ /* ApeScript overrides */ #define OVERRIDE_GOAL 1 /* number of time steps after which a goal is abandoned */ #define GOAL_TIMEOUT (60*24) /* how close do we need to get to a goal to say that it has been reached? */ #define GOAL_RADIUS 40000 #define DRIVES_MAX 255 /* maximum value of each drive */ enum drives_definition { DRIVE_HUNGER = 0, DRIVE_SOCIAL, DRIVE_FATIGUE, DRIVE_SEX, DRIVES /* number of biological drives */ }; /** used with social_meet function to specify whether the location should be included within the social graph entry */ enum being_meet_location_type { LOCATION_KNOWN = 0, LOCATION_UNKNOWN }; /* Types of entities which it's possible to have a disposition towards */ enum { ENTITY_BEING = 0, ENTITY_BEING_GROUP, ENTITY_OBJECT, ENTITY_TERRITORY }; typedef struct { n_byte2 value; n_byte2 frequency; n_byte type; } simulated_feature; #ifdef FEATURE_SET typedef struct { n_byte2 feature_number; simulated_feature features[MAX_FEATURESET_SIZE]; n_byte2 observations; } simulated_featureset; #endif /*! @struct @discussion This describes a disposition towards other beings or things (an edge in the social graph) @field entity_type The type of entity encountered @field location Location where the entity was last seen @field time The time when the social graph entry was last updated @field date The date when the social graph entry was last updated @field first_name The first name of the entity @field family_name The family names of the entity @field attraction Attraction/desirability value used for mating @field friend_foe Whether friendly or hostile towards this entity @field belief Current belief about the state of this entity @field familiarity How many times has this entity been encountered @field relationship The type of relationship with the entity @field classification set of features which belong to this entity @field braincode the language machinery associated with this entity */ typedef struct { n_spacetime space_time; n_byte2 first_name[2]; n_byte2 family_name[2]; n_byte attraction; n_byte friend_foe; n_byte2 belief; n_byte2 familiarity; n_byte relationship; n_byte entity_type; #ifdef FEATURE_SET simulated_featureset classification; #endif #ifdef BRAINCODE_ON n_byte braincode[BRAINCODE_SIZE]; #endif } simulated_isocial; /*! @struct @discussion Describes an episodic memory event @field event Type of event @field affect Affect value associated with the event @field location Location of the event @field time Time when the event occurred @field date0 First component of the date when the event occurred @field date1 Second component of the date when the event occurred @field first_name First name of a being associated with the event @field food Food item associated with the event @field family_name Family name of a being associated with the event @field arg Additional argument */ typedef struct { n_spacetime space_time; n_byte2 first_name[2]; n_byte2 family_name[2]; n_byte event; n_byte food; n_byte2 affect; n_byte2 arg; } simulated_iepisodic; /*! @struct @field name A number representing the place name @field familiarity Number of times that this place has been visited @discussion This is the equivalent of a place cell, containing parameters for a particular place on the map */ typedef struct { n_byte name; n_byte2 familiarity; } simulated_iplace; #ifdef BRAINCODE_ON /*! @struct @field type type of probe (0=read, 1=write) @field position position of the probe within the brain @field address address within the braincode @field frequency frequency of the pulse in time steps (minutes) @field offset resting value @field frequency current state of the probe @discussion A probe which can be attached to the brain to inject or detect signals. */ typedef struct { n_byte type; n_byte position; n_byte address; n_byte frequency; n_byte offset; n_byte state; } simulated_ibrain_probe; #endif typedef n_byte4 n_genetics; #define CHROMOSOMES 4 #define CHROMOSOME_Y 0 #define IMMUNE_ANTIGENS 8 #define IMMUNE_POPULATION 16 enum { WATCH_NONE = 0, WATCH_ALL = 1, WATCH_SOCIAL_GRAPH, WATCH_EPISODIC, WATCH_BRAINCODE, WATCH_BRAINPROBES, WATCH_APPEARANCE, WATCH_SPEECH, WATCH_PATHOGENS, WATCH_STATES }; /* ------- ------- ------- SIMULATED APE GENETICS MATRIX (BETA) ------- ------- ------- */ #define GET_NUCLEOTIDE(gene,num) ((gene[((num)>>3) & 3]>>((num&7)*2))&3) /* returns a value for the gene in the range 0-15 */ #define GENE_VAL(gene, num0, num1) ((GET_NUCLEOTIDE(gene,num0) << 2) | GET_NUCLEOTIDE(gene,num1)) /* Genes which regulate the transcription network */ #define GENE_REGULATOR(gene,a,b) (1+GENE_VAL(gene,(15+(a)),(15+(b)))) #define GENE_VAL_REG(gene,a,b,c,d) GENE_VAL(gene,GENE_REGULATOR(gene,a,b),GENE_REGULATOR(gene,c,d)) /* this may become redundant since body frame will be determined by other genes */ #define GENE_FRAME(gene) GENE_VAL_REG(gene, 10, 11, 1, 6) /* hair length */ #define GENE_HAIR(gene) GENE_VAL_REG(gene, 12, 5, 12, 11) /* Nose shape */ #define GENE_NOSE_SHAPE(gene) GENE_VAL_REG(gene, 4, 5, 6, 8) /* Mouth shape */ #define GENE_MOUTH_SHAPE(gene) GENE_VAL_REG(gene, 9, 5, 8, 15) /* Pigmentation */ #define GENE_PIGMENTATION(gene) GENE_VAL_REG(gene, 8, 9, 8, 3) /* Ear shape */ #define GENE_EAR_SHAPE(gene) GENE_VAL_REG(gene, 12, 4, 14, 1) /* Eyebrow shape */ #define GENE_EYEBROW_SHAPE(gene) GENE_VAL_REG(gene, 9, 10, 8, 4) /* Eye shape */ #define GENE_EYE_SHAPE(gene) GENE_VAL_REG(gene, 9, 12, 1, 5) /* Eye color */ #define GENE_EYE_COLOR(gene) GENE_VAL_REG(gene, 9, 7, 3, 7) /* Eye separation */ #define GENE_EYE_SEPARATION(gene) GENE_VAL_REG(gene, 3, 2, 0, 14) /* Rate of growth */ /*#define GENE_RATE_OF_GROWTH(gene) GENE_VAL_REG(gene, 11, 5, 13, 11) not used */ /* Returns a value for a gene corresponding to a body segment The number of body segments defined by the constant BONES is assumed to be < 18 */ #define GENE_HOX(gene,bodyseg) GENE_VAL_REG(gene, 2+(bodyseg), 4+(bodyseg), 18-(bodyseg), 21-(bodyseg)) /* Vision */ #define GENE_VISION_INITIAL(gene) GENE_VAL_REG(gene, 2, 12, 3, 9) #define GENE_VISION_DELTA(gene) GENE_VAL_REG(gene, 11, 7, 2, 9) /* Ear shape */ #define GENE_EAR_SHAPE(gene) GENE_VAL_REG(gene, 12, 4, 14, 1) /* Eyebrow shape */ #define GENE_EYEBROW_SHAPE(gene) GENE_VAL_REG(gene, 9, 10, 8, 4) #ifdef IMMUNE_ON /*! @struct @field antigens The number of antigens for each shape @field shape_antigen The shape of the antigen @field antbodies The number of antibodies for each shape @field shape_antibody The shape of the antibody @field strength immune system strength @discussion Immune system parameters */ typedef struct { n_byte antigens[IMMUNE_ANTIGENS]; n_byte shape_antigen[IMMUNE_ANTIGENS]; n_byte antibodies[IMMUNE_POPULATION]; n_byte shape_antibody[IMMUNE_POPULATION]; n_byte2 random_seed[2]; } simulated_immune_system; #endif typedef struct { n_byte2 location[2]; } simulated_idead_body; #define NUMBER_OF_BODIES (10) typedef struct { simulated_idead_body bodies[NUMBER_OF_BODIES]; n_byte2 count; n_byte2 location; } simulated_remains; typedef struct { n_byte4 date_of_birth; n_byte2 generation_min; n_byte2 generation_max; n_byte2 name[2]; n_genetics genetics[CHROMOSOMES]; /* constant */ } simulated_being_constant; enum PATHOGEN_TRANSMISSION_METHOD { PATHOGEN_TRANSMISSION_AIR = 0, PATHOGEN_TRANSMISSION_SOIL, PATHOGEN_TRANSMISSION_SEX, PATHOGEN_TRANSMISSION_TOUCH, PATHOGEN_TRANSMISSION_FOOD_VEGETABLE, PATHOGEN_TRANSMISSION_FOOD_FRUIT, PATHOGEN_TRANSMISSION_FOOD_SHELLFISH, PATHOGEN_TRANSMISSION_FOOD_SEAWEED, PATHOGEN_TRANSMISSION_TOTAL }; enum { METABOLISM_STATE = 0, METABOLISM_PROTEIN, METABOLISM_STARCH, METABOLISM_FAT, METABOLISM_SUGAR, METABOLISM_WATER, METABOLISM_BILE, METABOLISM_GLUCOSE, METABOLISM_MUSCLE, METABOLISM_AMINO_ACIDS, METABOLISM_GLUCOGEN, METABOLISM_ADRENALIN, METABOLISM_GLYCOGEN, METABOLISM_AMMONIA, METABOLISM_UREA, METABOLISM_LACTATE, METABOLISM_OXYGEN, METABOLISM_CO2, METABOLISM_FATTY_ACIDS, METABOLISM_TRIGLYCERIDE, METABOLISM_ADIPOSE, METABOLISM_INSULIN, METABOLISM_ADP, METABOLISM_ATP, METABOLISM_ENERGY, METABOLISM_HEAT, METABOLISM_PYRUVATE, METABOLISM_WASTE, METABOLISM_LEPTIN, METABOLISM_GHRELIN, METABOLISM_PROLACTIN, METABOLISM_MILK, METABOLISM_HEART_RATE, METABOLISM_BREATHING_RATE, METABOLISM_THERMOREGULATOR, METABOLISM_LUNG_CAPACITY, METABOLISM_SIZE }; enum { ORGAN_STOMACH = 1, ORGAN_MUSCLES, ORGAN_LIVER, ORGAN_KIDNEYS, ORGAN_LUNGS, ORGAN_PANCREAS_A, ORGAN_PANCREAS_B, ORGAN_TISSUE, ORGANS }; typedef enum { FULLY_ASLEEP = 0, SLIGHTLY_AWAKE = 1, FULLY_AWAKE = 2 } sleep_state; typedef struct { n_byte2 location[2]; n_byte direction_facing; n_byte velocity[10]; n_byte2 stored_energy; n_byte2 random_seed[2]; n_byte2 macro_state; n_byte parasites; n_byte honor; n_byte crowding; n_byte2 height; n_byte2 mass; n_byte posture; n_byte2 goal[4]; n_byte2 social_coord_x; n_byte2 social_coord_y; n_byte2 social_coord_nx; /* why is this needed? */ n_byte2 social_coord_ny; /* why is this needed? */ n_byte /*sleep_state*/ awake; #ifdef DEBUG_LACK_OF_MOVEMENT n_int total_movement; #endif } simulated_being_delta; #if 0 static simulated_file_definition simulated_being_events_json[]= { {type_object_name, "simulated_being_events", 1}, {type_object_name, "social", 1}, {type_n_spacetime, "space_time", 1}, {type_n_byte2, "first_name", 2}, {type_n_byte2, "family_name", 2}, {type_n_byte, "attraction", 1}, {type_n_byte, "friend_foe", 1}, {type_n_byte2, "belief", 1}, {type_n_byte2, "familiarity", 1}, {type_n_byte, "relationship", 1}, {type_n_byte, "entity_type", 1}, {type_end, "", 1} #ifdef FEATURE_SET n_byte2 feature_number; simulated_feature features[MAX_FEATURESET_SIZE]; n_byte2 value; n_byte2 frequency; n_byte type; n_byte2 observations; simulated_featureset classification; #endif #ifdef BRAINCODE_ON n_byte braincode[BRAINCODE_SIZE]; #endif {type_object_name, "episodic", 1}, n_spacetime space_time; n_byte2 first_name[2]; n_byte2 family_name[2]; n_byte event; n_byte food; n_byte2 affect; n_byte2 arg; {type_end, "", 1} }; #endif typedef struct { simulated_isocial social[SOCIAL_SIZE]; simulated_iepisodic episodic[EPISODIC_SIZE]; #ifdef TERRITORY_ON simulated_iplace territory[TERRITORY_DIMENSION * TERRITORY_DIMENSION]; #endif } simulated_being_events; typedef struct { n_byte drives[DRIVES]; n_byte shout[SHOUT_BYTES]; n_byte2 inventory[INVENTORY_SIZE]; n_byte learned_preference[PREFERENCES]; n_byte4 date_of_conception; n_genetics fetal_genetics[CHROMOSOMES]; /* constant */ n_byte2 father_name[2]; n_byte2 mother_name[2]; n_byte2 child_generation_min; n_byte2 child_generation_max; } simulated_being_volatile; typedef struct { #ifdef BRAINCODE_ON n_byte braincode_register[BRAINCODE_PSPACE_REGISTERS]; simulated_ibrain_probe brainprobe[BRAINCODE_PROBES]; #endif n_byte2 brain_state[6]; n_byte2 script_overrides; n_byte attention[ATTENTION_SIZE]; } simulated_being_brain; typedef struct { simulated_being_delta delta; simulated_being_constant constant; simulated_being_events events; simulated_being_brain braindata; simulated_being_volatile changes; #ifdef IMMUNE_ON simulated_immune_system immune_system; #endif } simulated_being; typedef void ( being_birth_event )( simulated_being *born, simulated_being *mother, void *sim ); typedef void ( being_death_event )( simulated_being *deceased, void *sim ); #define LARGE_SIM 256 typedef struct { simulated_being beings[LARGE_SIM]; simulated_remains remains; simulated_being *select; /* used by gui */ being_birth_event *ext_birth; being_death_event *ext_death; n_uint num; n_uint max; } simulated_group; typedef struct { n_uint real_time; n_uint last_time; n_uint delta_cycles; n_uint count_cycles; n_uint delta_frames; n_uint count_frames; } simulated_timing; /* macros defined to ease in the vectorised code */ #define GET_M(bei) ((bei)->delta.mass) #define GET_I(bei) (being_genetics(bei)[CHROMOSOME_Y]) #define FIND_SEX(array) (array&3) #define SEX_FEMALE 3 #define BRAIN_OFFSET(num) (num) typedef void ( loop_fn )( simulated_group *group, simulated_being *actual, void *data ); typedef void ( loop_no_sim_fn )( simulated_being *actual, void *data ); typedef void ( loop_no_sim_no_data_fn )( simulated_being *actual ); void loop_no_thread( simulated_group *group, simulated_being *being_not, loop_fn bf_func, void *data ); void loop_being_no_sim( simulated_being *beings, n_uint number_beings, loop_no_sim_fn bf_func, void *data ); void loop_being_no_sim_no_data( simulated_being *beings, n_uint number_beings, loop_no_sim_no_data_fn bf_func ); void loop_being( simulated_group *group, loop_fn bf_func, n_int beings_per_thread ); n_int being_location_x( simulated_being *value ); n_int being_location_y( simulated_being *value ); n_int being_energy( simulated_being *value ); n_genetics *being_genetics( simulated_being *value ); n_int being_dob( simulated_being *value ); typedef void ( console_generic )( void *ptr, n_string ape_name, simulated_being *local_being, n_string result ); typedef void ( line_braincode )( n_string pointer, n_int line ); #ifdef BRAINCODE_ON void command_populate_braincode( simulated_group *group, line_braincode function ); #endif n_file *death_record_file_ready( void ); void death_record_file_cleanup( void ); void console_capture_death( simulated_being *deceased, void *sim ); void *sim_init( KIND_OF_USE kind, n_uint randomise, n_uint offscreen_size, n_uint landbuffer_size ); void sim_cycle( void ); void sim_update_output( void ); /* This is the new way. Please continue forwards. */ n_file *tranfer_out( void ); n_file *tranfer_out_json( void ); n_int tranfer_in( n_file *input_file ); #ifdef APESCRIPT_INCLUDED n_int sim_interpret( n_file *input_file ); #endif void sim_close( void ); simulated_timing *sim_timing( void ); simulated_group *sim_group( void ); n_uint sim_memory_allocated( n_int max ); void sim_flood( void ); void sim_healthy_carrier( void ); void sim_realtime( n_uint time ); void sim_set_select( simulated_being *select ); n_int sim_new_run_condition( void ); void sim_view_options( n_int px, n_int py ); void sim_rotate( n_int integer_rotation_256 ); void sim_move( n_int rel_vel, n_byte kind ); void sim_change_selected( n_byte forwards ); n_int sim_view_regular( n_int px, n_int py ); void sim_control_set( n_int px, n_int py, n_byte value, n_byte character ); void sim_control_erase( n_int size_x, n_int size_y, n_int max_characters ); void sim_control_regular( n_int px, n_int py ); void sim_terrain( n_int sx ); void sim_set_console_input( n_console_input *local_input_function ); void sim_set_console_output( n_console_output *local_output_function ); void sim_set_output( n_int value ); n_int sim_get_writing_output( void ); n_string sim_output_string( void ); n_int sim_new( void ); void transfer_debug_csv( n_file *fil, n_byte initial ); n_int get_time_interval( n_string str, n_int *number, n_int *interval ); void watch_ape( void *ptr, n_console_output output_function ); void watch_control( void *ptr, n_string beingname, simulated_being *local_being, n_string result ); void command_change_selected( simulated_group *group, n_byte forwards ); n_int command_stop( void *ptr, n_string response, n_console_output output_function ); n_int command_idea( void *ptr, n_string response, n_console_output output_function ); n_int command_being( void *ptr, n_string response, n_console_output output_function ); n_int command_braincode( void *ptr, n_string response, n_console_output output_function ); n_int command_speech( void *ptr, n_string response, n_console_output output_function ); n_int command_relationship_count( n_int friend_type ); simulated_being *command_relationship_being( simulated_group *group, n_int friend_type, n_int location ); n_int command_pathogen_graph( void *ptr, n_string response, n_console_output output_function ); n_int command_social_graph( void *ptr, n_string response, n_console_output output_function ); n_int command_genome( void *ptr, n_string response, n_console_output output_function ); n_int command_appearance( void *ptr, n_string response, n_console_output output_function ); n_int command_stats( void *ptr, n_string response, n_console_output output_function ); n_int command_episodic( void *ptr, n_string response, n_console_output output_function ); n_int command_probes( void *ptr, n_string response, n_console_output output_function ); n_int command_watch( void *ptr, n_string response, n_console_output output_function ); n_int command_logging( void *ptr, n_string response, n_console_output output_function ); n_int command_list( void *ptr, n_string response, n_console_output output_function ); n_int command_memory( void *ptr, n_string response, n_console_output output_function ); n_int command_next( void *ptr, n_string response, n_console_output output_function ); n_int command_previous( void *ptr, n_string response, n_console_output output_function ); n_int command_simulation( void *ptr, n_string response, n_console_output output_function ); n_int command_step( void *ptr, n_string response, n_console_output output_function ); n_int command_run( void *ptr, n_string response, n_console_output output_function ); n_int command_interval( void *ptr, n_string response, n_console_output output_function ); n_int command_reset( void *ptr, n_string response, n_console_output output_function ); n_int command_top( void *ptr, n_string response, n_console_output output_function ); n_int command_epic( void *ptr, n_string response, n_console_output output_function ); n_int command_file( void *ptr, n_string response, n_console_output output_function ); n_int command_event( void *ptr, n_string response, n_console_output output_function ); n_int command_epic( void *ptr, n_string response, n_console_output output_function ); n_int console_death( void *ptr, n_string response, n_console_output output_function ); n_int command_save( void *ptr, n_string response, n_console_output output_function ); n_int command_open( void *ptr, n_string response, n_console_output output_function ); n_int command_script( void *ptr, n_string response, n_console_output output_function ); n_int command_quit( void *ptr, n_string response, n_console_output output_function ); #ifndef _WIN32 n_int sim_thread_console_quit( void ); void sim_thread_console( void ); #endif void sim_console( n_string simulation_filename, n_uint randomise ); #ifdef CONSOLE_REQUIRED const static simulated_console_command control_commands[] = { {&io_help, "help", "[(command)]", "Displays a list of all the commands"}, #ifdef COMMAND_LINE_EXPLICIT {&command_reset, "reset", "", "Reset the simulation"}, {&command_reset, "clear" "", ""}, {&command_open, "open", "[file]", "Load a simulation file"}, {&command_open, "load", "", ""}, #endif {&command_script, "script", "[file]", "Load an ApeScript simulation file"}, {&command_save, "save", "[file]", "Save a simulation file"}, {&command_quit, "quit", "", "Quits the console"}, {&command_quit, "exit", "", ""}, {&command_quit, "close", "", ""}, {&command_stop, "stop", "", "Stop the simulation during step or run"}, {&command_file, "file", "[(component)]", "Information on the file format"}, {&command_run, "run", "(time format)|forever", "Simulate for a given number of days or forever"}, {&command_step, "step", "", "Run for a single logging interval"}, {&command_top, "top", "", "List the top apes"}, {&command_epic, "epic", "", "List the most talked about apes"}, {&command_interval, "interval", "(days)", "Set the simulation logging interval in days"}, {&command_event, "event", "on|social|off", "Episodic events (all) on, social on or all off"}, {&command_logging, "logging", "on|off", "Turn logging of images and data on or off"}, {&command_logging, "log", "", ""}, {&command_simulation, "simulation", "", ""}, {&command_simulation, "sim", "", "Show simulation parameters"}, {&command_watch, "watch", "(ape name)|all|off|*", "Watch (specific *) for the current ape"}, {&command_watch, "monitor", "", ""}, {&command_idea, "idea", "", "Track shared braincode between apes"}, {&command_being, "ape", "", "Name of the currently watched ape"}, {&command_being, "pwd", "", ""}, {&command_pathogen_graph, "pathogen", "(ape name)", "* Show pathogens for a named ape"}, {&command_social_graph, "friends", "", ""}, {&command_social_graph, "social", "", ""}, {&command_social_graph, "socialgraph", "", ""}, {&command_social_graph, "graph", "(ape name)", "* Show social graph for a named ape"}, {&command_braincode, "braincode", "(ape name)", "* Show braincode for a named ape"}, {&command_speech, "speech", "(ape name)", "* Show speech for a named ape"}, {&command_episodic, "episodic", "(ape name)", "* Show episodic memory for a named ape"}, {&command_probes, "probes", "(ape name)", "* Show brain probes for a named ape"}, {&command_stats, "stats", "(ape name)", "* Show parameters for a named ape"}, {&command_stats, "status", "", ""}, {&command_appearance, "appearance", "(ape name)", "* Show appearance values for a named ape"}, {&command_appearance, "physical", "", ""}, {&command_genome, "genome", "(ape name)", "Show genome for a named ape"}, {&command_genome, "genetics", "", ""}, {&command_list, "list", "", "List all ape names"}, {&command_list, "ls", "", ""}, {&command_list, "dir", "", ""}, {&command_next, "next", "", "Next ape"}, {&command_previous, "previous", "", "Previous ape"}, {&command_previous, "prev", "", ""}, {&command_memory, "memory", "", "Memory information for the simulation"}, {0L, 0L}, }; #endif #endif /* SIMULATEDAPE_UNIVERSE_H */
412
0.905207
1
0.905207
game-dev
MEDIA
0.352841
game-dev
0.59369
1
0.59369
benperk/BeginningCSharp7
3,100
Chapter15/KarliCards/KarliCards.Gui/GameOptions.cs
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using Ch13CardLib; using System.Windows.Input; using System.IO; using System.Xml.Serialization; namespace KarliCards.Gui { [Serializable] public class GameOptions { private bool playAgainstComputer = true; private int numberOfPlayers = 2; private ComputerSkillLevel computerSkill = ComputerSkillLevel.Dumb; private ObservableCollection<string> playerNames = new ObservableCollection<string>(); public List<string> SelectedPlayers { get; set; } = new List<string>(); public static RoutedCommand OptionsCommand = new RoutedCommand("Show Options", typeof(GameOptions), new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.O, ModifierKeys.Control) })); public int NumberOfPlayers { get { return numberOfPlayers; } set { numberOfPlayers = value; OnPropertyChanged(nameof(NumberOfPlayers)); } } public bool PlayAgainstComputer { get { return playAgainstComputer; } set { playAgainstComputer = value; OnPropertyChanged(nameof(PlayAgainstComputer)); } } public ComputerSkillLevel ComputerSkill { get { return computerSkill; } set { computerSkill = value; OnPropertyChanged(nameof(ComputerSkill)); } } public ObservableCollection<string> PlayerNames { get { return playerNames; } set { playerNames = value; OnPropertyChanged("PlayerNames"); } } public void AddPlayer(string playerName) { if (playerNames.Contains(playerName)) return; playerNames.Add(playerName); OnPropertyChanged("PlayerNames"); } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public void Save() { using (var stream = File.Open("GameOptions.xml", FileMode.Create)) { var serializer = new XmlSerializer(typeof(GameOptions)); serializer.Serialize(stream, this); } } public static GameOptions Create() { if (File.Exists("GameOptions.xml")) { using (var stream = File.OpenRead("GameOptions.xml")) { var serializer = new XmlSerializer(typeof(GameOptions)); return serializer.Deserialize(stream) as GameOptions; } } else return new GameOptions(); } } }
412
0.6929
1
0.6929
game-dev
MEDIA
0.633359
game-dev
0.639178
1
0.639178
mit-biomimetics/Cheetah-Software
1,734
user/MIT_Controller/FSM_States/TransitionData.h
/*============================= FSM State =============================*/ #ifndef TRANSITIONDATA_H #define TRANSITIONDATA_H /** * Struct of relevant data that can be used during transition to pass * data between states. */ template <typename T> struct TransitionData { EIGEN_MAKE_ALIGNED_OPERATOR_NEW TransitionData() { zero(); } // Zero out all of the data void zero() { // Flag to mark when transition is done done = false; // Timing parameters t0 = 0.0; // time that transition started tCurrent = 0.0; // current time since transition started tDuration = 0.0; // overall transition duration // Robot state at the beginning of transition comState0 = Vec12<T>::Zero(); // center of mass state qJoints0 = Vec12<T>::Zero(); // joint positions pFoot0 = Mat34<T>::Zero(); // foot positions // Current robot state comState = Vec12<T>::Zero(); // center of mass state qJoints = Vec12<T>::Zero(); // joint positions pFoot = Mat34<T>::Zero(); // foot positions } // Flag to mark when transition is done bool done = false; // Timing parameters T t0; // time that transition started T tCurrent; // current time since transition started T tDuration; // overall transition duration // Robot state at the beginning of transition Vec12<T> comState0; // center of mass state Vec12<T> qJoints0; // joint positions Mat34<T> pFoot0; // foot positions // Current robot state Vec12<T> comState; // center of mass state Vec12<T> qJoints; // joint positions Mat34<T> pFoot; // foot positions }; template struct TransitionData<double>; template struct TransitionData<float>; #endif // CONTROLFSM_H
412
0.804245
1
0.804245
game-dev
MEDIA
0.365587
game-dev
0.62998
1
0.62998
clockworklabs/spacetimedb-minecraft
1,031
crates/mc173-server/src/block/repeater.rs
//! Redstone repeater metadata functions. use crate::geom::Face; /// Get the face where the repeater send power. #[inline] pub fn get_face(metadata: u8) -> Face { match metadata & 3 { 0 => Face::NegZ, 1 => Face::PosX, 2 => Face::PosZ, 3 => Face::NegX, _ => unreachable!() } } /// Set the face where the repeater send power. #[inline] pub fn set_face(metadata: &mut u8, face: Face) { *metadata &= !3; *metadata |= match face { Face::NegZ => 0, Face::PosX => 1, Face::PosZ => 2, Face::NegX => 3, _ => 0 }; } /// Get the delay of the repeater. #[inline] pub fn get_delay(metadata: u8) -> u8 { (metadata & 0b1100) >> 2 } /// Set the delay of the repeater. #[inline] pub fn set_delay(metadata: &mut u8, delay: u8) { *metadata &= !0b1100; *metadata |= (delay & 0b11) << 2; } /// Get the delay of the repeater in ticks. #[inline] pub fn get_delay_ticks(metadata: u8) -> u64 { (get_delay(metadata) as u64 + 1) * 2 }
412
0.761392
1
0.761392
game-dev
MEDIA
0.4598
game-dev
0.880523
1
0.880523
martinbjeldbak/Shotta
7,761
Libs/DevTool-1.1.6/Libs/CallbackHandler-1.0/CallbackHandler-1.0.lua
--[[ $Id: CallbackHandler-1.0.lua 1298 2022-12-12 15:10:10Z nevcairiel $ ]] local MAJOR, MINOR = "CallbackHandler-1.0", 8 local CallbackHandler = LibStub:NewLibrary(MAJOR, MINOR) if not CallbackHandler then return end -- No upgrade needed local meta = {__index = function(tbl, key) tbl[key] = {} return tbl[key] end} -- Lua APIs local securecallfunction, error = securecallfunction, error local setmetatable, rawget = setmetatable, rawget local next, select, pairs, type, tostring = next, select, pairs, type, tostring local function Dispatch(handlers, ...) local index, method = next(handlers) if not method then return end repeat securecallfunction(method, ...) index, method = next(handlers, index) until not method end -------------------------------------------------------------------------- -- CallbackHandler:New -- -- target - target object to embed public APIs in -- RegisterName - name of the callback registration API, default "RegisterCallback" -- UnregisterName - name of the callback unregistration API, default "UnregisterCallback" -- UnregisterAllName - name of the API to unregister all callbacks, default "UnregisterAllCallbacks". false == don't publish this API. function CallbackHandler.New(_self, target, RegisterName, UnregisterName, UnregisterAllName) RegisterName = RegisterName or "RegisterCallback" UnregisterName = UnregisterName or "UnregisterCallback" if UnregisterAllName==nil then -- false is used to indicate "don't want this method" UnregisterAllName = "UnregisterAllCallbacks" end -- we declare all objects and exported APIs inside this closure to quickly gain access -- to e.g. function names, the "target" parameter, etc -- Create the registry object local events = setmetatable({}, meta) local registry = { recurse=0, events=events } -- registry:Fire() - fires the given event/message into the registry function registry:Fire(eventname, ...) if not rawget(events, eventname) or not next(events[eventname]) then return end local oldrecurse = registry.recurse registry.recurse = oldrecurse + 1 Dispatch(events[eventname], eventname, ...) registry.recurse = oldrecurse if registry.insertQueue and oldrecurse==0 then -- Something in one of our callbacks wanted to register more callbacks; they got queued for event,callbacks in pairs(registry.insertQueue) do local first = not rawget(events, event) or not next(events[event]) -- test for empty before. not test for one member after. that one member may have been overwritten. for object,func in pairs(callbacks) do events[event][object] = func -- fire OnUsed callback? if first and registry.OnUsed then registry.OnUsed(registry, target, event) first = nil end end end registry.insertQueue = nil end end -- Registration of a callback, handles: -- self["method"], leads to self["method"](self, ...) -- self with function ref, leads to functionref(...) -- "addonId" (instead of self) with function ref, leads to functionref(...) -- all with an optional arg, which, if present, gets passed as first argument (after self if present) target[RegisterName] = function(self, eventname, method, ... --[[actually just a single arg]]) if type(eventname) ~= "string" then error("Usage: "..RegisterName.."(eventname, method[, arg]): 'eventname' - string expected.", 2) end method = method or eventname local first = not rawget(events, eventname) or not next(events[eventname]) -- test for empty before. not test for one member after. that one member may have been overwritten. if type(method) ~= "string" and type(method) ~= "function" then error("Usage: "..RegisterName.."(\"eventname\", \"methodname\"): 'methodname' - string or function expected.", 2) end local regfunc if type(method) == "string" then -- self["method"] calling style if type(self) ~= "table" then error("Usage: "..RegisterName.."(\"eventname\", \"methodname\"): self was not a table?", 2) elseif self==target then error("Usage: "..RegisterName.."(\"eventname\", \"methodname\"): do not use Library:"..RegisterName.."(), use your own 'self'", 2) elseif type(self[method]) ~= "function" then error("Usage: "..RegisterName.."(\"eventname\", \"methodname\"): 'methodname' - method '"..tostring(method).."' not found on self.", 2) end if select("#",...)>=1 then -- this is not the same as testing for arg==nil! local arg=select(1,...) regfunc = function(...) self[method](self,arg,...) end else regfunc = function(...) self[method](self,...) end end else -- function ref with self=object or self="addonId" or self=thread if type(self)~="table" and type(self)~="string" and type(self)~="thread" then error("Usage: "..RegisterName.."(self or \"addonId\", eventname, method): 'self or addonId': table or string or thread expected.", 2) end if select("#",...)>=1 then -- this is not the same as testing for arg==nil! local arg=select(1,...) regfunc = function(...) method(arg,...) end else regfunc = method end end if events[eventname][self] or registry.recurse<1 then -- if registry.recurse<1 then -- we're overwriting an existing entry, or not currently recursing. just set it. events[eventname][self] = regfunc -- fire OnUsed callback? if registry.OnUsed and first then registry.OnUsed(registry, target, eventname) end else -- we're currently processing a callback in this registry, so delay the registration of this new entry! -- yes, we're a bit wasteful on garbage, but this is a fringe case, so we're picking low implementation overhead over garbage efficiency registry.insertQueue = registry.insertQueue or setmetatable({},meta) registry.insertQueue[eventname][self] = regfunc end end -- Unregister a callback target[UnregisterName] = function(self, eventname) if not self or self==target then error("Usage: "..UnregisterName.."(eventname): bad 'self'", 2) end if type(eventname) ~= "string" then error("Usage: "..UnregisterName.."(eventname): 'eventname' - string expected.", 2) end if rawget(events, eventname) and events[eventname][self] then events[eventname][self] = nil -- Fire OnUnused callback? if registry.OnUnused and not next(events[eventname]) then registry.OnUnused(registry, target, eventname) end end if registry.insertQueue and rawget(registry.insertQueue, eventname) and registry.insertQueue[eventname][self] then registry.insertQueue[eventname][self] = nil end end -- OPTIONAL: Unregister all callbacks for given selfs/addonIds if UnregisterAllName then target[UnregisterAllName] = function(...) if select("#",...)<1 then error("Usage: "..UnregisterAllName.."([whatFor]): missing 'self' or \"addonId\" to unregister events for.", 2) end if select("#",...)==1 and ...==target then error("Usage: "..UnregisterAllName.."([whatFor]): supply a meaningful 'self' or \"addonId\"", 2) end for i=1,select("#",...) do local self = select(i,...) if registry.insertQueue then for eventname, callbacks in pairs(registry.insertQueue) do if callbacks[self] then callbacks[self] = nil end end end for eventname, callbacks in pairs(events) do if callbacks[self] then callbacks[self] = nil -- Fire OnUnused callback? if registry.OnUnused and not next(callbacks) then registry.OnUnused(registry, target, eventname) end end end end end end return registry end -- CallbackHandler purposefully does NOT do explicit embedding. Nor does it -- try to upgrade old implicit embeds since the system is selfcontained and -- relies on closures to work.
412
0.91156
1
0.91156
game-dev
MEDIA
0.496304
game-dev
0.914819
1
0.914819