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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
castle-engine/castle-engine | 2,236 | src/scene/castlelivingbehaviors_missile.inc | {%MainUnit castlelivingbehaviors.pas}
{
Copyright 2006-2024 Michalis Kamburelis.
This file is part of "Castle Game Engine".
"Castle Game Engine" is free software; see the file COPYING.txt,
included in this distribution, for details about the copyright.
"Castle Game Engine" 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.
----------------------------------------------------------------------------
}
{$ifdef read_interface}
type
{ Missile that flies in the given direction @link(TCastleTransform.Direction)
with the given @link(MoveSpeed). On impact, it will hurt a living thing.
Missile may have also @link(TCastleMissile) if the missile can be destroyed
in-flight (e.g. by other missile or short-range attack of TCastleMoveAttack).
If the missile doesn't have @link(TCastleMissile), it is indestructible. }
TCastleMissile = class(TCastleBehavior)
strict private
FDamage: TCastleDamage;
protected
function CanAttachToParent(const NewParent: TCastleTransform;
out ReasonWhyCannot: String): Boolean; override;
public
constructor Create(AOwner: TComponent); override;
published
{ Damage caused by the missile impact. }
property Damage: TCastleDamage read FDamage;
// TODO: define MoveSpeed
// TODO: make missile fly (with physics, to also be affected by gravity)
// TODO: on impact (physical detect), apply Damage
end;
{$endif read_interface}
{$ifdef read_implementation}
{ TCastleMissile ------------------------------------------------------- }
constructor TCastleMissile.Create(AOwner: TComponent);
begin
inherited;
FDamage := TCastleDamage.Create(Self);
FDamage.SetSubComponent(true);
FDamage.Name := 'Damage';
end;
function TCastleMissile.CanAttachToParent(const NewParent: TCastleTransform;
out ReasonWhyCannot: String): Boolean;
begin
Result := inherited;
if not Result then Exit;
if NewParent.FindBehavior(TCastleMissile) <> nil then
begin
ReasonWhyCannot := 'Only one TCastleMissile can be added to a given TCastleTransform';
Result := false;
end;
end;
{$endif read_implementation}
| 412 | 0.822004 | 1 | 0.822004 | game-dev | MEDIA | 0.972311 | game-dev | 0.911708 | 1 | 0.911708 |
koobo/HippoPlayer | 24,312 | scopes/e_patternscope0.s | *******************************************************************************
* External patternscope for HippoPlayer
* By K-P Koljonen
*******************************************************************************
* Requires kick2.0+!
incdir include:
include exec/exec_lib.i
include exec/ports.i
include exec/types.i
include graphics/graphics_lib.i
include graphics/rastport.i
include intuition/intuition_lib.i
include intuition/intuition.i
include dos/dosextens.i
include mucro.i
incdir
include asm:pt/kpl_offsets.s
*** HippoPlayer's port:
STRUCTURE HippoPort,MP_SIZE
LONG hip_private1 * Private..
APTR hip_kplbase * kplbase address
WORD hip_reserved0 * Private..
BYTE hip_quit
BYTE hip_opencount * Open count
BYTE hip_mainvolume * Main volume, 0-64
BYTE hip_play * If non-zero, HiP is playing
BYTE hip_playertype * 33 = Protracker, 49 = PS3M.
*** Protracker ***
BYTE hip_reserved2
APTR hip_PTch1 * Protracker channel data for ch1
APTR hip_PTch2 * ch2
APTR hip_PTch3 * ch3
APTR hip_PTch4 * ch4
*** PS3M ***
APTR hip_ps3mleft * Buffer for the left side
APTR hip_ps3mright * Buffer for the right side
LONG hip_ps3moffs * Playing position
LONG hip_ps3mmaxoffs * Max value for hip_ps3moffs
BYTE hip_PTtrigger1
BYTE hip_PTtrigger2
BYTE hip_PTtrigger3
BYTE hip_PTtrigger4
LABEL HippoPort_SIZEOF
*** PT channel data block
STRUCTURE PTch,0
LONG PTch_start * Start address of sample
WORD PTch_length * Length of sample in words
LONG PTch_loopstart * Start address of loop
WORD PTch_replen * Loop length in words
WORD PTch_volume * Channel volume
WORD PTch_period * Channel period
WORD PTch_private1 * Private...
WIDTH = 320 * Drawing dimensions
HEIGHT = 64
RHEIGHT = HEIGHT+2
*** Variables:
rsreset
_ExecBase rs.l 1
_GFXBase rs.l 1
_IntuiBase rs.l 1
port rs.l 1
owntask rs.l 1
screenlock rs.l 1
oldpri rs.l 1
windowbase rs.l 1
rastport rs.l 1
userport rs.l 1
windowtop rs 1
windowtopb rs 1
windowright rs 1
windowleft rs 1
windowbottom rs 1
draw1 rs.l 1
draw2 rs.l 1
icounter rs 1
icounter2 rs 1
tr1 rs.b 1
tr2 rs.b 1
tr3 rs.b 1
tr4 rs.b 1
vol1 rs 1
vol2 rs 1
vol3 rs 1
vol4 rs 1
wbmessage rs.l 1
omabitmap rs.b bm_SIZEOF
size_var rs.b 0
main
lea var_b,a5
move.l 4.w,a6
move.l a6,(a5)
bsr.w getwbmessage
sub.l a1,a1
lob FindTask
move.l d0,owntask(a5)
lea intuiname(pc),a1
lore Exec,OldOpenLibrary
move.l d0,_IntuiBase(a5)
lea gfxname(pc),a1
lob OldOpenLibrary
move.l d0,_GFXBase(a5)
*** Try to find HippoPlayer's port, add 1 to hip_opencount
*** Protect this phase with Forbid()-Permit()!
lob Forbid
lea portname(pc),a1
lob FindPort
move.l d0,port(a5)
beq.w exit
move.l d0,a0
addq.b #1,hip_opencount(a0) * We are using the port now!
lob Permit
bsr.w getscreendata
*** Open our window
lea winstruc,a0
lore Intui,OpenWindow
move.l d0,windowbase(a5)
beq.w exit
move.l d0,a0
move.l wd_RPort(a0),rastport(a5)
move.l wd_UserPort(a0),userport(a5)
move.l rastport(a5),a1
moveq #1,d0
lore GFX,SetAPen
*** Draw some gfx
plx1 equr d4
plx2 equr d5
ply1 equr d6
ply2 equr d7
moveq #7,plx1
move #332,plx2
moveq #13,ply1
moveq #80,ply2
add windowleft(a5),plx1
add windowleft(a5),plx2
add windowtop(a5),ply1
add windowtop(a5),ply2
move.l rastport(a5),a1
bsr.w piirra_loota2a
*** Initialize our bitmap structure
lea omabitmap(a5),a0
moveq #1,d0 * depth
move #WIDTH,d1 * width
move #HEIGHT,d2 * heigth (turva-alue)
lore GFX,InitBitMap
move.l #buffer1,omabitmap+bm_Planes(a5)
move.l #buffer1,draw1(a5) * Buffer pointers for drawing
move.l #buffer2,draw2(a5)
move.l owntask(a5),a1 * Set our task to low priority
moveq #-30,d0
;moveq #0,d0
lore Exec,SetTaskPri
move.l d0,oldpri(a5) * Store the old priority
*** Main loop
loop move.l _GFXBase(a5),a6 * Wait...
lob WaitTOF
move.l port(a5),a0 * Check if HiP is playing
tst.b hip_quit(a0)
bne.b .x
tst.b hip_play(a0)
beq.b .oh
cmp.b #33,hip_playertype(a0) * Playing a Protracker module?
bne.b .oh
*** See if we should actually update the window.
move.l _IntuiBase(a5),a1
move.l ib_FirstScreen(a1),a1
move.l windowbase(a5),a0
cmp.l wd_WScreen(a0),a1 * Is our screen on top?
beq.b .yes
tst sc_TopEdge(a1) * Some other screen is partially on top
beq.b .oh * of our screen?
.yes
bsr.w dung * Do the scope
.oh
move.l userport(a5),a0 * Get messages from IDCMP
lore Exec,GetMsg
tst.l d0
beq.b loop
move.l d0,a1
move.l im_Class(a1),d2
move im_Code(a1),d3
lob ReplyMsg
cmp.l #IDCMP_MOUSEBUTTONS,d2 * Right mousebutton pressed?
bne.b .xy
cmp #MENUDOWN,d3
beq.b .x
.xy cmp.l #IDCMP_CLOSEWINDOW,d2 * Should we exit?
bne.b loop * No. Keep loopin'
.x move.l owntask(a5),a1 * Restore the old priority
move.l oldpri(a5),d0
lore Exec,SetTaskPri
exit
*** Exit program
move.l port(a5),d0 * IMPORTANT! Subtract 1 from
beq.b .uh0 * hip_opencount when exiting
move.l d0,a0
subq.b #1,hip_opencount(a0)
.uh0
move.l windowbase(a5),d0
beq.b .uh1
move.l d0,a0
lore Intui,CloseWindow
.uh1
move.l _IntuiBase(a5),d0
bsr.b closel
move.l _GFXBase(a5),d0
bsr.b closel
bsr.w replywbmessage
moveq #0,d0 * No error
rts
closel beq.b .huh
move.l d0,a1
lore Exec,CloseLibrary
.huh rts
***** Get info about screen we're running on
getscreendata
move.l (a5),a0
cmp #37,LIB_VERSION(a0)
bhs.b .new
rts
.new
*** Get some data about the default public screen
sub.l a0,a0
lore Intui,LockPubScreen * The only kick2.0+ function in this prg!
move.l d0,d7
beq.b exit
move.l d0,a0
move.b sc_BarHeight(a0),windowtop+1(a5) * Palkin korkeus
move.b sc_WBorBottom(a0),windowbottom+1(a5)
move.b sc_WBorTop(a0),windowtopb+1(a5)
move.b sc_WBorLeft(a0),windowleft+1(a5)
move.b sc_WBorRight(a0),windowright+1(a5)
move windowtopb(a5),d0
add d0,windowtop(a5)
subq #4,windowleft(a5) * saattaa menn negatiiviseksi
subq #4,windowright(a5)
subq #2,windowtop(a5)
subq #2,windowbottom(a5)
sub #10,windowtop(a5)
bpl.b .o
clr windowtop(a5)
.o
move windowtop(a5),d0 * Adjust the window size
add d0,winstruc+6
move windowleft(a5),d1
add d1,winstruc+4
add d1,winsiz
move windowbottom(a5),d3
add d3,winsiz+2
move.l d7,a1
sub.l a0,a0
lob UnlockPubScreen
rts
*** Draw a bevel box
piirra_loota2a
** bevelboksit, reunat kaks pixeli
laatikko1
moveq #1,d3
moveq #2,d2
move.l a1,a3
move d2,a4
move d3,a2
** valkoset reunat
move a2,d0
move.l a3,a1
lore GFX,SetAPen
move plx2,d0 * x1
subq #1,d0
move ply1,d1 * y1
move plx1,d2 * x2
move ply1,d3 * y2
bsr.w drawli
move plx1,d0 * x1
move ply1,d1 * y1
move plx1,d2
addq #1,d2
move ply2,d3
bsr.w drawli
** mustat reunat
move a4,d0
move.l a3,a1
lob SetAPen
move plx1,d0
addq #1,d0
move ply2,d1
move plx2,d2
move ply2,d3
bsr.b drawli
move plx2,d0
move ply2,d1
move plx2,d2
move ply1,d3
bsr.b drawli
move plx2,d0
subq #1,d0
move ply1,d1
addq #1,d1
move plx2,d2
subq #1,d2
move ply2,d3
bsr.b drawli
looex moveq #1,d0
move.l a3,a1
jmp _LVOSetAPen(a6)
drawli cmp d0,d2
bhi.b .e
exg d0,d2
.e cmp d1,d3
bhi.b .x
exg d1,d3
.x move.l a3,a1
move.l _GFXBase(a5),a6
jmp _LVORectFill(a6)
*** Draw the scope
dung
move.l _GFXBase(a5),a6 * Grab the blitter
lob OwnBlitter
lob WaitBlit
move.l draw2(a5),$dff054 * Clear the drawing area
move #0,$dff066
move.l #$01000000,$dff040
move #HEIGHT*64+WIDTH/16,$dff058
lob DisownBlitter * Free the blitter
pushm all
bsr.b notescroller * Do the scope
popm all
movem.l draw1(a5),d0/d1 * Doublebuffering
exg d0,d1
movem.l d0/d1,draw1(a5)
lea omabitmap(a5),a0 * Set the bitplane pointer so bitmap
move.l d1,bm_Planes(a0)
; lea omabitmap(a5),a0 * Copy from bitmap to rastport
move.l rastport(a5),a1
moveq #0,d0 * source x,y
moveq #0,d1
moveq #10,d2 * dest x,y
moveq #15,d3
add windowleft(a5),d2
add windowtop(a5),d3
move.l #$c0,d6 * minterm a->d
move.l #WIDTH,d4 * x-size
move #HEIGHT,d5 * y-size
lore GFX,BltBitMapRastPort
rts
*******************************
* NoteScroller (ProTracker)
*
notescroller
pushm all
bsr.w .notescr
*** viiva
move.l draw1(a5),a0
lea 7*40+2*8*40(a0),a0
moveq #19-1,d0
.raita or #$aaaa,(a0)+
or #$aaaa,8*40-2(a0)
dbf d0,.raita
move.l port(a5),a2
move.b hip_PTtrigger1(a2),d0
move.b hip_PTtrigger2(a2),d1
move.b hip_PTtrigger3(a2),d2
move.b hip_PTtrigger4(a2),d3
cmp.b tr1(a5),d0
beq.b .q1
move.l hip_PTch1(a2),a0
move PTch_volume(a0),vol1(a5)
.q1 cmp.b tr2(a5),d1
beq.b .q2
move.l hip_PTch2(a2),a0
move PTch_volume(a0),vol2(a5)
.q2 cmp.b tr3(a5),d2
beq.b .q3
move.l hip_PTch3(a2),a0
move PTch_volume(a0),vol3(a5)
.q3 cmp.b tr4(a5),d3
beq.b .q4
move.l hip_PTch4(a2),a0
move PTch_volume(a0),vol4(a5)
.q4
move.b d0,tr1(a5)
move.b d1,tr2(a5)
move.b d2,tr3(a5)
move.b d3,tr4(a5)
move.l port(a5),a0
move.l hip_PTch1(a0),a0
move vol1(a5),d0
moveq #2,d1
bsr.w .palkki
move.l port(a5),a0
move.l hip_PTch2(a0),a0
move vol2(a5),d0
moveq #11,d1
bsr.w .palkki
move.l port(a5),a0
move.l hip_PTch3(a0),a0
move vol3(a5),d0
moveq #20,d1
bsr.b .palkki
move.l port(a5),a0
move.l hip_PTch1(a0),a0
move vol4(a5),d0
moveq #29,d1
bsr.b .palkki
move.l port(a5),a0
move.l hip_PTch1(a0),a3
move.b #%11100000,d2
moveq #38,d1
bsr.w .palkki2
move.l port(a5),a0
move.l hip_PTch2(a0),a3
moveq #%1110,d2
moveq #38,d1
bsr.b .palkki2
move.l port(a5),a0
move.l hip_PTch3(a0),a3
moveq #39,d1
move.b #%11100000,d2
bsr.b .palkki2
move.l port(a5),a0
move.l hip_PTch4(a0),a3
moveq #%1110,d2
moveq #39,d1
bsr.b .palkki2
.ohi
lea vol1(a5),a0
bsr.b .orl
lea vol2(a5),a0
bsr.b .orl
lea vol3(a5),a0
bsr.b .orl
lea vol4(a5),a0
bsr.b .orl
popm all
rts
.orl tst (a0)
beq.b .urh
subq #1,(a0)
.urh rts
***** Volumepalkgi
.palkki
move.l port(a5),a0
moveq #0,d2
move.b hip_mainvolume(a0),d2
mulu d2,d0
lsr #6,d0
move.l draw1(a5),a0
lea 64*40(a0),a0
add d1,a0
lea .paldata(pC),a1
moveq #-2,d2
subq #1,d0
bmi.b .yg
.purl and.b d2,(a0)
move.b -(a1),d1
or.b d1,(a0)
lea -40(a0),a0
dbf d0,.purl
.yg rts
**** Periodpalkki
.palkki2
cmp #2,PTch_length(a3)
bls.b .h
moveq #0,d0
move PTch_period(a3),d0
beq.b .h
sub #108,d0
lsl #1,d0
divu #27,d0 * lukualueeksi 0-59
move.l draw1(a5),a0
lea multab(pc),a1
add d0,d0
move (a1,d0),d0
add d0,a0
add d1,a0
or.b d2,(a0)
or.b d2,40(a0)
or.b d2,80(a0)
or.b d2,120(a0)
.h rts
;* 8x58
; DC.l $FCFCDCFC,$FCFCDCFC,$74FCDCFC,$54FC5CFC,$54BC54FC,$54B854E8
; DC.l $54B854A8,$54B854A8,$548854A0,$54885420,$54885400,$54005000
; DC.l $54001000,$04001000
; dc $0000
;.paldata
* 8x64
DC.B $FC,$FC,$FC,$FC
DC.B $FC,$DC,$FC,$7C
DC.B $FC,$DC,$FC,$54
DC.B $FC,$5C,$FC,$54
DC.B $FC,$54,$FC,$54
DC.B $B8,$54,$FC,$54
DC.B $B8,$54,$AC,$54
DC.B $B8,$54,$A8,$54
DC.B $A8,$54,$A8,$54
DC.B $88,$54,$28,$54
DC.B $88,$54,$00,$54
DC.B $88,$54,$00,$54
DC.B $00,$54,$00,$54
DC.B $00,$10,$00,$54
DC.B $00,$10,$00,$00
DC.B $00,$10,$00,$00
.paldata
**************** Piirretn patterndata
.notescr
move.l port(a5),a0
move.l hip_kplbase(a0),a0
move.l k_songdataptr(a0),a3
moveq #0,d0
move k_songpos(a0),d0
move.b (a3,d0),d0
lsl #6,d0
add k_patternpos(a0),d0
lsl.l #4,d0
add.l d0,a3
lea 1084-952(a3),a3
move.l draw1(a5),a4
addq #3,a4
moveq #8-1,d7
move k_patternpos(a0),d6 * eka rivi?
move d6,d0
subq #4,d0
bpl.b .ok
neg d0
sub d0,d7
moveq #4,d1
sub d0,d1
sub d1,d6
lsl #4,d1
sub d1,a3
mulu #8*40,d0
add.l d0,a4
bra.b .ok2
.ok
lea -4*16(a3),a3
subq #4,d6
.ok2
.plorl
lea .pos(pc),a0 * rivinumero
move d6,d0
divu #10,d0
or.b #'0',d0
move.b d0,(a0)
swap d0
or.b #'0',d0
move.b d0,1(a0)
move.l a4,a1
subq #3,a1
moveq #2-1,d1
bsr.w .print
moveq #4-1,d5
.plorl2
lea .note(pc),a2
moveq #0,d0
move.b 2(a3),d0
bne.b .jee
move.b #' ',(a2)+
move.b #' ',(a2)+
move.b #' ',(a2)+
bra.b .nonote
.jee
subq #1,d0
divu #12*2,d0
addq #1,d0
or.b #'0',d0
move.b d0,2(a2)
swap d0
lea .notes(pc),a1
lea (a1,d0),a0
move.b (a0)+,(a2)+ * Nuotti
move.b (a0)+,(a2)+
addq #1,a2
.nonote
moveq #0,d0 * samplenumero
move.b 3(a3),d0
bne.b .onh
move.b #' ',(a2)+
move.b #' ',(a2)+
bra.b .eihn
.onh
lsr #2,d0
divu #$10,d0
bne.b .onh2
move.b #' ',(a2)+
bra.b .eihn2
.onh2 or.b #'0',d0
move.b d0,(a2)+
.eihn2 swap d0
bsr.b .hegs
.eihn
move.b (a3),d0 * komento
lsr.b #2,d0
bsr.b .hegs
moveq #0,d0
move.b 1(a3),d0
divu #$10,d0
bsr.b .hegs
swap d0
bsr.b .hegs
move.l a4,a1
lea .note(pc),a0
moveq #8-1,d1
bsr.b .print
addq #4,a3
add #9,a4
dbf d5,.plorl2
add #8*40-4*9,a4
addq #1,d6
cmp #64,d6
beq.b .lorl
dbf d7,.plorl
.lorl
rts
.hegs cmp.b #9,d0
bhi.b .high1
or.b #'0',d0
bra.b .hge
.high1 sub.b #10,d0
add.b #'A',d0
.hge move.b d0,(a2)+
rts
.notes dc.b "C-"
dc.b "C#"
dc.b "D-"
dc.b "D#"
dc.b "E-"
dc.b "F-"
dc.b "F#"
dc.b "G-"
dc.b "G#"
dc.b "A-"
dc.b "A#"
dc.b "B-"
.note dc.b "00000000"
.pos dc.b "00"
even
.print
pushm a3-a4
lea font(pc),a2
; move 38(a2),d2 * font modulo
; move.l 34(a2),a2 * data
move #192,d2
moveq #40,d4
.ooe moveq #0,d0
move.b (a0)+,d0
cmp.b #$20,d0
beq.b .space
lea -$20(a2,d0),a3
move.l a1,a4
moveq #8-1,d3
.lin move.b (a3),(a4)
add d2,a3
add d4,a4
dbf d3,.lin
.space addq #1,a1
dbf d1,.ooe
popm a3-a4
rts
multab
aa set 0
rept HEIGHT
dc aa
aa set aa+WIDTH/8
endr
**
* Workbench viestit
**
getwbmessage
sub.l a1,a1
lore Exec,FindTask
move.l d0,owntask(a5)
move.l d0,a4 * Vastataan WB:n viestiin, jos on.
tst.l pr_CLI(a4)
bne.b .nowb
lea pr_MsgPort(a4),a0
lob WaitPort
lea pr_MsgPort(a4),a0
lob GetMsg
move.l d0,wbmessage(a5)
.nowb rts
replywbmessage
move.l wbmessage(a5),d3
beq.b .nomsg
lore Exec,Forbid
move.l d3,a1
lob ReplyMsg
.nomsg rts
*******************************************************************************
* Window
wflags set WFLG_SMART_REFRESH!WFLG_DRAGBAR!WFLG_CLOSEGADGET!WFLG_DEPTHGADGET
wflags set wflags!WFLG_RMBTRAP
idcmpflags = IDCMP_CLOSEWINDOW!IDCMP_MOUSEBUTTONS
winstruc
dc 110,85 * x,y position
winsiz dc 340,85 * x,y size
dc.b 2,1
dc.l idcmpflags
dc.l wflags
dc.l 0
dc.l 0
dc.l .t * title
dc.l 0
dc.l 0
dc 0,640 * min/max x
dc 0,256 * min/max y
dc WBENCHSCREEN
dc.l 0
.t dc.b "PatternScope",0
intuiname dc.b "intuition.library",0
gfxname dc.b "graphics.library",0
dosname dc.b "dos.library",0
portname dc.b "HiP-Port",0
even
font
DC.B $00,$18,$6C,$6C,$18,$00,$38,$18
DC.B $0C,$30,$00,$00,$00,$00,$00,$03
DC.B $3C,$18,$3C,$3C,$1C,$7E,$1C,$7E
DC.B $3C,$3C,$00,$00,$0C,$00,$30,$3C
DC.B $7C,$18,$FC,$3C,$F8,$FE,$FE,$3C
DC.B $66,$7E,$0E,$E6,$F0,$82,$C6,$38
DC.B $FC,$38,$FC,$3C,$7E,$66,$C3,$C6
DC.B $C3,$C3,$FE,$3C,$C0,$3C,$10,$00
DC.B $18,$00,$E0,$00,$0E,$00,$1C,$00
DC.B $E0,$18,$06,$E0,$38,$00,$00,$00
DC.B $00,$00,$00,$00,$08,$00,$00,$00
DC.B $00,$00,$00,$0E,$18,$70,$72,$CC
DC.B $7E,$18,$0C,$1C,$42,$C3,$18,$3C
DC.B $66,$7E,$30,$00,$3E,$00,$7E,$7E
DC.B $3C,$18,$F0,$F0,$18,$00,$7E,$00
DC.B $00,$30,$70,$00,$20,$20,$C0,$18
DC.B $30,$0C,$18,$71,$C3,$3C,$1F,$3C
DC.B $60,$18,$30,$66,$30,$0C,$18,$66
DC.B $F8,$71,$30,$0C,$18,$71,$C3,$00
DC.B $3D,$30,$0C,$18,$66,$06,$F0,$7C
DC.B $30,$0C,$18,$71,$33,$3C,$00,$00
DC.B $30,$0C,$18,$66,$30,$0C,$18,$66
DC.B $60,$71,$30,$0C,$18,$71,$66,$00
DC.B $00,$30,$0C,$18,$66,$0C,$F0,$66
DC.B $00,$3C,$6C,$6C,$3E,$C6,$6C,$18
DC.B $18,$18,$66,$18,$00,$00,$00,$06
DC.B $66,$38,$66,$66,$3C,$60,$30,$66
DC.B $66,$66,$18,$18,$18,$00,$18,$66
DC.B $C6,$3C,$66,$66,$6C,$66,$66,$66
DC.B $66,$18,$06,$66,$60,$C6,$E6,$6C
DC.B $66,$6C,$66,$66,$5A,$66,$C3,$C6
DC.B $66,$C3,$C6,$30,$60,$0C,$38,$00
DC.B $18,$00,$60,$00,$06,$00,$36,$00
DC.B $60,$00,$00,$60,$18,$00,$00,$00
DC.B $00,$00,$00,$00,$18,$00,$00,$00
DC.B $00,$00,$00,$18,$18,$18,$9C,$33
DC.B $66,$00,$3E,$36,$3C,$66,$18,$40
DC.B $00,$81,$48,$33,$06,$00,$81,$00
DC.B $66,$18,$18,$18,$30,$00,$F4,$00
DC.B $00,$70,$88,$CC,$63,$63,$23,$00
DC.B $08,$10,$24,$8E,$18,$66,$3C,$66
DC.B $10,$20,$48,$00,$08,$10,$24,$00
DC.B $6C,$8E,$08,$10,$24,$8E,$3C,$63
DC.B $66,$08,$10,$24,$00,$08,$60,$66
DC.B $08,$10,$24,$8E,$00,$66,$00,$00
DC.B $08,$10,$24,$00,$08,$10,$24,$00
DC.B $FC,$8E,$08,$10,$24,$8E,$00,$18
DC.B $01,$08,$10,$24,$00,$10,$60,$00
DC.B $00,$3C,$00,$FE,$60,$CC,$68,$30
DC.B $30,$0C,$3C,$18,$00,$00,$00,$0C
DC.B $6E,$18,$06,$06,$6C,$7C,$60,$06
DC.B $66,$66,$18,$18,$30,$7E,$0C,$06
DC.B $DE,$3C,$66,$C0,$66,$60,$60,$C0
DC.B $66,$18,$06,$6C,$60,$EE,$F6,$C6
DC.B $66,$C6,$66,$70,$18,$66,$66,$C6
DC.B $3C,$66,$8C,$30,$30,$0C,$6C,$00
DC.B $0C,$3C,$6C,$3C,$36,$3C,$30,$3B
DC.B $6C,$38,$06,$66,$18,$66,$7C,$3C
DC.B $DC,$3D,$EC,$3E,$3E,$66,$66,$63
DC.B $63,$66,$7E,$18,$18,$18,$00,$CC
DC.B $66,$18,$6C,$30,$66,$3C,$18,$3C
DC.B $00,$9D,$88,$66,$00,$7E,$B9,$00
DC.B $3C,$7E,$30,$30,$00,$C6,$F4,$18
DC.B $00,$30,$88,$66,$26,$26,$66,$18
DC.B $3C,$3C,$3C,$3C,$3C,$3C,$3C,$C0
DC.B $FE,$FE,$FE,$FE,$7E,$7E,$7E,$7E
DC.B $66,$C6,$3C,$3C,$3C,$3C,$66,$36
DC.B $CF,$66,$66,$66,$66,$C3,$7E,$66
DC.B $3C,$3C,$3C,$3C,$3C,$3C,$7E,$3C
DC.B $3C,$3C,$3C,$3C,$38,$38,$38,$38
DC.B $18,$7C,$3C,$3C,$3C,$3C,$3C,$00
DC.B $3E,$66,$66,$66,$66,$66,$7C,$66
DC.B $00,$18,$00,$6C,$3C,$18,$76,$00
DC.B $30,$0C,$FF,$7E,$00,$7E,$00,$18
DC.B $7E,$18,$1C,$1C,$CC,$06,$7C,$0C
DC.B $3C,$3E,$00,$00,$60,$00,$06,$0C
DC.B $DE,$66,$7C,$C0,$66,$78,$78,$CE
DC.B $7E,$18,$06,$78,$60,$FE,$DE,$C6
DC.B $7C,$C6,$7C,$38,$18,$66,$66,$D6
DC.B $18,$3C,$18,$30,$18,$0C,$C6,$00
DC.B $00,$06,$76,$66,$6E,$66,$78,$66
DC.B $76,$18,$06,$6C,$18,$77,$66,$66
DC.B $66,$66,$76,$60,$18,$66,$66,$6B
DC.B $36,$66,$4C,$70,$18,$0E,$00,$33
DC.B $66,$18,$6C,$78,$3C,$18,$00,$66
DC.B $00,$B1,$F8,$CC,$00,$7E,$B9,$00
DC.B $00,$18,$60,$18,$00,$C6,$74,$18
DC.B $00,$30,$70,$33,$2C,$2C,$2C,$30
DC.B $66,$66,$66,$66,$66,$66,$6F,$C0
DC.B $60,$60,$60,$60,$18,$18,$18,$18
DC.B $F6,$E6,$66,$66,$66,$66,$C3,$1C
DC.B $DB,$66,$66,$66,$66,$66,$63,$6C
DC.B $06,$06,$06,$06,$06,$06,$1B,$66
DC.B $66,$66,$66,$66,$18,$18,$18,$18
DC.B $7C,$66,$66,$66,$66,$66,$66,$7E
DC.B $67,$66,$66,$66,$66,$66,$66,$66
DC.B $00,$18,$00,$FE,$06,$30,$DC,$00
DC.B $30,$0C,$3C,$18,$00,$00,$00,$30
DC.B $76,$18,$30,$06,$FE,$06,$66,$18
DC.B $66,$06,$00,$00,$30,$00,$0C,$18
DC.B $DE,$7E,$66,$C0,$66,$60,$60,$C6
DC.B $66,$18,$66,$6C,$62,$D6,$CE,$C6
DC.B $60,$C6,$6C,$0E,$18,$66,$3C,$FE
DC.B $3C,$18,$32,$30,$0C,$0C,$00,$00
DC.B $00,$1E,$66,$60,$66,$7E,$30,$66
DC.B $66,$18,$06,$78,$18,$6B,$66,$66
DC.B $66,$66,$66,$3C,$18,$66,$66,$6B
DC.B $1C,$66,$18,$18,$18,$18,$00,$CC
DC.B $66,$3C,$3E,$30,$42,$3C,$18,$3C
DC.B $00,$B1,$00,$66,$00,$00,$B1,$00
DC.B $00,$18,$F8,$F0,$00,$C6,$14,$00
DC.B $00,$30,$00,$66,$19,$1B,$D9,$60
DC.B $7E,$7E,$7E,$7E,$7E,$7E,$7C,$66
DC.B $78,$78,$78,$78,$18,$18,$18,$18
DC.B $66,$D6,$C3,$C3,$C3,$C3,$C3,$36
DC.B $F3,$66,$66,$66,$66,$3C,$63,$66
DC.B $1E,$1E,$1E,$1E,$1E,$1E,$7F,$60
DC.B $7E,$7E,$7E,$7E,$18,$18,$18,$18
DC.B $C6,$66,$66,$66,$66,$66,$66,$00
DC.B $6B,$66,$66,$66,$66,$66,$66,$66
DC.B $00,$00,$00,$6C,$7C,$66,$CC,$00
DC.B $18,$18,$66,$18,$18,$00,$18,$60
DC.B $66,$18,$66,$66,$0C,$66,$66,$18
DC.B $66,$0C,$18,$18,$18,$7E,$18,$00
DC.B $C0,$C3,$66,$66,$6C,$66,$60,$66
DC.B $66,$18,$66,$66,$66,$C6,$C6,$6C
DC.B $60,$6C,$66,$66,$18,$66,$3C,$EE
DC.B $66,$18,$66,$30,$06,$0C,$00,$00
DC.B $00,$66,$66,$66,$66,$60,$30,$3C
DC.B $66,$18,$06,$6C,$18,$63,$66,$66
DC.B $7C,$3E,$60,$06,$1A,$66,$3C,$36
DC.B $36,$3C,$32,$18,$18,$18,$00,$33
DC.B $66,$3C,$0C,$30,$00,$18,$18,$02
DC.B $00,$9D,$FC,$33,$00,$00,$A9,$00
DC.B $00,$00,$00,$00,$00,$EE,$14,$00
DC.B $00,$00,$F8,$CC,$33,$31,$33,$66
DC.B $C3,$C3,$C3,$C3,$C3,$C3,$CC,$3C
DC.B $60,$60,$60,$60,$18,$18,$18,$18
DC.B $6C,$CE,$66,$66,$66,$66,$66,$63
DC.B $66,$66,$66,$66,$66,$18,$7E,$66
DC.B $66,$66,$66,$66,$66,$66,$D8,$66
DC.B $60,$60,$60,$60,$18,$18,$18,$18
DC.B $C6,$66,$66,$66,$66,$66,$66,$18
DC.B $73,$66,$66,$66,$66,$3C,$7C,$3C
DC.B $00,$18,$00,$6C,$18,$C6,$76,$00
DC.B $0C,$30,$00,$00,$18,$00,$18,$C0
DC.B $3C,$7E,$7E,$3C,$1E,$3C,$3C,$18
DC.B $3C,$38,$18,$18,$0C,$00,$30,$18
DC.B $78,$C3,$FC,$3C,$F8,$FE,$F0,$3E
DC.B $66,$7E,$3C,$E6,$FE,$C6,$C6,$38
DC.B $F0,$3C,$E3,$3C,$3C,$3E,$18,$C6
DC.B $C3,$3C,$FE,$3C,$03,$3C,$00,$00
DC.B $00,$3B,$3C,$3C,$3B,$3C,$78,$C6
DC.B $E6,$3C,$66,$E6,$3C,$63,$66,$3C
DC.B $60,$06,$F0,$7C,$0C,$3B,$18,$36
DC.B $63,$18,$7E,$0E,$18,$70,$00,$CC
DC.B $7E,$18,$00,$7E,$00,$3C,$18,$3C
DC.B $00,$81,$00,$00,$00,$00,$81,$00
DC.B $00,$7E,$00,$00,$00,$FA,$14,$00
DC.B $18,$00,$00,$00,$67,$62,$67,$3C
DC.B $C3,$C3,$C3,$C3,$C3,$C3,$CF,$08
DC.B $FE,$FE,$FE,$FE,$7E,$7E,$7E,$7E
DC.B $F8,$C6,$3C,$3C,$3C,$3C,$3C,$00
DC.B $BC,$3E,$3E,$3E,$3E,$3C,$60,$6C
DC.B $3B,$3B,$3B,$3B,$3B,$3B,$77,$3C
DC.B $3C,$3C,$3C,$3C,$3C,$3C,$3C,$3C
DC.B $7C,$66,$3C,$3C,$3C,$3C,$3C,$00
DC.B $3E,$3B,$3B,$3B,$3B,$18,$60,$18
DC.B $00,$00,$00,$00,$00,$00,$00,$00
DC.B $00,$00,$00,$00,$30,$00,$00,$00
DC.B $00,$00,$00,$00,$00,$00,$00,$00
DC.B $00,$00,$00,$30,$00,$00,$00,$00
DC.B $00,$00,$00,$00,$00,$00,$00,$00
DC.B $00,$00,$00,$00,$00,$00,$00,$00
DC.B $00,$06,$00,$00,$00,$00,$00,$00
DC.B $00,$00,$00,$00,$00,$00,$00,$FE
DC.B $00,$00,$00,$00,$00,$00,$00,$7C
DC.B $00,$00,$3C,$00,$00,$00,$00,$00
DC.B $F0,$07,$00,$00,$00,$00,$00,$00
DC.B $00,$70,$00,$00,$00,$00,$00,$33
DC.B $00,$00,$00,$00,$00,$00,$00,$00
DC.B $00,$7E,$00,$00,$00,$00,$7E,$00
DC.B $00,$00,$00,$00,$00,$C0,$00,$00
DC.B $30,$00,$00,$00,$01,$07,$01,$00
DC.B $00,$00,$00,$00,$00,$00,$00,$30
DC.B $00,$00,$00,$00,$00,$00,$00,$00
DC.B $00,$00,$00,$00,$00,$00,$00,$00
DC.B $00,$00,$00,$00,$00,$00,$F0,$60
DC.B $00,$00,$00,$00,$00,$00,$00,$10
DC.B $00,$00,$00,$00,$00,$00,$00,$00
DC.B $00,$00,$00,$00,$00,$00,$00,$00
DC.B $40,$00,$00,$00,$00,$70,$F0,$70
DC.B $00,$00,$00,$08,$00,$08,$00,$08
DC.B $00,$10,$00,$08,$00,$18,$00,$08
DC.B $00,$20,$00,$08,$00,$28,$00,$08
DC.B $00,$30,$00,$08,$00,$38,$00,$08
DC.B $00,$40,$00,$08,$00,$48,$00,$08
DC.B $00,$50,$00,$08,$00,$58,$00,$08
DC.B $00,$60,$00,$08,$00,$68,$00,$08
DC.B $00,$70,$00,$08,$00,$78,$00,$08
DC.B $00,$80,$00,$08,$00,$88,$00,$08
DC.B $00,$90,$00,$08,$00,$98,$00,$08
DC.B $00,$A0,$00,$08,$00,$A8,$00,$08
DC.B $00,$B0,$00,$08,$00,$B8,$00,$08
DC.B $00,$C0,$00,$08,$00,$C8,$00,$08
DC.B $00,$D0,$00,$08,$00,$D8,$00,$08
DC.B $00,$E0,$00,$08,$00,$E8,$00,$08
DC.B $00,$F0,$00,$08,$00,$F8,$00,$08
DC.B $01,$00,$00,$08,$01,$08,$00,$08
DC.B $01,$10,$00,$08,$01,$18,$00,$08
DC.B $01,$20,$00,$08,$01,$28,$00,$08
DC.B $01,$30,$00,$08,$01,$38,$00,$08
DC.B $01,$40,$00,$08,$01,$48,$00,$08
DC.B $01,$50,$00,$08,$01,$58,$00,$08
DC.B $01,$60,$00,$08,$01,$68,$00,$08
DC.B $01,$70,$00,$08,$01,$78,$00,$08
DC.B $01,$80,$00,$08,$01,$88,$00,$08
DC.B $01,$90,$00,$08,$01,$98,$00,$08
DC.B $01,$A0,$00,$08,$01,$A8,$00,$08
DC.B $01,$B0,$00,$08,$01,$B8,$00,$08
DC.B $01,$C0,$00,$08,$01,$C8,$00,$08
DC.B $01,$D0,$00,$08,$01,$D8,$00,$08
DC.B $01,$E0,$00,$08,$01,$E8,$00,$08
DC.B $01,$F0,$00,$08,$01,$F8,$00,$08
DC.B $02,$00,$00,$08,$02,$08,$00,$08
DC.B $02,$10,$00,$08,$02,$18,$00,$08
DC.B $02,$20,$00,$08,$02,$28,$00,$08
DC.B $02,$30,$00,$08,$02,$38,$00,$08
DC.B $02,$40,$00,$08,$02,$48,$00,$08
DC.B $02,$50,$00,$08,$02,$58,$00,$08
DC.B $02,$60,$00,$08,$02,$68,$00,$08
DC.B $02,$70,$00,$08,$02,$78,$00,$08
DC.B $02,$80,$00,$08,$02,$88,$00,$08
DC.B $02,$90,$00,$08,$02,$98,$00,$08
DC.B $02,$A0,$00,$08,$02,$A8,$00,$08
DC.B $02,$B0,$00,$08,$02,$B8,$00,$08
DC.B $02,$C0,$00,$08,$02,$C8,$00,$08
DC.B $02,$D0,$00,$08,$02,$D8,$00,$08
DC.B $02,$E0,$00,$08,$02,$E8,$00,$08
DC.B $02,$F0,$00,$08,$02,$F8,$00,$08
DC.B $03,$00,$00,$08,$03,$00,$00,$08
DC.B $03,$00,$00,$08,$03,$00,$00,$08
DC.B $03,$00,$00,$08,$03,$00,$00,$08
DC.B $03,$00,$00,$08,$03,$00,$00,$08
DC.B $03,$00,$00,$08,$03,$00,$00,$08
DC.B $03,$00,$00,$08,$03,$00,$00,$08
DC.B $03,$00,$00,$08,$03,$00,$00,$08
DC.B $03,$00,$00,$08,$03,$00,$00,$08
DC.B $03,$00,$00,$08,$03,$00,$00,$08
DC.B $03,$00,$00,$08,$03,$00,$00,$08
DC.B $03,$00,$00,$08,$03,$00,$00,$08
DC.B $03,$00,$00,$08,$03,$00,$00,$08
DC.B $03,$00,$00,$08,$03,$00,$00,$08
DC.B $03,$00,$00,$08,$03,$00,$00,$08
DC.B $03,$00,$00,$08,$03,$00,$00,$08
DC.B $03,$00,$00,$08,$03,$00,$00,$08
section udnm,bss_p
var_b ds.b size_var
section hihi,bss_c
buffer1 ds.b WIDTH/8*RHEIGHT
buffer2 ds.b WIDTH/8*RHEIGHT
end
| 412 | 0.885593 | 1 | 0.885593 | game-dev | MEDIA | 0.656551 | game-dev | 0.927936 | 1 | 0.927936 |
GValiente/butano | 19,061 | games/butano-fighter/src/bf_game_hero.cpp | /*
* Copyright (c) 2020-2025 Gustavo Valiente gustavo.valiente@protonmail.com
* zlib License, see LICENSE file.
*/
#include "bf_game_hero.h"
#include "bn_keypad.h"
#include "bn_colors.h"
#include "bn_fixed_rect.h"
#include "bn_sound_items.h"
#include "bn_sprite_builder.h"
#include "bn_sprite_items_hero_death.h"
#include "bn_sprite_items_hero_shield.h"
#include "bn_sprite_items_hero_weapons.h"
#include "bn_sprite_items_hero_bomb_icon.h"
#include "bn_sprite_items_hero_body_flying.h"
#include "bn_sprite_items_hero_body_walking.h"
#include "bf_scene_type.h"
#include "bf_game_enemies.h"
#include "bf_game_objects.h"
#include "bf_game_hero_bomb.h"
#include "bf_game_background.h"
#include "bf_butano_background.h"
#include "bf_game_enemy_bullets.h"
#include "bf_game_rumble_manager.h"
#include "bf_game_hero_bullet_level.h"
namespace bf::game
{
namespace
{
constexpr int body_delta_y = 48;
constexpr int weapon_delta_x = 2;
constexpr int weapon_delta_y = -13;
constexpr int shoot_frames = 5;
constexpr int scale_weapon_frames = 30;
constexpr int scale_weapon_half_frames = scale_weapon_frames / 2;
constexpr int body_shadows_multiplier = 4;
constexpr bn::fixed_size dimensions(12, 12);
bn::vector<bn::sprite_ptr, 3> _create_body_shadows(const bn::sprite_item& body_sprite_item,
const bn::camera_ptr& camera)
{
bn::vector<bn::sprite_ptr, 3> result;
for(int index = 0; index < 3; ++index)
{
bn::sprite_builder builder(body_sprite_item);
builder.set_z_order(constants::hero_shadows_z_order);
builder.set_camera(camera);
result.push_back(builder.release_build());
}
return result;
}
bn::sprite_cached_animate_action<2> _create_body_sprite_animate_action(const bn::sprite_item& body_sprite_item,
const bn::camera_ptr& camera)
{
bn::sprite_builder builder(body_sprite_item);
builder.set_position(0, body_delta_y);
builder.set_camera(camera);
return bn::create_sprite_cached_animate_action_forever(builder.release_build(), 16,
body_sprite_item.tiles_item(), 0, 1);
}
bn::sprite_ptr _create_weapon_sprite(int level, const bn::fixed_point& position, const bn::camera_ptr& camera)
{
bn::sprite_builder builder(bn::sprite_items::hero_weapons, level);
builder.set_position(position);
builder.set_camera(camera);
return builder.release_build();
}
bn::sprite_ptr _create_shield_sprite(const bn::camera_ptr& camera)
{
bn::sprite_builder builder(bn::sprite_items::hero_shield);
builder.set_z_order(constants::hero_shield_z_order);
builder.set_camera(camera);
builder.set_visible(false);
return builder.release_build();
}
}
hero::hero(const bn::camera_ptr& camera, status& status) :
_status(status),
_body_sprite_item(status.current_stage().in_air ?
bn::sprite_items::hero_body_flying : bn::sprite_items::hero_body_walking),
_body_shadows(_create_body_shadows(_body_sprite_item, camera)),
_body_sprite_animate_action(_create_body_sprite_animate_action(_body_sprite_item, camera)),
_body_snapshots(body_snapshots_count, body_snapshot_type{ _body_sprite_animate_action.sprite().position(), 0 }),
_body_position(0, body_delta_y),
_weapon_position(weapon_delta_x, body_delta_y + weapon_delta_y),
_weapon_sprite(_create_weapon_sprite(status.level(), _weapon_position, camera)),
_shield_sprite(_create_shield_sprite(camera)),
_bomb_sprites_affine_mat(bn::sprite_affine_mat_ptr::create())
{
}
void hero::show_shoot(bn::color fade_color)
{
bn::sprite_palette_ptr body_palette = _body_sprite_animate_action.sprite().palette();
body_palette.set_fade(fade_color, 0.5);
_body_palette_fade_action.emplace(bn::move(body_palette), shoot_frames, 0);
bn::sprite_palette_ptr weapon_palette = _weapon_sprite.palette();
weapon_palette.set_fade(fade_color, 0.75);
_weapon_palette_fade_action.emplace(bn::move(weapon_palette), shoot_frames, 0);
if(! _show_shoot_counter)
{
_show_shoot_counter = shoot_frames * 2;
}
}
bn::optional<scene_type> hero::update(const hero_bomb& hero_bomb, const enemies& enemies,
enemy_bullets& enemy_bullets, objects& objects, background& background,
butano_background& butano_background, bn::camera_ptr& camera,
rumble_manager& rumble_manager)
{
bn::optional<scene_type> result;
if(alive())
{
bn::fixed_point old_body_position = _body_position;
bool looking_down = _looking_down;
_looking_down = enemies.hero_should_look_down(old_body_position, looking_down);
_move(camera);
bn::fixed_rect new_body_rect(_body_position, dimensions);
_animate_alive(old_body_position);
if(objects.check_hero_weapon(new_body_rect, camera))
{
[[maybe_unused]] bool level_added = _status.add_level();
BN_ASSERT(level_added, "Level add failed");
_scale_weapon_counter = scale_weapon_frames;
_weapon_sprite.set_item(bn::sprite_items::hero_weapons, _status.level());
_weapon_sprite.set_scale(2);
}
bool max_bombs_count = _status.bombs_count() == constants::max_hero_bombs;
int level = _status.level();
objects::bomb_check_result bomb_check_result =
objects.check_hero_bomb(new_body_rect, max_bombs_count, level, camera);
if(bomb_check_result.add_bomb)
{
[[maybe_unused]] bool bomb_added = _status.add_bomb();
BN_ASSERT(bomb_added, "Bomb add failed");
}
int experience_to_add = bomb_check_result.experience_to_add + objects.check_gem(new_body_rect, level, camera);
if(experience_to_add && add_experience(experience_to_add))
{
objects.spawn_hero_weapon_with_sound(bn::fixed_point(0, -constants::view_height), level + 1, camera);
}
if(_shield_counter)
{
_animate_shield(background, rumble_manager);
}
else
{
if(! hero_bomb.active())
{
if(enemies.check_hero(new_body_rect) || enemy_bullets.check_hero(new_body_rect))
{
int old_bombs_count = _status.bombs_count();
rumble_manager.set_enabled(true);
if(_status.throw_shield())
{
_show_shield(old_bombs_count, camera, background);
}
else
{
++_death_counter;
}
}
}
}
if(enemies.boss_dead())
{
if(! _stage_done)
{
butano_background.show(_weapon_sprite.position(), camera);
_stage_done = true;
}
else if(! butano_background.silhouette_visible())
{
if(_status.go_to_next_stage())
{
result = scene_type::GAME;
}
else
{
_status.update_high_experience();
_status = status();
result = scene_type::ENDING;
}
}
}
}
else
{
result = _animate_dead(camera, background, butano_background, rumble_manager);
_body_position = _body_sprite_animate_action.sprite().position();
}
return result;
}
void hero::_move(bn::camera_ptr& camera)
{
bn::sprite_ptr body_sprite = _body_sprite_animate_action.sprite();
bn::fixed speed = _shooting ? 1 : 2;
if(bn::keypad::left_held())
{
bn::fixed sprite_x = bn::max(_body_position.x() - speed, bn::fixed(-constants::play_width));
body_sprite.set_x(sprite_x);
_body_position.set_x(sprite_x);
if(sprite_x < constants::camera_width)
{
camera.set_x(bn::max(camera.x() - speed, bn::fixed(-constants::camera_width)));
}
}
else if(bn::keypad::right_held())
{
bn::fixed sprite_x = bn::min(_body_position.x() + speed, bn::fixed(constants::play_width));
body_sprite.set_x(sprite_x);
_body_position.set_x(sprite_x);
if(sprite_x > -constants::camera_width)
{
camera.set_x(bn::min(camera.x() + speed, bn::fixed(constants::camera_width)));
}
}
if(bn::keypad::up_held())
{
bn::fixed sprite_y = bn::max(_body_position.y() - speed, bn::fixed(-constants::play_height));
body_sprite.set_y(sprite_y);
_body_position.set_y(sprite_y);
}
else if(bn::keypad::down_held())
{
bn::fixed sprite_y = bn::min(_body_position.y() + speed, bn::fixed(constants::play_height));
body_sprite.set_y(sprite_y);
_body_position.set_y(sprite_y);
}
bool looking_down = _looking_down;
body_sprite.set_horizontal_flip(looking_down);
body_sprite.set_vertical_flip(looking_down);
}
void hero::_animate_alive(const bn::fixed_point& old_body_position)
{
int weapon_shift_y = 0;
if(_show_shoot_counter)
{
if(_show_shoot_counter > 5)
{
weapon_shift_y = -1;
}
--_show_shoot_counter;
}
const bn::fixed_point& new_body_position = _body_position;
bool looking_down = _looking_down;
if(looking_down)
{
_weapon_position = new_body_position + bn::fixed_point(-weapon_delta_x, -weapon_delta_y);
}
else
{
_weapon_position = new_body_position + bn::fixed_point(weapon_delta_x, weapon_delta_y);
}
_weapon_sprite.set_position(_weapon_position + bn::fixed_point(0, weapon_shift_y));
_weapon_sprite.set_horizontal_flip(looking_down);
_weapon_sprite.set_vertical_flip(looking_down);
if(! _shooting && old_body_position != new_body_position)
{
_body_sprite_animate_action.update();
}
_body_sprite_animate_action.update();
if(_body_palette_fade_action)
{
_body_palette_fade_action->update();
_weapon_palette_fade_action->update();
if(_body_palette_fade_action->done())
{
_body_palette_fade_action.reset();
_weapon_palette_fade_action.reset();
}
}
if(_scale_weapon_counter)
{
--_scale_weapon_counter;
if(_scale_weapon_counter)
{
if(_scale_weapon_counter <= scale_weapon_half_frames)
{
_weapon_sprite.set_scale(1 + (bn::fixed(_scale_weapon_counter) / scale_weapon_half_frames));
}
}
else
{
_weapon_sprite.set_scale(1);
}
}
int current_graphics_index = _body_sprite_animate_action.current_index();
int shadows_count = _body_shadows.size();
_body_snapshots.pop_back();
_body_snapshots.push_front(body_snapshot_type{ new_body_position, int16_t(current_graphics_index), looking_down });
if(_shooting)
{
_body_shadows_counter = bn::max(_body_shadows_counter - 1, 0);
}
else
{
_body_shadows_counter = bn::min(_body_shadows_counter + 1, shadows_count * body_shadows_multiplier);
}
const bn::sprite_tiles_item& body_tiles_item = _body_sprite_item.tiles_item();
int visible_shadows_count = _body_shadows_counter / body_shadows_multiplier;
for(int index = 0, limit = _body_shadows.size(); index < limit; ++index)
{
const body_snapshot_type& body_snapshot = _body_snapshots[(index + 1) * body_shadows_multiplier];
bn::sprite_ptr& body_shadow = _body_shadows[shadows_count - index - 1];
if(index >= visible_shadows_count || body_snapshot.position == new_body_position)
{
body_shadow.set_visible(false);
}
else
{
int graphics_index = ((index + 1) * 2) + body_snapshot.graphics_index;
body_shadow.set_position(body_snapshot.position);
body_shadow.set_tiles(body_tiles_item.create_tiles(graphics_index));
body_shadow.set_horizontal_flip(body_snapshot.looking_down);
body_shadow.set_vertical_flip(body_snapshot.looking_down);
body_shadow.set_visible(true);
}
}
}
void hero::_show_shield(int old_bombs_count, const bn::camera_ptr& camera, background& background)
{
bool looking_down = _looking_down;
_shield_toggle_action.emplace(_shield_sprite, 1);
_shield_rotate_action.emplace(_shield_sprite, 5);
_shield_counter = 210;
for(int index = 0; index < old_bombs_count; ++index)
{
bn::fixed x = (index % 2) ? bn::fixed(0.5) : bn::fixed(-0.5);
bn::fixed y = (index / 2) ? bn::fixed(-0.5) : bn::fixed(0.5);
bn::sprite_builder builder(bn::sprite_items::hero_bomb_icon);
builder.set_position(_body_position);
builder.set_z_order(constants::hero_shield_z_order);
builder.set_affine_mat(_bomb_sprites_affine_mat);
builder.set_camera(camera);
if(looking_down)
{
_bomb_sprite_move_actions.emplace_back(builder.release_build(), -x, -y);
}
else
{
_bomb_sprite_move_actions.emplace_back(builder.release_build(), x, y);
}
}
_bomb_sprites_affine_mat.set_rotation_angle(0);
_bomb_sprites_affine_mat.set_scale(1);
_bomb_sprites_rotate_action.emplace(_bomb_sprites_affine_mat, 4);
background.show_hero_dying();
bn::sound_items::explosion_2.play();
}
void hero::_animate_shield(background& background, rumble_manager& rumble_manager)
{
--_shield_counter;
if(int shield_counter = _shield_counter)
{
_shield_sprite.set_position(_body_position);
_shield_toggle_action->update();
_shield_rotate_action->update();
if(shield_counter > 150)
{
_bomb_sprites_rotate_action->update();
for(bn::sprite_move_by_action& bomb_sprite_move_action : _bomb_sprite_move_actions)
{
bomb_sprite_move_action.update();
}
int scale_counter = shield_counter - 150;
if(scale_counter < 30)
{
_bomb_sprites_affine_mat.set_scale(scale_counter * bn::fixed(1.0 / 30));
}
}
else if(shield_counter == 150)
{
_bomb_sprites_rotate_action.reset();
_bomb_sprite_move_actions.clear();
background.show_hero_alive();
}
else if(shield_counter == 135)
{
rumble_manager.set_enabled(false);
}
else if(shield_counter < 60)
{
_shield_sprite.set_scale(shield_counter * bn::fixed(1.0 / 60));
}
if(shield_counter % 16 == 0)
{
bn::sound_items::flame_thrower.play();
}
}
else
{
_shield_sprite.set_scale(1);
_shield_sprite.set_visible(false);
_shield_toggle_action.reset();
_shield_rotate_action.reset();
}
}
bn::optional<scene_type> hero::_animate_dead(const bn::camera_ptr& camera, background& background,
butano_background& butano_background, rumble_manager& rumble_manager)
{
bn::sprite_ptr body_sprite = _body_sprite_animate_action.sprite();
bn::optional<scene_type> result;
if(_death_counter == 1)
{
bn::sprite_palette_ptr body_palette = body_sprite.palette();
body_palette.set_fade(bn::colors::yellow, 0.75);
_body_palette_fade_action.emplace(bn::move(body_palette), 30, 0);
_body_rotate_action.emplace(body_sprite, bn::fixed(0.5));
bn::sprite_palette_ptr weapon_palette = _weapon_sprite.palette();
weapon_palette.set_fade(bn::colors::yellow, 0.75);
_weapon_palette_fade_action.emplace(bn::move(weapon_palette), 30, 0);
_weapon_sprite.set_scale(1);
_weapon_move_action.emplace(_weapon_sprite, 70, _weapon_sprite.position() + bn::fixed_point(10, -10));
_weapon_rotate_action.emplace(_weapon_sprite, -10);
_body_shadows.clear();
background.show_hero_dying();
_music_volume_action.emplace(50, 0);
bn::sound_items::boss_shoot.play();
}
else if(_death_counter == 70)
{
bn::fixed_point explosion_position = body_sprite.position() + bn::fixed_point(2, 4);
_death_explosion.emplace(bn::sprite_items::hero_death, explosion_position, 4, 0, false, camera);
_weapon_move_action.emplace(_weapon_sprite, 70, _weapon_sprite.position() + bn::fixed_point(5, -5));
_weapon_rotate_action.emplace(_weapon_sprite, -5);
background.show_hero_dead();
bn::sound_items::death.play();
}
else if(_death_counter == 100)
{
rumble_manager.set_enabled(false);
}
else if(_death_counter == 220)
{
butano_background.show(_weapon_sprite.position(), camera);
}
else if(_death_counter > 220 && ! butano_background.silhouette_visible())
{
_status.update_high_experience();
_status = status();
result = scene_type::TITLE;
}
++_death_counter;
if(_death_explosion && ! _death_explosion->done())
{
_death_explosion->update();
body_sprite.set_visible(_death_explosion->show_target_sprite());
}
if(body_sprite.visible())
{
_body_rotate_action->update();
body_sprite.set_y(body_sprite.y() + constants::background_speed);
if(_death_counter % 8 == 0)
{
body_sprite.set_x(body_sprite.x() + 2);
}
else if(_death_counter % 4 == 0)
{
body_sprite.set_x(body_sprite.x() - 2);
}
}
if(_weapon_move_action)
{
_weapon_move_action->update();
_weapon_rotate_action->update();
if(_weapon_move_action->done())
{
_weapon_move_action.reset();
_weapon_rotate_action.reset();
}
}
else
{
bn::fixed weapon_y = _weapon_sprite.y();
if(weapon_y < constants::view_height)
{
_weapon_sprite.set_y(weapon_y + constants::background_speed);
}
}
if(_body_palette_fade_action)
{
_body_palette_fade_action->update();
_weapon_palette_fade_action->update();
if(_body_palette_fade_action->done())
{
_body_palette_fade_action.reset();
_weapon_palette_fade_action.reset();
}
}
if(_music_volume_action)
{
_music_volume_action->update();
if(_music_volume_action->done())
{
_music_volume_action.reset();
}
}
return result;
}
}
| 412 | 0.917611 | 1 | 0.917611 | game-dev | MEDIA | 0.98712 | game-dev | 0.668059 | 1 | 0.668059 |
glKarin/com.n0n3m4.diii4a | 1,732 | Q3E/src/main/jni/source/common/replay/ireplayperformancerecorder.h | //========= Copyright Valve Corporation, All rights reserved. ============//
//
//=======================================================================================//
#ifndef IREPLAYPERFORMANCERECORDER_H
#define IREPLAYPERFORMANCERECORDER_H
#ifdef _WIN32
#pragma once
#endif
//----------------------------------------------------------------------------------------
#include "interface.h"
//----------------------------------------------------------------------------------------
class CReplay;
class Vector;
class QAngle;
class CReplayPerformance;
//----------------------------------------------------------------------------------------
class IReplayPerformanceRecorder : public IBaseInterface
{
public:
virtual void BeginPerformanceRecord( CReplay *pReplay ) = 0;
virtual void EndPerformanceRecord() = 0;
virtual void NotifyPauseState( bool bPaused ) = 0;
virtual CReplayPerformance *GetPerformance() = 0;
virtual bool IsRecording() const = 0;
virtual void SnipAtTime( float flTime ) = 0;
virtual void NotifySkipping() = 0;
virtual void ClearSkipping() = 0;
virtual void AddEvent_Camera_Change_FirstPerson( float flTime, int nEntityIndex ) = 0;
virtual void AddEvent_Camera_Change_ThirdPerson( float flTime, int nEntityIndex ) = 0;
virtual void AddEvent_Camera_Change_Free( float flTime ) = 0;
virtual void AddEvent_Camera_ChangePlayer( float flTime, int nEntIndex ) = 0;
virtual void AddEvent_Camera_SetView( float flTime, const Vector& origin, const QAngle &angles, float fov ) = 0;
virtual void AddEvent_Slowmo( float flTime, float flScale ) = 0;
};
//----------------------------------------------------------------------------------------
#endif // IREPLAYPERFORMANCERECORDER_H
| 412 | 0.958073 | 1 | 0.958073 | game-dev | MEDIA | 0.717819 | game-dev | 0.753125 | 1 | 0.753125 |
libretro/mame2003-libretro | 12,576 | src/vidhrdw/starcrus_vidhrdw.c |
/* Ramtek - Star Cruiser */
#include "driver.h"
#include "vidhrdw/generic.h"
static struct mame_bitmap *ship1_vid;
static struct mame_bitmap *ship2_vid;
static struct mame_bitmap *proj1_vid;
static struct mame_bitmap *proj2_vid;
static int s1_x = 0;
static int s1_y = 0;
static int s2_x = 0;
static int s2_y = 0;
static int p1_x = 0;
static int p1_y = 0;
static int p2_x = 0;
static int p2_y = 0;
static int p1_sprite = 0;
static int p2_sprite = 0;
static int s1_sprite = 0;
static int s2_sprite = 0;
static int engine1_on = 0;
static int engine2_on = 0;
static int explode1_on = 0;
static int explode2_on = 0;
static int launch1_on = 0;
static int launch2_on = 0;
/* The collision detection techniques use in this driver
are well explained in the comments in the sprint2 driver */
static int collision_reg = 0x00;
/* I hate to have sound in vidhrdw, but the sprite and
audio bits are in the same bytes, and there are so few
samples... */
int starcrus_engine_sound_playing = 0;
int starcrus_explode_sound_playing = 0;
int starcrus_launch1_sound_playing = 0;
int starcrus_launch2_sound_playing = 0;
WRITE_HANDLER( starcrus_s1_x_w ) { s1_x = data^0xff; }
WRITE_HANDLER( starcrus_s1_y_w ) { s1_y = data^0xff; }
WRITE_HANDLER( starcrus_s2_x_w ) { s2_x = data^0xff; }
WRITE_HANDLER( starcrus_s2_y_w ) { s2_y = data^0xff; }
WRITE_HANDLER( starcrus_p1_x_w ) { p1_x = data^0xff; }
WRITE_HANDLER( starcrus_p1_y_w ) { p1_y = data^0xff; }
WRITE_HANDLER( starcrus_p2_x_w ) { p2_x = data^0xff; }
WRITE_HANDLER( starcrus_p2_y_w ) { p2_y = data^0xff; }
VIDEO_START( starcrus )
{
if ((ship1_vid = auto_bitmap_alloc(16,16)) == 0)
return 1;
if ((ship2_vid = auto_bitmap_alloc(16,16)) == 0)
return 1;
if ((proj1_vid = auto_bitmap_alloc(16,16)) == 0)
return 1;
if ((proj2_vid = auto_bitmap_alloc(16,16)) == 0)
return 1;
return 0;
}
WRITE_HANDLER( starcrus_ship_parm_1_w )
{
s1_sprite = data&0x1f;
engine1_on = ((data&0x20)>>5)^0x01;
if (engine1_on || engine2_on)
{
if (starcrus_engine_sound_playing == 0)
{
starcrus_engine_sound_playing = 1;
sample_start(0,0,1); /* engine sample */
}
}
else
{
if (starcrus_engine_sound_playing == 1)
{
starcrus_engine_sound_playing = 0;
sample_stop(0);
}
}
}
WRITE_HANDLER( starcrus_ship_parm_2_w )
{
s2_sprite = data&0x1f;
set_led_status(2,~data & 0x80); /* game over lamp */
coin_counter_w(0, ((data&0x40)>>6)^0x01); /* coin counter */
engine2_on = ((data&0x20)>>5)^0x01;
if (engine1_on || engine2_on)
{
if (starcrus_engine_sound_playing == 0)
{
starcrus_engine_sound_playing = 1;
sample_start(0,0,1); /* engine sample */
}
}
else
{
if (starcrus_engine_sound_playing == 1)
{
starcrus_engine_sound_playing = 0;
sample_stop(0);
}
}
}
WRITE_HANDLER( starcrus_proj_parm_1_w )
{
p1_sprite = data&0x0f;
launch1_on = ((data&0x20)>>5)^0x01;
explode1_on = ((data&0x10)>>4)^0x01;
if (explode1_on || explode2_on)
{
if (starcrus_explode_sound_playing == 0)
{
starcrus_explode_sound_playing = 1;
sample_start(1,1,1); /* explosion initial sample */
}
}
else
{
if (starcrus_explode_sound_playing == 1)
{
starcrus_explode_sound_playing = 0;
sample_start(1,2,0); /* explosion ending sample */
}
}
if (launch1_on)
{
if (starcrus_launch1_sound_playing == 0)
{
starcrus_launch1_sound_playing = 1;
sample_start(2,3,0); /* launch sample */
}
}
else
{
starcrus_launch1_sound_playing = 0;
}
}
WRITE_HANDLER( starcrus_proj_parm_2_w )
{
p2_sprite = data&0x0f;
launch2_on = ((data&0x20)>>5)^0x01;
explode2_on = ((data&0x10)>>4)^0x01;
if (explode1_on || explode2_on)
{
if (starcrus_explode_sound_playing == 0)
{
starcrus_explode_sound_playing = 1;
sample_start(1,1,1); /* explosion initial sample */
}
}
else
{
if (starcrus_explode_sound_playing == 1)
{
starcrus_explode_sound_playing = 0;
sample_start(1,2,0); /* explosion ending sample */
}
}
if (launch2_on)
{
if (starcrus_launch2_sound_playing == 0)
{
starcrus_launch2_sound_playing = 1;
sample_start(3,3,0); /* launch sample */
}
}
else
{
starcrus_launch2_sound_playing = 0;
}
}
int starcrus_collision_check_s1s2(void)
{
int org_x, org_y;
int sx, sy;
struct rectangle clip;
clip.min_x=0;
clip.max_x=15;
clip.min_y=0;
clip.max_y=15;
fillbitmap(ship1_vid,Machine->pens[0],&clip);
fillbitmap(ship2_vid,Machine->pens[0],&clip);
/* origin is with respect to ship1 */
org_x = s1_x;
org_y = s1_y;
/* Draw ship 1 */
drawgfx(ship1_vid,
Machine->gfx[8+((s1_sprite&0x04)>>2)],
(s1_sprite&0x03)^0x03,
0,
(s1_sprite&0x08)>>3,(s1_sprite&0x10)>>4,
s1_x-org_x,s1_y-org_y,
&clip,
TRANSPARENCY_NONE,
0);
/* Draw ship 2 */
drawgfx(ship2_vid,
Machine->gfx[10+((s2_sprite&0x04)>>2)],
(s2_sprite&0x03)^0x03,
0,
(s2_sprite&0x08)>>3,(s2_sprite&0x10)>>4,
s2_x-org_x,s2_y-org_y,
&clip,
TRANSPARENCY_NONE,
0);
/* Now check for collisions */
for (sy=0;sy<16;sy++)
{
for (sx=0;sx<16;sx++)
{
if (read_pixel(ship1_vid, sx, sy)==Machine->pens[1])
{
/* Condition 1 - ship 1 = ship 2 */
if (read_pixel(ship2_vid, sx, sy)==Machine->pens[1])
return 1;
}
}
}
return 0;
}
int starcrus_collision_check_p1p2(void)
{
int org_x, org_y;
int sx, sy;
struct rectangle clip;
/* if both are scores, return */
if ( ((p1_sprite & 0x08) == 0) &&
((p2_sprite & 0x08) == 0) )
{
return 0;
}
clip.min_x=0;
clip.max_x=15;
clip.min_y=0;
clip.max_y=15;
fillbitmap(proj1_vid,Machine->pens[0],&clip);
fillbitmap(proj2_vid,Machine->pens[0],&clip);
/* origin is with respect to proj1 */
org_x = p1_x;
org_y = p1_y;
if (p1_sprite & 0x08) /* if p1 is a projectile */
{
/* Draw score/projectile 1 */
drawgfx(proj1_vid,
Machine->gfx[(p1_sprite&0x0c)>>2],
(p1_sprite&0x03)^0x03,
0,
0,0,
p1_x-org_x,p1_y-org_y,
&clip,
TRANSPARENCY_NONE,
0);
}
if (p2_sprite & 0x08) /* if p2 is a projectile */
{
/* Draw score/projectile 2 */
drawgfx(proj2_vid,
Machine->gfx[4+((p2_sprite&0x0c)>>2)],
(p2_sprite&0x03)^0x03,
0,
0,0,
p2_x-org_x,p2_y-org_y,
&clip,
TRANSPARENCY_NONE,
0);
}
/* Now check for collisions */
for (sy=0;sy<16;sy++)
{
for (sx=0;sx<16;sx++)
{
if (read_pixel(proj1_vid, sx, sy)==Machine->pens[1])
{
/* Condition 1 - proj 1 = proj 2 */
if (read_pixel(proj2_vid, sx, sy)==Machine->pens[1])
return 1;
}
}
}
return 0;
}
int starcrus_collision_check_s1p1p2(void)
{
int org_x, org_y;
int sx, sy;
struct rectangle clip;
/* if both are scores, return */
if ( ((p1_sprite & 0x08) == 0) &&
((p2_sprite & 0x08) == 0) )
{
return 0;
}
clip.min_x=0;
clip.max_x=15;
clip.min_y=0;
clip.max_y=15;
fillbitmap(ship1_vid,Machine->pens[0],&clip);
fillbitmap(proj1_vid,Machine->pens[0],&clip);
fillbitmap(proj2_vid,Machine->pens[0],&clip);
/* origin is with respect to ship1 */
org_x = s1_x;
org_y = s1_y;
/* Draw ship 1 */
drawgfx(ship1_vid,
Machine->gfx[8+((s1_sprite&0x04)>>2)],
(s1_sprite&0x03)^0x03,
0,
(s1_sprite&0x08)>>3,(s1_sprite&0x10)>>4,
s1_x-org_x,s1_y-org_y,
&clip,
TRANSPARENCY_NONE,
0);
if (p1_sprite & 0x08) /* if p1 is a projectile */
{
/* Draw projectile 1 */
drawgfx(proj1_vid,
Machine->gfx[(p1_sprite&0x0c)>>2],
(p1_sprite&0x03)^0x03,
0,
0,0,
p1_x-org_x,p1_y-org_y,
&clip,
TRANSPARENCY_NONE,
0);
}
if (p2_sprite & 0x08) /* if p2 is a projectile */
{
/* Draw projectile 2 */
drawgfx(proj2_vid,
Machine->gfx[4+((p2_sprite&0x0c)>>2)],
(p2_sprite&0x03)^0x03,
0,
0,0,
p2_x-org_x,p2_y-org_y,
&clip,
TRANSPARENCY_NONE,
0);
}
/* Now check for collisions */
for (sy=0;sy<16;sy++)
{
for (sx=0;sx<16;sx++)
{
if (read_pixel(ship1_vid, sx, sy)==Machine->pens[1])
{
/* Condition 1 - ship 1 = proj 1 */
if (read_pixel(proj1_vid, sx, sy)==Machine->pens[1])
return 1;
/* Condition 2 - ship 1 = proj 2 */
if (read_pixel(proj2_vid, sx, sy)==Machine->pens[1])
return 1;
}
}
}
return 0;
}
int starcrus_collision_check_s2p1p2(void)
{
int org_x, org_y;
int sx, sy;
struct rectangle clip;
/* if both are scores, return */
if ( ((p1_sprite & 0x08) == 0) &&
((p2_sprite & 0x08) == 0) )
{
return 0;
}
clip.min_x=0;
clip.max_x=15;
clip.min_y=0;
clip.max_y=15;
fillbitmap(ship2_vid,Machine->pens[0],&clip);
fillbitmap(proj1_vid,Machine->pens[0],&clip);
fillbitmap(proj2_vid,Machine->pens[0],&clip);
/* origin is with respect to ship2 */
org_x = s2_x;
org_y = s2_y;
/* Draw ship 2 */
drawgfx(ship2_vid,
Machine->gfx[10+((s2_sprite&0x04)>>2)],
(s2_sprite&0x03)^0x03,
0,
(s2_sprite&0x08)>>3,(s2_sprite&0x10)>>4,
s2_x-org_x,s2_y-org_y,
&clip,
TRANSPARENCY_NONE,
0);
if (p1_sprite & 0x08) /* if p1 is a projectile */
{
/* Draw projectile 1 */
drawgfx(proj1_vid,
Machine->gfx[(p1_sprite&0x0c)>>2],
(p1_sprite&0x03)^0x03,
0,
0,0,
p1_x-org_x,p1_y-org_y,
&clip,
TRANSPARENCY_NONE,
0);
}
if (p2_sprite & 0x08) /* if p2 is a projectile */
{
/* Draw projectile 2 */
drawgfx(proj2_vid,
Machine->gfx[4+((p2_sprite&0x0c)>>2)],
(p2_sprite&0x03)^0x03,
0,
0,0,
p2_x-org_x,p2_y-org_y,
&clip,
TRANSPARENCY_NONE,
0);
}
/* Now check for collisions */
for (sy=0;sy<16;sy++)
{
for (sx=0;sx<16;sx++)
{
if (read_pixel(ship2_vid, sx, sy)==Machine->pens[1])
{
/* Condition 1 - ship 2 = proj 1 */
if (read_pixel(proj1_vid, sx, sy)==Machine->pens[1])
return 1;
/* Condition 2 - ship 2 = proj 2 */
if (read_pixel(proj2_vid, sx, sy)==Machine->pens[1])
return 1;
}
}
}
return 0;
}
VIDEO_UPDATE( starcrus )
{
fillbitmap(bitmap,Machine->pens[0],&Machine->visible_area);
/* Draw ship 1 */
drawgfx(bitmap,
Machine->gfx[8+((s1_sprite&0x04)>>2)],
(s1_sprite&0x03)^0x03,
0,
(s1_sprite&0x08)>>3,(s1_sprite&0x10)>>4,
s1_x,s1_y,
&Machine->visible_area,
TRANSPARENCY_PEN,
0);
/* Draw ship 2 */
drawgfx(bitmap,
Machine->gfx[10+((s2_sprite&0x04)>>2)],
(s2_sprite&0x03)^0x03,
0,
(s2_sprite&0x08)>>3,(s2_sprite&0x10)>>4,
s2_x,s2_y,
&Machine->visible_area,
TRANSPARENCY_PEN,
0);
/* Draw score/projectile 1 */
drawgfx(bitmap,
Machine->gfx[(p1_sprite&0x0c)>>2],
(p1_sprite&0x03)^0x03,
0,
0,0,
p1_x,p1_y,
&Machine->visible_area,
TRANSPARENCY_PEN,
0);
/* Draw score/projectile 2 */
drawgfx(bitmap,
Machine->gfx[4+((p2_sprite&0x0c)>>2)],
(p2_sprite&0x03)^0x03,
0,
0,0,
p2_x,p2_y,
&Machine->visible_area,
TRANSPARENCY_PEN,
0);
/* Collision detection */
collision_reg = 0x00;
/* Check for collisions between ship1 and ship2 */
if (starcrus_collision_check_s1s2())
{
collision_reg |= 0x08;
}
/* Check for collisions between ship1 and projectiles */
if (starcrus_collision_check_s1p1p2())
{
collision_reg |= 0x02;
}
/* Check for collisions between ship1 and projectiles */
if (starcrus_collision_check_s2p1p2())
{
collision_reg |= 0x01;
}
/* Check for collisions between ship1 and projectiles */
/* Note: I don't think this is used by the game */
if (starcrus_collision_check_p1p2())
{
collision_reg |= 0x04;
}
}
READ_HANDLER( starcrus_coll_det_r )
{
return collision_reg ^ 0xff;
}
| 412 | 0.707318 | 1 | 0.707318 | game-dev | MEDIA | 0.520372 | game-dev,graphics-rendering | 0.895275 | 1 | 0.895275 |
BigWigsMods/LittleWigs | 4,897 | TBC/!Locales/zhTW.lua | -- Magisters' Terrace
local L = BigWigs:NewBossLocale("Vexallus", "zhTW")
if not L then return end
if L then
--L.energy_discharged = "%s discharged" -- %s = Pure Energy (npc ID = 24745)
end
L = BigWigs:NewBossLocale("Kael'thas Sunstrider Magisters' Terrace", "zhTW")
if L then
-- Don't look so smug! I know what you're thinking, but Tempest Keep was merely a setback. Did you honestly believe I would trust the future to some blind, half-night elf mongrel?
--L.warmup_trigger = "Don't look so smug!"
end
L = BigWigs:NewBossLocale("Magisters' Terrace Trash", "zhTW")
if L then
--L.mage_guard = "Sunblade Mage Guard"
--L.magister = "Sunblade Magister"
--L.keeper = "Sunblade Keeper"
end
-- Mana-Tombs
L = BigWigs:NewBossLocale("Mana-Tombs Trash", "zhTW")
if L then
--L.scavenger = "Ethereal Scavenger"
--L.priest = "Ethereal Priest"
--L.nexus_terror = "Nexus Terror"
--L.theurgist = "Ethereal Theurgist"
end
-- Old Hillsbrad Foothills
L = BigWigs:NewBossLocale("Old Hillsbrad Foothills Trash", "zhTW")
if L then
--L.custom_on_autotalk_desc = "Instantly select Erozion's, Thrall's and Taretha's gossip options."
--L.incendiary_bombs = "Incendiary Bombs"
--L.incendiary_bombs_desc = "Display a message when an Incendiary Bomb is planted."
end
L = BigWigs:NewBossLocale("Lieutenant Drake", "zhTW")
if L then
-- You there, fetch water quickly! Get these flames out before they spread to the rest of the keep! Hurry, damn you!
--L.warmup_trigger = "fetch water"
end
L = BigWigs:NewBossLocale("Captain Skarloc", "zhTW")
if L then
-- Thrall! You didn't really think you would escape, did you? You and your allies shall answer to Blackmoore... after I've had my fun.
--L.warmup_trigger = "answer to Blackmoore"
end
L = BigWigs:NewBossLocale("Epoch Hunter", "zhTW")
if L then
-- Ah, there you are. I had hoped to accomplish this with a bit of subtlety, but I suppose direct confrontation was inevitable. Your future, Thrall, must not come to pass and so... you and your troublesome friends must die!
--L.trash_warmup_trigger = "troublesome friends"
-- Enough, I will erase your very existence!
--L.boss_warmup_trigger = "very existence!"
end
-- The Arcatraz
L = BigWigs:NewBossLocale("Harbinger Skyriss", "zhTW")
if L then
-- I knew the prince would be angry, but I... I have not been myself. I had to let them out! The great one speaks to me, you see. Wait--outsiders. Kael'thas did not send you! Good... I'll just tell the prince you released the prisoners!
--L.first_cell_trigger = "I have not been myself"
-- Behold, yet another terrifying creature of incomprehensible power!
--L.second_and_third_cells_trigger = "of incomprehensible power"
-- Anarchy! Bedlam! Oh, you are so wise! Yes, I see it now, of course!
--L.fourth_cell_trigger = "Anarchy! Bedlam!"
-- It is a small matter to control the mind of the weak... for I bear allegiance to powers untouched by time, unmoved by fate. No force on this world or beyond harbors the strength to bend our knee... not even the mighty Legion!
--L.warmup_trigger = "the mighty Legion"
--L.prison_cell = "Prison Cell"
end
L = BigWigs:NewBossLocale("The Arcatraz Trash", "zhTW")
if L then
--L.entropic_eye = "Entropic Eye"
--L.sightless_eye = "Sightless Eye"
--L.soul_eater = "Eredar Soul-Eater"
--L.temptress = "Spiteful Temptress"
--L.abyssal = "Gargantuan Abyssal"
end
-- The Black Morass
L = BigWigs:NewBossLocale("The Black Morass Trash", "zhTW")
if L then
--L.wave = "Wave Warnings"
--L.wave_desc = "Announce approximate warning messages for the waves."
L.medivh = "麦迪文" -- zhCN?
--L.rift = "Time Rift"
end
-- The Mechanar
L = BigWigs:NewBossLocale("Pathaleon the Calculator", "zhTW")
if L then
L.despawn_message = "虚空怨灵召回,帕萨雷恩进入狂暴状态"
end
L = BigWigs:NewBossLocale("Gatewatcher Iron-Hand", "zhTW")
if L then
L.bossName = "看守者鐵手"
end
L = BigWigs:NewBossLocale("Gatewatcher Gyro-Kill", "zhTW")
if L then
L.bossName = "看守者蓋洛奇歐"
end
L = BigWigs:NewBossLocale("Nethermancer Sepethrea", "zhTW")
if L then
L.fixate_desc = "使施法者鎖定一個隨機目標。"
end
-- The Shattered Halls
L = BigWigs:NewBossLocale("The Shattered Halls Trash", "zhTW")
if L then
--L.legionnaire = "Shattered Hand Legionnaire"
--L.brawler = "Shattered Hand Brawler"
--L.acolyte = "Shadowmoon Acolyte"
--L.darkcaster = "Shadowmoon Darkcaster"
--L.assassin = "Shattered Hand Assassin"
end
-- The Slave Pens
L = BigWigs:NewBossLocale("The Slave Pens Trash", "zhTW")
if L then
--L.defender = "Coilfang Defender"
--L.enchantress = "Coilfang Enchantress"
--L.healer = "Coilfang Scale-Healer"
--L.collaborator = "Coilfang Collaborator"
--L.ray = "Coilfang Ray"
end
L = BigWigs:NewBossLocale("Ahune", "zhTW")
if L then
--L.ahune = "Ahune"
--L.warmup_trigger = "The Ice Stone has melted!"
end
-- The Steamvault
L = BigWigs:NewBossLocale("Mekgineer Steamrigger", "zhTW")
if L then
--L.mech_trigger = "Tune 'em up good, boys!"
end
| 412 | 0.547224 | 1 | 0.547224 | game-dev | MEDIA | 0.965456 | game-dev | 0.932782 | 1 | 0.932782 |
Gaby-Station/Gaby-Station | 1,740 | Content.Server/Antag/MobReplacementRuleSystem.cs | // SPDX-FileCopyrightText: 2024 Nemanja <98561806+EmoGarbage404@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 Piras314 <p1r4s@proton.me>
// SPDX-FileCopyrightText: 2024 deltanedas <39013340+deltanedas@users.noreply.github.com>
// SPDX-FileCopyrightText: 2024 deltanedas <@deltanedas:kde.org>
// SPDX-FileCopyrightText: 2024 metalgearsloth <31366439+metalgearsloth@users.noreply.github.com>
// SPDX-FileCopyrightText: 2025 Aiden <28298836+Aidenkrz@users.noreply.github.com>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
using Content.Server.Antag.Mimic;
using Content.Server.GameTicking.Rules;
using Content.Shared.GameTicking.Components;
using Content.Shared.VendingMachines;
using Robust.Shared.Map;
using Robust.Shared.Random;
namespace Content.Server.Antag;
public sealed class MobReplacementRuleSystem : GameRuleSystem<MobReplacementRuleComponent>
{
[Dependency] private readonly IRobustRandom _random = default!;
protected override void Started(EntityUid uid, MobReplacementRuleComponent component, GameRuleComponent gameRule, GameRuleStartedEvent args)
{
base.Started(uid, component, gameRule, args);
var query = AllEntityQuery<VendingMachineComponent, TransformComponent>();
var spawns = new List<(EntityUid Entity, EntityCoordinates Coordinates)>();
while (query.MoveNext(out var vendingUid, out _, out var xform))
{
if (!_random.Prob(component.Chance))
continue;
spawns.Add((vendingUid, xform.Coordinates));
}
foreach (var entity in spawns)
{
var coordinates = entity.Coordinates;
Del(entity.Entity);
Spawn(component.Proto, coordinates);
}
}
} | 412 | 0.916997 | 1 | 0.916997 | game-dev | MEDIA | 0.965026 | game-dev | 0.882539 | 1 | 0.882539 |
HyperDbg/HyperDbg | 12,885 | hwdbg/src/main/scala/hwdbg/script/set_value.scala | /**
* @file
* set_value.scala
* @author
* Sina Karvandi (sina@hyperdbg.org)
* @brief
* Script engine set value
* @details
* @version 0.1
* @date
* 2024-05-29
*
* @copyright
* This project is released under the GNU Public License v3.
*/
package hwdbg.script
import chisel3._
import chisel3.util._
import hwdbg.configs._
import hwdbg.utils._
import hwdbg.stage._
class ScriptEngineSetValue(
debug: Boolean = DebuggerConfigurations.ENABLE_DEBUG,
instanceInfo: HwdbgInstanceInformation
) extends Module {
//
// Import script data types enum
//
import hwdbg.script.ScriptConstantTypes.ScriptDataTypes
import hwdbg.script.ScriptConstantTypes.ScriptDataTypes._
val io = IO(new Bundle {
//
// Chip signals
//
val en = Input(Bool()) // chip enable signal
//
// Evaluation operator symbol
//
val operator = Input(new HwdbgShortSymbol(instanceInfo.scriptVariableLength))
//
// Input variables
//
val inputLocalGlobalVariables =
Input(Vec(instanceInfo.numberOfSupportedLocalAndGlobalVariables, UInt(instanceInfo.scriptVariableLength.W))) // Local (and Global) variables
val inputTempVariables =
Input(Vec(instanceInfo.numberOfSupportedTemporaryVariables, UInt(instanceInfo.scriptVariableLength.W))) // Temporary variables
//
// Input value
//
val inputValue = Input(UInt(instanceInfo.scriptVariableLength.W)) // input value
//
// Output signals
//
val inputPin = Input(Vec(instanceInfo.numberOfPins, UInt(1.W))) // output pins
val outputPin = Output(Vec(instanceInfo.numberOfPins, UInt(1.W))) // output pins
//
// Output variables
//
val outputLocalGlobalVariables =
Output(Vec(instanceInfo.numberOfSupportedLocalAndGlobalVariables, UInt(instanceInfo.scriptVariableLength.W))) // Local (and Global) variables
val outputTempVariables =
Output(Vec(instanceInfo.numberOfSupportedTemporaryVariables, UInt(instanceInfo.scriptVariableLength.W))) // Temporary variables
})
//
// Temp input
//
val inputLocalGlobalVariables = io.inputLocalGlobalVariables
val inputTempVariables = io.inputTempVariables
val inputPin = io.inputPin.asUInt
//
// Output pins
//
val outputPin = WireInit(0.U(instanceInfo.numberOfPins.W))
val outputLocalGlobalVariables = WireInit(
VecInit(Seq.fill(instanceInfo.numberOfSupportedLocalAndGlobalVariables)(0.U(instanceInfo.scriptVariableLength.W)))
) // Local (and Global) variables
val outputTempVariables = WireInit(
VecInit(Seq.fill(instanceInfo.numberOfSupportedTemporaryVariables)(0.U(instanceInfo.scriptVariableLength.W)))
) // Temporary variables
//
// Assign operator type (split the signal into only usable part)
//
LogInfo(debug)("Usable size of Type in the SYMBOL: " + ScriptDataTypes().getWidth)
val mainOperatorType = io.operator.Type(ScriptDataTypes().getWidth - 1, 0).asTypeOf(ScriptDataTypes())
//
// *** Implementing the setting data logic ***
//
//
// Apply the chip enable signal
//
when(io.en === true.B) {
switch(mainOperatorType) {
is(symbolUndefined) {
//
// In case of undefined SET value, just pass every input to the next step
//
outputPin := inputPin
outputLocalGlobalVariables := inputLocalGlobalVariables
outputTempVariables := inputTempVariables
}
is(symbolGlobalIdType) {
if (HwdbgScriptCapabilities.isCapabilitySupported(instanceInfo.scriptCapabilities, HwdbgScriptCapabilities.assign_local_global_var) == true) {
//
// Set the local (and global) variables
//
outputPin := inputPin
outputLocalGlobalVariables := inputLocalGlobalVariables
outputTempVariables := inputTempVariables
//
// Set the target variable
//
outputLocalGlobalVariables(io.operator.Value) := io.inputValue
}
}
is(symbolLocalIdType) {
if (HwdbgScriptCapabilities.isCapabilitySupported(instanceInfo.scriptCapabilities, HwdbgScriptCapabilities.assign_local_global_var) == true) {
//
// Set the target local/global variable
//
outputPin := inputPin
outputLocalGlobalVariables := inputLocalGlobalVariables
outputTempVariables := inputTempVariables
//
// Set the target local/global variable
//
outputLocalGlobalVariables(io.operator.Value) := io.inputValue
}
}
is(symbolRegisterType) {
if (HwdbgScriptCapabilities.isCapabilitySupported(instanceInfo.scriptCapabilities, HwdbgScriptCapabilities.assign_registers) == true) {
when(instanceInfo.numberOfPins.U > io.operator.Value) {
//
// *** Used for setting the pin value ***
//
//
// Registers are pins (set the value based on less significant bit)
//
val tempShiftedBit = (1.U << io.operator.Value)
when(io.inputValue(0) === 1.U) {
outputPin := inputPin | tempShiftedBit; // Set the N-th bit to 1
}.otherwise {
outputPin := inputPin & ~tempShiftedBit; // Clear the N-th bit to 0
}
}.otherwise {
//
// *** Used for setting the port value ***
//
//
// Iterate based on port configuration
//
var currentPortNum: Int = 0
val numPorts = instanceInfo.portsConfiguration.length
for ((port, index) <- instanceInfo.portsConfiguration.zipWithIndex) {
LogInfo(debug)(f"========================= port assignment (${index} - port size: ${port}) =========================")
when(io.operator.Value === (index + instanceInfo.numberOfPins).U) {
//
// If the current port's bit width is bigger than the script variable length,
// we need to append zero
//
val targetInputValue = WireInit(0.U(port.W))
if (port > instanceInfo.scriptVariableLength) {
//
// Since the port size is bigger than the variable size,
// we need to append zeros to the target value
//
LogInfo(debug)(
f"Appending zeros (${port - instanceInfo.scriptVariableLength}) to input variable (targetInputValue) to support port num: ${index}"
)
targetInputValue := Cat(io.inputValue, 0.U((port - instanceInfo.scriptVariableLength).W))
} else {
//
// Since the variable size is bigger than the port size,
// we need only a portion of the input value
//
targetInputValue := io.inputValue(port - 1, 0)
}
//
// Determine the range of bits to be modified
//
val high = currentPortNum + port - 1
val low = currentPortNum
// Create the modified outputPin based on whether it's the first, last or a middle port
val modifiedOutputPin = if (index == 0) {
//
// First port: keep higher bits unchanged, set lower bits to input value
//
LogInfo(debug)(
f"Set connecting index=${index} - inputPin(${instanceInfo.numberOfPins - 1}, ${high + 1}) + targetInputValue(${port - 1}, 0)"
)
Cat(
inputPin(instanceInfo.numberOfPins - 1, high + 1), // Bits above the range to keep unchanged
targetInputValue // New value for the specified range
)
} else if (index == numPorts - 1) {
//
// Last port: keep lower bits unchanged, set higher bits to input value
//
LogInfo(debug)(f"Set connecting index=${index} - targetInputValue(${port - 1}, 0) + inputPin(${low - 1}, 0)")
Cat(
targetInputValue, // New value for the specified range
inputPin(low - 1, 0) // Bits below the range to keep unchanged
)
} else {
//
// Middle port: keep both higher and lower bits unchanged
//
LogInfo(debug)(
f"Set connecting index=${index} - inputPin(${instanceInfo.numberOfPins - 1}, ${high + 1}) + targetInputValue(${port - 1}, 0) + inputPin(${low - 1}, 0)"
)
Cat(
inputPin(instanceInfo.numberOfPins - 1, high + 1), // Bits above the range to keep unchanged
targetInputValue, // New value for the specified range
inputPin(low - 1, 0) // Bits below the range to keep unchanged
)
}
//
// Assign the modified outputPin back to outputPin
//
outputPin := modifiedOutputPin
}
currentPortNum += port
}
}
outputLocalGlobalVariables := inputLocalGlobalVariables
outputTempVariables := inputTempVariables
}
}
is(symbolPseudoRegType) {
if (HwdbgScriptCapabilities.isCapabilitySupported(instanceInfo.scriptCapabilities, HwdbgScriptCapabilities.assign_pseudo_registers) == true) {
//
// To be implemented
//
outputPin := 0.U
outputLocalGlobalVariables := inputLocalGlobalVariables
outputTempVariables := inputTempVariables
}
}
is(symbolStackIndexType) {
if (HwdbgScriptCapabilities.isCapabilitySupported(instanceInfo.scriptCapabilities, HwdbgScriptCapabilities.stack_assignments) == true) {
//
// To be implemented
//
outputPin := inputPin
outputLocalGlobalVariables := inputLocalGlobalVariables
outputTempVariables := inputTempVariables
}
}
is(symbolTempType) {
if (
HwdbgScriptCapabilities.isCapabilitySupported(
instanceInfo.scriptCapabilities,
HwdbgScriptCapabilities.conditional_statements_and_comparison_operators
) == true
) {
//
// Set the temporary variables
//
outputPin := inputPin
outputLocalGlobalVariables := inputLocalGlobalVariables
outputTempVariables := inputTempVariables
//
// Set the target temporary variable
//
outputTempVariables(io.operator.Value) := io.inputValue
}
}
}
}
//
// Connect the output signals
//
io.outputLocalGlobalVariables := outputLocalGlobalVariables
io.outputTempVariables := outputTempVariables
for (i <- 0 until instanceInfo.numberOfPins) {
io.outputPin(i) := outputPin(i)
}
}
object ScriptEngineSetValue {
def apply(
debug: Boolean = DebuggerConfigurations.ENABLE_DEBUG,
instanceInfo: HwdbgInstanceInformation
)(
en: Bool,
operator: HwdbgShortSymbol,
inputLocalGlobalVariables: Vec[UInt],
inputTempVariables: Vec[UInt],
inputValue: UInt,
inputPin: Vec[UInt]
): (Vec[UInt], Vec[UInt], Vec[UInt]) = {
val scriptEngineSetValueModule = Module(
new ScriptEngineSetValue(
debug,
instanceInfo
)
)
val outputPin = Wire(Vec(instanceInfo.numberOfPins, UInt(1.W)))
val outputLocalGlobalVariables = Wire(Vec(instanceInfo.numberOfSupportedLocalAndGlobalVariables, UInt(instanceInfo.scriptVariableLength.W)))
val outputTempVariables = Wire(Vec(instanceInfo.numberOfSupportedTemporaryVariables, UInt(instanceInfo.scriptVariableLength.W)))
//
// Configure the input signals
//
scriptEngineSetValueModule.io.en := en
scriptEngineSetValueModule.io.operator := operator
scriptEngineSetValueModule.io.inputLocalGlobalVariables := inputLocalGlobalVariables
scriptEngineSetValueModule.io.inputTempVariables := inputTempVariables
scriptEngineSetValueModule.io.inputValue := inputValue
scriptEngineSetValueModule.io.inputPin := inputPin
//
// Configure the output signal
//
outputPin := scriptEngineSetValueModule.io.outputPin
outputLocalGlobalVariables := scriptEngineSetValueModule.io.outputLocalGlobalVariables
outputTempVariables := scriptEngineSetValueModule.io.outputTempVariables
//
// Return the output result
//
(
outputPin,
outputLocalGlobalVariables,
outputTempVariables
)
}
}
| 412 | 0.896985 | 1 | 0.896985 | game-dev | MEDIA | 0.30262 | game-dev | 0.946721 | 1 | 0.946721 |
swift502/Sketchbook | 4,501 | src/ts/vehicles/VehicleDoor.ts | import * as THREE from 'three';
import * as CANNON from 'cannon';
import { Vehicle } from './Vehicle';
import * as Utils from '../core/FunctionLibrary';
import { VehicleSeat } from './VehicleSeat';
import { Side } from '../enums/Side';
export class VehicleDoor
{
public vehicle: Vehicle;
public seat: VehicleSeat;
public doorObject: THREE.Object3D;
public doorVelocity: number = 0;
public doorWorldPos: THREE.Vector3 = new THREE.Vector3();
public lastTrailerPos: THREE.Vector3 = new THREE.Vector3();
public lastTrailerVel: THREE.Vector3 = new THREE.Vector3();
public rotation: number = 0;
public achievingTargetRotation: boolean = false;
public physicsEnabled: boolean = false;
public targetRotation: number = 0;
public rotationSpeed: number = 5;
public lastVehicleVel: THREE.Vector3 = new THREE.Vector3();
public lastVehiclePos: THREE.Vector3 = new THREE.Vector3();
private sideMultiplier: number;
constructor(seat: VehicleSeat, object: THREE.Object3D)
{
this.seat = seat;
this.vehicle = seat.vehicle as unknown as Vehicle;
this.doorObject = object;
const side = Utils.detectRelativeSide(this.seat.seatPointObject, this.doorObject);
if (side === Side.Left) this.sideMultiplier = -1;
else if (side === Side.Right) this.sideMultiplier = 1;
else this.sideMultiplier = 0;
}
public update(timestep: number): void
{
if (this.achievingTargetRotation)
{
if (this.rotation < this.targetRotation)
{
this.rotation += timestep * this.rotationSpeed;
if (this.rotation > this.targetRotation)
{
this.rotation = this.targetRotation;
// this.resetPhysTrailer();
this.achievingTargetRotation = false;
this.physicsEnabled = true;
}
}
else if (this.rotation > this.targetRotation)
{
this.rotation -= timestep * this.rotationSpeed;
if (this.rotation < this.targetRotation)
{
this.rotation = this.targetRotation;
// this.resetPhysTrailer();
this.achievingTargetRotation = false;
this.physicsEnabled = false;
}
}
}
this.doorObject.setRotationFromEuler(new THREE.Euler(0, this.sideMultiplier * this.rotation, 0));
}
public preStepCallback(): void
{
if (this.physicsEnabled && !this.achievingTargetRotation)
{
// Door world position
this.doorObject.getWorldPosition(this.doorWorldPos);
// Get acceleration
let vehicleVel = Utils.threeVector(this.vehicle.rayCastVehicle.chassisBody.velocity);
let vehicleVelDiff = vehicleVel.clone().sub(this.lastVehicleVel);
// Get vectors
const quat = Utils.threeQuat(this.vehicle.rayCastVehicle.chassisBody.quaternion);
const back = new THREE.Vector3(0, 0, -1).applyQuaternion(quat);
const up = new THREE.Vector3(0, 1, 0).applyQuaternion(quat);
// Get imaginary positions
let trailerPos = back.clone().applyAxisAngle(up, this.sideMultiplier * this.rotation).add(this.doorWorldPos);
let trailerPushedPos = trailerPos.clone().sub(vehicleVelDiff);
// Update last values
this.lastVehicleVel.copy(vehicleVel);
this.lastTrailerPos.copy(trailerPos);
// Measure angle difference
let v1 = trailerPos.clone().sub(this.doorWorldPos).normalize();
let v2 = trailerPushedPos.clone().sub(this.doorWorldPos).normalize();
let angle = Utils.getSignedAngleBetweenVectors(v1, v2, up);
// Apply door velocity
this.doorVelocity += this.sideMultiplier * angle * 0.05;
this.rotation += this.doorVelocity;
// Bounce door when it reaches rotation limit
if (this.rotation < 0)
{
this.rotation = 0;
if (this.doorVelocity < -0.08)
{
this.close();
this.doorVelocity = 0;
}
else
{
this.doorVelocity = -this.doorVelocity / 2;
}
}
if (this.rotation > 1)
{
this.rotation = 1;
this.doorVelocity = -this.doorVelocity / 2;
}
// Damping
this.doorVelocity = this.doorVelocity * 0.98;
}
}
public open(): void
{
// this.resetPhysTrailer();
this.achievingTargetRotation = true;
this.targetRotation = 1;
}
public close(): void
{
this.achievingTargetRotation = true;
this.targetRotation = 0;
}
public resetPhysTrailer(): void
{
// Door world position
this.doorObject.getWorldPosition(this.doorWorldPos);
// Get acceleration
this.lastVehicleVel = new THREE.Vector3();
// Get vectors
const quat = Utils.threeQuat(this.vehicle.rayCastVehicle.chassisBody.quaternion);
const back = new THREE.Vector3(0, 0, -1).applyQuaternion(quat);
this.lastTrailerPos.copy(back.add(this.doorWorldPos));
}
} | 412 | 0.880917 | 1 | 0.880917 | game-dev | MEDIA | 0.51215 | game-dev,graphics-rendering | 0.989602 | 1 | 0.989602 |
Die4Ever/deus-ex-randomizer | 4,232 | src/Augmentations/DeusEx/Classes/AugHealing.uc | #compileif injections
class BalanceAugHealing injects AugHealing;
//DXRando: put a cap on the health that regen gives you
state Active
{
Begin:
Loop:
Sleep(1.0);
if(Level5Value > 0) {
if (NeedsHeal())
HealPlayer(6); // 6 health at a time because 6 body parts
else
Deactivate();
} else {
if (Player.Health < 100)
Player.HealPlayer(Int(LevelValues[CurrentLevel]), False);
else
Deactivate();
}
Player.ClientFlash(0.5, vect(0, 0, 500));
Goto('Loop');
}
function HealPlayer(int amount) {
local int origHealAmount;
origHealAmount = amount;
while(amount > 0 && NeedsHeal()) {
HealPartOne(Player.HealthHead, amount);
HealPartOne(Player.HealthTorso, amount);
HealPartOne(Player.HealthLegRight, amount);
HealPartOne(Player.HealthLegLeft, amount);
HealPartOne(Player.HealthArmRight, amount);
HealPartOne(Player.HealthArmLeft, amount);
}
Player.GenerateTotalHealth();
amount = origHealAmount - amount;
if (amount == 1)
Player.ClientMessage(Sprintf(Player.HealedPointLabel, amount));
else if (amount > 0)
Player.ClientMessage(Sprintf(Player.HealedPointsLabel, amount));
else
Deactivate();
}
function HealPart(out int points, out int amt)
{
local int max;
max = Int(GetAugLevelValue());
HealPartMax(points, amt, max);
}
function HealPartOne(out int points, out int amt)
{
HealPartMax(points, amt, points+1);
}
function HealPartMax(out int points, out int amt, int max)
{
local int spill;
max = Min(max, Player.default.HealthTorso);
max = Min(max, GetAugLevelValue());
if(points >= max) return;
if(amt <= 0) return;
points += amt;
spill = points - max;
if (spill > 0)
points = max;
else
spill = 0;
amt = spill;
}
function bool NeedsHeal()
{
local int i;
i = Int(GetAugLevelValue());
return Player.HealthHead < Min(i, Player.default.HealthHead)
|| Player.HealthTorso < Min(i, Player.default.HealthTorso)
|| Player.HealthLegRight < Min(i, Player.default.HealthLegRight)
|| Player.HealthLegLeft < Min(i, Player.default.HealthLegLeft)
|| Player.HealthArmRight < Min(i, Player.default.HealthArmRight)
|| Player.HealthArmLeft < Min(i, Player.default.HealthArmLeft);
}
function UpdateBalance()
{
local int i;
if(class'MenuChoice_BalanceAugs'.static.IsEnabled()) {
EnergyRate = 140;
LevelValues[0] = 25;
LevelValues[1] = 40;
LevelValues[2] = 55;
LevelValues[3] = 70;
Level5Value = 90;
Description = "Programmable polymerase automatically directs construction of proteins in injured cells, restoring an agent's health over time."
$ "|n|nTECH ONE: Healing only fixes serious injuries."
$ "|n|nTECH TWO: Healing fixes moderate injuries."
$ "|n|nTECH THREE: Healing fixes most injuries."
$ "|n|nTECH FOUR: Healing restores the agent to nearly full health.";
} else {
EnergyRate = 120;
LevelValues[0] = 5;
LevelValues[1] = 15;
LevelValues[2] = 25;
LevelValues[3] = 40;
Level5Value = -1;
Description = "Programmable polymerase automatically directs construction of proteins in injured cells, restoring an agent to full health over time."
$ "|n|nTECH ONE: Healing occurs at a normal rate.|n|nTECH TWO: Healing occurs at a slightly faster rate."
$ "|n|nTECH THREE: Healing occurs at a moderately faster rate.|n|nTECH FOUR: Healing occurs at a significantly faster rate.";
}
for(i=0; i<ArrayCount(LevelValues); i++) {
default.LevelValues[i] = LevelValues[i];
}
default.EnergyRate = EnergyRate;
default.Level5Value = Level5Value;
default.Description = Description;
}
// original values go from 5 to 40, but those controlled healing rate, EnergyRate of 120
defaultproperties
{
EnergyRate=140
LevelValues(0)=25
LevelValues(1)=40
LevelValues(2)=55
LevelValues(3)=70
Level5Value=90
}
| 412 | 0.877007 | 1 | 0.877007 | game-dev | MEDIA | 0.87761 | game-dev | 0.845643 | 1 | 0.845643 |
AlexModGuy/Rats | 5,745 | src/main/java/com/github/alexthe666/rats/server/entity/mount/RatGolemMount.java | package com.github.alexthe666.rats.server.entity.mount;
import com.github.alexthe666.citadel.client.model.AdvancedModelBox;
import com.github.alexthe666.rats.registry.RatsItemRegistry;
import com.github.alexthe666.rats.server.entity.rat.AbstractRat;
import com.google.common.collect.ImmutableList;
import net.minecraft.core.BlockPos;
import net.minecraft.core.particles.BlockParticleOption;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.util.Mth;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.PathfinderMob;
import net.minecraft.world.entity.ai.attributes.AttributeSupplier;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;
public class RatGolemMount extends RatMountBase {
private int attackTimer;
public RatGolemMount(EntityType<? extends PathfinderMob> type, Level level) {
super(type, level);
this.setMaxUpStep(1.0F);
this.riderY = 1.95F;
this.riderXZ = -0.1F;
}
public static AttributeSupplier.Builder createAttributes() {
return Mob.createMobAttributes()
.add(Attributes.MAX_HEALTH, 100.0D)
.add(Attributes.MOVEMENT_SPEED, 0.2D)
.add(Attributes.ATTACK_DAMAGE, 1.0D)
.add(Attributes.KNOCKBACK_RESISTANCE, 1.0D);
}
public void aiStep() {
super.aiStep();
if (this.attackTimer > 0) {
--this.attackTimer;
}
if (this.getDeltaMovement().horizontalDistance() > (double) 2.5000003E-7F && this.getRandom().nextInt(5) == 0) {
int i = Mth.floor(this.getX());
int j = Mth.floor(this.getY() - (double) 0.2F);
int k = Mth.floor(this.getZ());
BlockState blockstate = this.level().getBlockState(new BlockPos(i, j, k));
if (!blockstate.isAir()) {
this.level().addParticle(new BlockParticleOption(ParticleTypes.BLOCK, blockstate), this.getX() + ((double) this.getRandom().nextFloat() - 0.5D) * (double) this.getBbWidth(), this.getBoundingBox().minY + 0.1D, this.getZ() + ((double) this.getRandom().nextFloat() - 0.5D) * (double) this.getBbWidth(), 4.0D * ((double) this.getRandom().nextFloat() - 0.5D), 0.5D, ((double) this.getRandom().nextFloat() - 0.5D) * 4.0D);
}
}
}
public boolean hurt(DamageSource source, float amount) {
Cracks irongolementity$cracks = this.getCracks();
boolean flag = super.hurt(source, amount);
if (flag && this.getCracks() != irongolementity$cracks) {
this.playSound(SoundEvents.IRON_GOLEM_DAMAGE, 1.0F, 1.0F);
}
return flag;
}
public InteractionResult mobInteract(Player player, InteractionHand hand) {
ItemStack stack = player.getItemInHand(hand);
if (!stack.is(Items.IRON_INGOT)) {
return super.mobInteract(player, hand);
} else {
float f = this.getHealth();
this.heal(25.0F);
if (this.getHealth() == f) {
return super.mobInteract(player, hand);
} else {
float f1 = 1.0F + (this.getRandom().nextFloat() - this.getRandom().nextFloat()) * 0.2F;
this.playSound(SoundEvents.IRON_GOLEM_REPAIR, 1.0F, f1);
if (!player.getAbilities().instabuild) {
stack.shrink(1);
}
return InteractionResult.SUCCESS;
}
}
}
public RatGolemMount.Cracks getCracks() {
return RatGolemMount.Cracks.byFraction(this.getHealth() / this.getMaxHealth());
}
public boolean doHurtTarget(Entity entity) {
this.attackTimer = 10;
this.level().broadcastEntityEvent(this, (byte) 4);
boolean flag = entity.hurt(this.damageSources().mobAttack(this), (float) (7 + this.getRandom().nextInt(15)));
if (flag) {
entity.setDeltaMovement(entity.getDeltaMovement().add(0.0D, 0.4F, 0.0D));
this.doEnchantDamageEffects(this, entity);
}
this.playSound(SoundEvents.IRON_GOLEM_ATTACK, 1.0F, 1.0F);
return flag;
}
public void handleEntityEvent(byte id) {
if (id == 4) {
this.attackTimer = 10;
this.playSound(SoundEvents.IRON_GOLEM_ATTACK, 1.0F, 1.0F);
} else {
super.handleEntityEvent(id);
}
}
protected SoundEvent getHurtSound(DamageSource damageSourceIn) {
return SoundEvents.IRON_GOLEM_HURT;
}
protected SoundEvent getDeathSound() {
return SoundEvents.IRON_GOLEM_DEATH;
}
protected void playStepSound(BlockPos pos, BlockState blockIn) {
this.playSound(SoundEvents.IRON_GOLEM_STEP, 1.0F, 1.0F);
}
public int getAttackTimer() {
return this.attackTimer;
}
@Override
public Item getUpgradeItem() {
return RatsItemRegistry.RAT_UPGRADE_GOLEM_MOUNT.get();
}
@Override
public void adjustRatTailRotation(AbstractRat rat, AdvancedModelBox upperTail, AdvancedModelBox lowerTail) {
this.progressRotation(upperTail, rat.sitProgress, -0.5F, 0.0F, 0.0F, 20.0F);
}
public enum Cracks {
NONE(1.0F),
LOW(0.75F),
MEDIUM(0.5F),
HIGH(0.25F);
private static final List<RatGolemMount.Cracks> BY_DAMAGE = Stream.of(values()).sorted(Comparator.comparingDouble(cracks -> cracks.fraction)).collect(ImmutableList.toImmutableList());
private final float fraction;
Cracks(float fraction) {
this.fraction = fraction;
}
public static RatGolemMount.Cracks byFraction(float fraction) {
for (RatGolemMount.Cracks cracks : BY_DAMAGE) {
if (fraction < cracks.fraction) {
return cracks;
}
}
return NONE;
}
}
}
| 412 | 0.862913 | 1 | 0.862913 | game-dev | MEDIA | 0.995615 | game-dev | 0.862839 | 1 | 0.862839 |
EddyRivasLab/hmmer | 3,388 | profmark/x-fps-wublast | #! /usr/bin/perl -w
# Do a piece of a profmark benchmark, for WU-BLAST searches by FPS
# (family-pairwise-search; best E-value of all individual queries).
#
# This script is normally called by pmark_master.pl; its command line
# syntax is tied to pmark_master.pl.
#
# Usage: x-wublast-fps <top_builddir> <top_srcdir> <resultdir> <tblfile> <msafile> <fafile> <outfile>
# Example: ./x-wublast-fps /usr/local/wublast ~/src/hmmer testdir test.tbl pmark.msa test.fa test.out
#
# SRE, Sat Apr 17 11:16:23 2010 [Janelia]
# SVN $Id$
BEGIN {
$top_builddir = shift;
$top_srcdir = shift;
$wrkdir = shift;
$tblfile = shift;
$msafile = shift;
$fafile = shift;
$outfile = shift;
}
use lib "${top_srcdir}/easel/demotic";
use demotic_blast;
$blastp = "${top_builddir}/blastp";
$blastopts = "cpus=1 V=9999 B=0 filter=seg filter=xnu";
if (! -d $top_builddir) { die "didn't find BLAST build directory $top_builddir"; }
if (! -d $top_srcdir) { die "didn't find H3 source directory $top_srcdir"; }
if (! -x $blastp) { die "didn't find executable $blastp"; }
if (! -e $wrkdir) { die "$wrkdir doesn't exist"; }
open(OUTFILE,">$outfile") || die "failed to open $outfile";
open(TABLE, "$tblfile") || die "failed to open $tblfile";
MSA:
while (<TABLE>)
{
($msaname) = split;
%seen = ();
%best_pval = ();
%best_bitscore = ();
`esl-afetch -o $wrkdir/$msaname.sto $msafile $msaname`;
if ($?) { print "FAILED: esl-afetch -o $wrkdir/$msaname.sto $msafile $msaname\n"; next MSA; }
# Extract a list of individual sequence names from the multiple alignment.
$output = `esl-seqstat -a $wrkdir/$msaname.sto | grep "^=" | awk '{print \$2}'`;
if ($?) { print "FAILED: esl-seqstat -a $wrkdir/$msaname.sto\n"; next MSA; }
@qnames = split(/^/,$output);
chop (@qnames);
# Loop over each query; blast; accumulate best pval for each target
QUERY:
foreach $qname (@qnames)
{
$output = `esl-sfetch -o $wrkdir/$msaname.query.fa $wrkdir/$msaname.sto $qname`;
if ($?) { print "FAILED: esl-sfetch -o $wrkdir/$msaname.query.fa $wrkdir/$msaname.sto $qname\n"; next QUERY; }
if (! open(BLASTP, "$blastp $fafile $wrkdir/$msaname.query.fa $blastopts |")) {
print "FAILED: $blastp $fafile $wrkdir/$msaname.query.fa $blastopts |\n"; next QUERY;
}
if (! demotic_blast::parse(\*BLASTP)) {
print "FAILED: demotic parser for blastp output; query might be x'ed by filters; skipping this query\n"; next QUERY;
}
for ($i = 0; $i < $demotic_blast::nhits; $i++)
{
$target = $demotic_blast::hit_target[$i];
$pval = $demotic_blast::hit_Eval[$i];
$bitscore = $demotic_blast::hit_bitscore[$i];
if (! $seen{$target} || $pval < $best_pval{$target})
{
$seen{$target} = 1;
$best_pval{$target} = $pval;
$best_bitscore{$target} = $bitscore;
}
}
close BLASTP;
}
# Append to the outfile.
foreach $target (keys(%seen))
{
printf OUTFILE "%g %.1f %s %s\n", $best_pval{$target}, $best_bitscore{$target}, $target, $msaname;
}
unlink "$wrkdir/$msaname.sto";
unlink "$wrkdir/$msaname.query.fa";
}
close TABLE;
close OUTFILE;
| 412 | 0.946 | 1 | 0.946 | game-dev | MEDIA | 0.285065 | game-dev | 0.885799 | 1 | 0.885799 |
cncgoko/Goko | 5,059 | org.goko.controller.grbl.v09/fragments/GrblFragment.e4xmi | <?xml version="1.0" encoding="ASCII"?>
<fragment:ModelFragments xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:commands="http://www.eclipse.org/ui/2010/UIModel/application/commands" xmlns:fragment="http://www.eclipse.org/ui/2010/UIModel/fragment" xmlns:menu="http://www.eclipse.org/ui/2010/UIModel/application/ui/menu" xmlns:ui="http://www.eclipse.org/ui/2010/UIModel/application/ui" xmi:id="_5BW8oPPKEeOJp_-s_mlAUA">
<fragments xsi:type="fragment:StringModelFragment" xmi:id="_6oU6cPPKEeOJp_-s_mlAUA" featurename="children" parentElementId="goko.menu.tools" positionInList="">
<elements xsi:type="menu:Menu" xmi:id="_9Dac0PPKEeOJp_-s_mlAUA" elementId="org.goko.controller.grbl.v09.menu.0" label="Grbl">
<visibleWhen xsi:type="ui:CoreExpression" xmi:id="_iamhgDVmEeWwQZbApVM4lA" coreExpressionId="org.goko.targetboard.grbl.v09"/>
<children xsi:type="menu:HandledMenuItem" xmi:id="_E55i0N4pEeSgkc4P43h1Kw" elementId="org.goko.controller.grbl.v09.handledmenuitem.activePolling" label="Active polling" type="Check" command="_6u_OAN4oEeSgkc4P43h1Kw"/>
<children xsi:type="menu:HandledMenuItem" xmi:id="_ZOPiUDaoEeWPlfi1OCrE0Q" elementId="org.goko.controller.grbl.v09.handledmenuitem.checkMode" label="Check mode" type="Check" command="_gBNqYAL0EeWNAc6kezL54A"/>
<children xsi:type="menu:MenuSeparator" xmi:id="_GTqyIN4pEeSgkc4P43h1Kw" elementId="org.goko.controller.grbl.v09.menuseparator.0"/>
<children xsi:type="menu:HandledMenuItem" xmi:id="_-R7eYPPKEeOJp_-s_mlAUA" elementId="org.goko.controller.grbl.v09.handledmenuitem.configuration" label="Grbl Configuration" command="_CCEIIPPLEeOJp_-s_mlAUA"/>
</elements>
</fragments>
<fragments xsi:type="fragment:StringModelFragment" xmi:id="_AuQ98PPLEeOJp_-s_mlAUA" featurename="commands" parentElementId="goko.application">
<elements xsi:type="commands:Command" xmi:id="_CCEIIPPLEeOJp_-s_mlAUA" elementId="org.goko.controller.grbl.v09.command.configuration" commandName="Grbl Settings" description="Open Grbl settings panel" category="_xwrgQAH6EeeZSvWBWfFcHg"/>
<elements xsi:type="commands:Command" xmi:id="_6u_OAN4oEeSgkc4P43h1Kw" elementId="org.goko.controller.grbl.v09.command.toggleActivePolling" commandName="Toggle Active Polling" category="_xwrgQAH6EeeZSvWBWfFcHg"/>
<elements xsi:type="commands:Command" xmi:id="_gBNqYAL0EeWNAc6kezL54A" elementId="org.goko.controller.grbl.v09.command.toggleCheckMode" commandName="Toggle Check mode" category="_xwrgQAH6EeeZSvWBWfFcHg"/>
<elements xsi:type="commands:Command" xmi:id="_zdK3cAPeEeWX6eDFOGSLJw" elementId="org.goko.controller.grbl.v09.command.stateWatcher" commandName="GRBL State watcher command">
<tags>system</tags>
</elements>
<elements xsi:type="commands:Command" xmi:id="_tqnT8LW1Eea3eO03IRlhpg" elementId="org.goko.controller.grbl.v09.command.grblconfigurationwatcher" commandName="GRBL configuration watcher">
<tags>system</tags>
</elements>
</fragments>
<fragments xsi:type="fragment:StringModelFragment" xmi:id="_F160QPPLEeOJp_-s_mlAUA" featurename="handlers" parentElementId="goko.application">
<elements xsi:type="commands:Handler" xmi:id="_HaDggPPLEeOJp_-s_mlAUA" elementId="org.goko.controller.grbl.v09.handler.openGrblSettings" contributionURI="bundleclass://org.goko.controller.grbl.v09/org.goko.controller.grbl.v09.internal.handlers.GrblConfigurationOpenHandler" command="_CCEIIPPLEeOJp_-s_mlAUA"/>
<elements xsi:type="commands:Handler" xmi:id="_8UWpUN4oEeSgkc4P43h1Kw" elementId="org.goko.controller.grbl.v09.handler.toggleActivePolling" contributionURI="bundleclass://org.goko.controller.grbl.v09/org.goko.controller.grbl.v09.internal.handlers.GrblActivePollingHandler" command="_6u_OAN4oEeSgkc4P43h1Kw"/>
<elements xsi:type="commands:Handler" xmi:id="_fLuz4AL0EeWNAc6kezL54A" elementId="org.goko.controller.grbl.v09.handler.toggleCheckMode" contributionURI="bundleclass://org.goko.controller.grbl.v09/org.goko.controller.grbl.v09.internal.handlers.GrblCheckModeHandler" command="_gBNqYAL0EeWNAc6kezL54A"/>
<elements xsi:type="commands:Handler" xmi:id="_74214APUEeWX6eDFOGSLJw" elementId="org.goko.controller.grbl.v09.handler.stateupdate" contributionURI="bundleclass://org.goko.controller.grbl.v09/org.goko.controller.grbl.v09.internal.handlers.GrblStateUpdateHandler" command="_zdK3cAPeEeWX6eDFOGSLJw"/>
<elements xsi:type="commands:Handler" xmi:id="_qbGD8LW1Eea3eO03IRlhpg" elementId="org.goko.controller.grbl.v09.handler.grblConfigurationWatcher" contributionURI="bundleclass://org.goko.controller.grbl.v09/org.goko.controller.grbl.v09.handlers.GrblConfigurationWatcherHandler" command="_tqnT8LW1Eea3eO03IRlhpg"/>
</fragments>
<fragments xsi:type="fragment:StringModelFragment" xmi:id="_wGUQMAH6EeeZSvWBWfFcHg" featurename="categories" parentElementId="goko.application">
<elements xsi:type="commands:Category" xmi:id="_xwrgQAH6EeeZSvWBWfFcHg" elementId="org.goko.controller.grbl.v09.category.grbl" name="Grbl"/>
</fragments>
</fragment:ModelFragments>
| 412 | 0.900714 | 1 | 0.900714 | game-dev | MEDIA | 0.646551 | game-dev,desktop-app | 0.728064 | 1 | 0.728064 |
FancyInnovations/FancyPlugins | 2,997 | plugins/fancynpcs/implementation_1_21_4/src/main/java/de/oliver/fancynpcs/v1_21_4/attributes/CatAttributes.java | package de.oliver.fancynpcs.v1_21_4.attributes;
import de.oliver.fancynpcs.api.Npc;
import de.oliver.fancynpcs.api.NpcAttribute;
import de.oliver.fancynpcs.v1_21_4.ReflectionHelper;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.animal.Cat;
import net.minecraft.world.item.DyeColor;
import org.bukkit.entity.EntityType;
import java.util.ArrayList;
import java.util.List;
public class CatAttributes {
public static List<NpcAttribute> getAllAttributes() {
List<NpcAttribute> attributes = new ArrayList<>();
attributes.add(new NpcAttribute(
"variant",
BuiltInRegistries.CAT_VARIANT.keySet().stream().map(ResourceLocation::getPath).toList(),
List.of(EntityType.CAT),
CatAttributes::setVariant
));
attributes.add(new NpcAttribute(
"pose",
List.of("standing", "sleeping", "sitting"),
List.of(EntityType.CAT),
CatAttributes::setPose
));
attributes.add(new NpcAttribute(
"collar_color",
List.of("RED", "BLUE", "YELLOW", "GREEN", "PURPLE", "ORANGE", "LIME", "MAGENTA", "BROWN", "WHITE", "GRAY", "LIGHT_GRAY", "LIGHT_BLUE", "BLACK", "CYAN", "PINK", "NONE"),
List.of(EntityType.CAT),
CatAttributes::setCollarColor
));
return attributes;
}
private static void setVariant(Npc npc, String value) {
final Cat cat = ReflectionHelper.getEntity(npc);
BuiltInRegistries.CAT_VARIANT.get(ResourceLocation.parse(value.toLowerCase()))
.ifPresent(cat::setVariant);
}
private static void setPose(Npc npc, String value) {
final Cat cat = ReflectionHelper.getEntity(npc);
switch (value.toLowerCase()) {
case "standing" -> {
cat.setInSittingPose(false, false);
cat.setLying(false);
}
case "sleeping" -> {
cat.setInSittingPose(false, false);
cat.setLying(true);
}
case "sitting" -> {
cat.setLying(false);
cat.setOrderedToSit(true);
cat.setInSittingPose(true, false);
}
}
}
private static void setCollarColor(Npc npc, String value) {
Cat cat = ReflectionHelper.getEntity(npc);
if (value.equalsIgnoreCase("none") || value.isEmpty()) {
// Reset to no collar
cat.setTame(false, false);
return;
}
try {
DyeColor color = DyeColor.valueOf(value.toUpperCase());
if (!cat.isTame()){
cat.setTame(true, false);
}
cat.setCollarColor(color);
} catch (IllegalArgumentException e) {
System.out.println("Invalid cat collar color: " + value);
}
}
}
| 412 | 0.924906 | 1 | 0.924906 | game-dev | MEDIA | 0.937177 | game-dev | 0.943567 | 1 | 0.943567 |
agraef/purr-data | 11,099 | externals/moocow/weightmap/src/weightmap.c | /* -*- Mode: C -*- */
/*=============================================================================*\
* File: weightmap.c
* Author: Bryan Jurish <moocow@ling.uni-potsdam.de>
* Description: gui-less finer-grained probability-to-integer-map for PD
*
* - inspired in part by Yves Degoyon's 'probalizer' object
*
* Copyright (c) 2002-2009 Bryan Jurish.
*
* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution.
*
* 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.
*
* See file LICENSE for further informations on licensing terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*=============================================================================*/
#include <m_pd.h>
#include <math.h>
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "mooPdUtils.h"
/*--------------------------------------------------------------------
* DEBUG
*--------------------------------------------------------------------*/
//#define WEIGHTMAP_DEBUG 1
/*=====================================================================
* Constants
*=====================================================================*/
#define DEFAULT_WEIGHT_VALUE 0
#define DEFAULT_WEIGHT_MAX 100
/*=====================================================================
* Structures and Types
*=====================================================================*/
static char *weightmap_banner =
"\n"
"weightmap: stochastic selection v" PACKAGE_VERSION " by Bryan Jurish\n"
"weightmap: compiled by " PACKAGE_BUILD_USER " on " PACKAGE_BUILD_DATE "";
static t_class *weightmap_class;
typedef struct _weightmap
{
t_object x_obj; /* black magic (probably inheritance-related) */
t_float x_wmax; /* maximum expected input weight */
t_int x_nvalues; /* number of stored values */
t_float *x_weights; /* weight of each event (0..x_wmax) */
t_float x_wsum; /* sum of all weights (internal use only) */
t_outlet *x_dumpoutlet; /* outlet for 'dump' messages */
} t_weightmap;
/*--------------------------------------------------------------------
* FLOAT : the guts : handle incoming weights
*--------------------------------------------------------------------*/
void weightmap_float(t_weightmap *x, t_floatarg f) {
int i;
float wt;
// scale weight from (0..x->x_wmax) to (0..x->x_wsum)
wt = (f * x->x_wsum) / x->x_wmax;
#ifdef WEIGHTMAP_DEBUG
post("weightmap_debug : float : rescale(%f : 0..%f) = %f : 0..%f", f, x->x_wmax, wt, x->x_wsum);
#endif
// find match
for (i = 0; i < x->x_nvalues; i++) {
wt -= x->x_weights[i];
if (wt < 0) {
// end of search : outlet current index (counting from 1, for compatibility)
outlet_float(x->x_obj.ob_outlet, i+1);
return;
}
}
// no matching value found: ouput 0
outlet_float(x->x_obj.ob_outlet, 0);
}
/*--------------------------------------------------------------------
* map : set selected values (no resize)
*--------------------------------------------------------------------*/
void weightmap_map(t_weightmap *x, MOO_UNUSED t_symbol *s, int argc, t_atom *argv) {
int i, idx;
float wt;
#ifdef WEIGHTMAP_DEBUG
post("weightmap_debug : map : argc=%d", argc);
#endif
for (i = 0; i < argc; i += 2) {
// get index
idx = atom_getint(argv+i);
if (idx <= 0 || idx > x->x_nvalues) {
// sanity check: index-range
pd_error(x,"weightmap : map : index out of range : %d", idx);
continue;
}
idx--;
// get weight-value
wt = atom_getfloatarg(i+1, argc, argv);
// adjust sum
x->x_wsum += wt - x->x_weights[idx];
// assign weight
x->x_weights[idx] = wt;
}
}
/*--------------------------------------------------------------------
* zero : zero the weight-vector
*--------------------------------------------------------------------*/
void weightmap_zero(t_weightmap *x) {
int i;
// zero all weights
for (i = 0; i < x->x_nvalues; i++) {
*(x->x_weights+i) = 0;
}
// reset sum
x->x_wsum = 0;
}
/*--------------------------------------------------------------------
* set : set the entire weight-vector in one go (with possible resize)
*--------------------------------------------------------------------*/
void weightmap_set(t_weightmap *x, MOO_UNUSED t_symbol *s, int argc, t_atom *argv) {
int i;
if (x->x_nvalues != argc) {
// set number of elements
x->x_nvalues = argc;
if ( x->x_nvalues < 1 ) x->x_nvalues = 1;
// (re-)allocate weights
if (x->x_weights) {
freebytes(x->x_weights, x->x_nvalues*sizeof(t_float));
}
x->x_weights = (t_float *)getbytes(x->x_nvalues*sizeof(t_float));
if (!x->x_weights) {
pd_error(x,"weightmap : failed to allocate new weight vector");
return;
}
}
// zero sum
x->x_wsum = 0;
// assign new weight-vector
for (i = 0; i < x->x_nvalues; i++) {
if (i >= argc) {
// sanity check: existence
x->x_weights[i] = DEFAULT_WEIGHT_VALUE;
}
else {
// normal case: set weight value
x->x_weights[i] = atom_getfloat(argv);
}
x->x_wsum += x->x_weights[i];
argv++;
}
}
/*--------------------------------------------------------------------
* resize : reset number of values & re-allocate
*--------------------------------------------------------------------*/
void weightmap_resize(t_weightmap *x, t_floatarg f) {
int i;
t_int old_nvalues = x->x_nvalues;
t_float *old_weights = x->x_weights;
#ifdef WEIGHTMAP_DEBUG
post("weightmap_debug : resize : size=%d", (int)f);
#endif
// reset number of elements
x->x_nvalues = f;
if ( x->x_nvalues < 1 ) x->x_nvalues = 1;
// allocate new weight-vector
x->x_weights = (t_float *)getbytes(x->x_nvalues*sizeof(t_float));
if (!x->x_weights) {
pd_error(x,"weightmap : resize : failed to allocate new weight vector");
return;
}
// zero sum
x->x_wsum = 0;
// copy old values
for (i = 0; i < x->x_nvalues; i++) {
if (i >= old_nvalues) {
x->x_weights[i] = DEFAULT_WEIGHT_VALUE;
} else {
x->x_weights[i] = old_weights[i];
x->x_wsum += old_weights[i];
}
}
// free old vector
freebytes(old_weights, old_nvalues*sizeof(t_float));
}
/*--------------------------------------------------------------------
* max : set maximum expected input-weight
*--------------------------------------------------------------------*/
void weightmap_max(t_weightmap *x, t_floatarg f) {
#ifdef WEIGHTMAP_DEBUG
post("weightmap_debug : max : max=%f", f);
#endif
if (f > 0) {
x->x_wmax = f;
} else {
pd_error(x,"weightmap : invalid maximum weight : %f", f);
}
}
/*--------------------------------------------------------------------
* dump : outputs weight-vector as a list
*--------------------------------------------------------------------*/
void weightmap_dump(t_weightmap *x) {
int i;
float f;
t_atom *dumpus;
#ifdef WEIGHTMAP_DEBUG
post("weightmap_debug : dump : sum=%f, max=%f", x->x_wsum, x->x_wmax);
#endif
// allocate dump-list
dumpus = (t_atom *)getbytes(x->x_nvalues*sizeof(t_atom));
if (!dumpus) {
pd_error(x,"weightmap : failed to allocate dump list");
return;
}
// populate dump-list
for (i = 0; i < x->x_nvalues; i++) {
f = x->x_weights[i];
SETFLOAT(dumpus+i, f);
}
// output dump-list
outlet_list(x->x_dumpoutlet,
&s_list,
x->x_nvalues,
dumpus);
}
/*--------------------------------------------------------------------
* new SIZE
*--------------------------------------------------------------------*/
static void *weightmap_new(t_floatarg f, t_floatarg max)
{
t_weightmap *x;
int i;
x = (t_weightmap *)pd_new(weightmap_class);
// create float (index) outlet
outlet_new(&x->x_obj, &s_float);
// create list (dump) outlet
x->x_dumpoutlet = outlet_new(&x->x_obj, &s_list);
// set number of elements
x->x_nvalues = f;
if ( x->x_nvalues < 1 ) x->x_nvalues = 1;
// set maximum expected input probability
x->x_wmax = max;
if (!x->x_wmax) x->x_wmax = DEFAULT_WEIGHT_MAX;
// allocate weight-vector
x->x_weights = (t_float *)getbytes(x->x_nvalues*sizeof(t_float));
if (!x->x_weights) {
pd_error(x,"weightmap : failed to allocate weight vector");
return NULL;
}
// initialize weights
for (i = 0; i < x->x_nvalues; i++) {
*(x->x_weights+i) = DEFAULT_WEIGHT_VALUE;
}
// initialize sum
x->x_wsum = DEFAULT_WEIGHT_VALUE * x->x_nvalues;
#ifdef WEIGHTMAP_DEBUG
post("weightmap_debug : create : nvalues=%d , wmax=%f", x->x_nvalues, x->x_wmax);
#endif
return (void *)x;
}
/*--------------------------------------------------------------------
* free
*--------------------------------------------------------------------*/
static void weightmap_free(t_weightmap *x) {
#ifdef WEIGHTMAP_DEBUG
post("weightmap_debug : free");
#endif
if (x->x_weights) {
freebytes(x->x_weights, x->x_nvalues*sizeof(t_float));
}
}
/*--------------------------------------------------------------------
* setup
*--------------------------------------------------------------------*/
void weightmap_setup(void) {
post(weightmap_banner);
weightmap_class = class_new(gensym("weightmap"), /* name */
(t_newmethod)weightmap_new, /* newmethod */
(t_method)weightmap_free, /* freemethod */
sizeof(t_weightmap), /* size */
0, /* flags */
A_DEFFLOAT, /* ARGLIST: arg1 (size) */
A_DEFFLOAT, /* ARGLIST: arg2 (max) */
0); /* ARGLIST: END */
class_addmethod(weightmap_class, (t_method)weightmap_float, &s_float, A_FLOAT, 0);
class_addmethod(weightmap_class, (t_method)weightmap_map, gensym("map"), A_GIMME, 0);
class_addmethod(weightmap_class, (t_method)weightmap_zero, gensym("zero"), 0);
class_addmethod(weightmap_class, (t_method)weightmap_set, gensym("set"), A_GIMME, 0);
class_addmethod(weightmap_class, (t_method)weightmap_resize, gensym("resize"), A_DEFFLOAT, 0);
class_addmethod(weightmap_class, (t_method)weightmap_max, gensym("max"), A_DEFFLOAT, 0);
class_addmethod(weightmap_class, (t_method)weightmap_dump, gensym("dump"), 0);
class_sethelpsymbol(weightmap_class, gensym("weightmap-help.pd"));
}
| 412 | 0.950094 | 1 | 0.950094 | game-dev | MEDIA | 0.386065 | game-dev | 0.989999 | 1 | 0.989999 |
Secrets-of-Sosaria/World | 1,091 | Data/Scripts/Items/Magical/Gifts/Shields/GiftElvenShield.cs | using System;
using Server;
namespace Server.Items
{
public class GiftElvenShield : BaseGiftShield
{
public override int BasePhysicalResistance{ get{ return 0; } }
public override int BaseFireResistance{ get{ return 1; } }
public override int BaseColdResistance{ get{ return 0; } }
public override int BasePoisonResistance{ get{ return 0; } }
public override int BaseEnergyResistance{ get{ return 0; } }
public override int InitMinHits{ get{ return 50; } }
public override int InitMaxHits{ get{ return 65; } }
public override int AosStrReq{ get{ return 90; } }
public override int ArmorBase{ get{ return 23; } }
[Constructable]
public GiftElvenShield() : base( 0x2FCA )
{
Name = "elven shield";
Weight = 8.0;
}
public GiftElvenShield( Serial serial ) : base(serial)
{
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int)0 );//version
}
}
}
| 412 | 0.878815 | 1 | 0.878815 | game-dev | MEDIA | 0.614013 | game-dev | 0.638216 | 1 | 0.638216 |
SkinsRestorer/SkinsRestorer | 2,635 | shared/src/main/java/net/skinsrestorer/shared/commands/library/PlayerSelector.java | /*
* SkinsRestorer
* Copyright (C) 2024 SkinsRestorer Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.skinsrestorer.shared.commands.library;
import net.skinsrestorer.shared.plugin.SRPlatformAdapter;
import net.skinsrestorer.shared.subjects.SRCommandSender;
import net.skinsrestorer.shared.subjects.SRPlayer;
import net.skinsrestorer.shared.utils.SRHelpers;
import java.util.*;
public record PlayerSelector(Collection<Resolvable> toResolve) {
public static PlayerSelector singleton(SRPlayer player) {
return new PlayerSelector(List.of(new Player(player)));
}
public Collection<UUID> resolve(SRCommandSender commandSender) {
Set<UUID> resolvedPlayers = new LinkedHashSet<>();
for (Resolvable resolvable : toResolve) {
resolvedPlayers.addAll(resolvable.resolve(commandSender));
}
return resolvedPlayers;
}
public enum SelectorType {
ALL_PLAYERS,
RANDOM_PLAYER
}
public interface Resolvable {
Collection<UUID> resolve(SRCommandSender commandSender);
}
public record Player(SRPlayer player) implements Resolvable {
@Override
public Collection<UUID> resolve(SRCommandSender commandSender) {
return List.of(player.getUniqueId());
}
}
public record UniqueId(UUID uniqueId) implements Resolvable {
@Override
public Collection<UUID> resolve(SRCommandSender commandSender) {
return List.of(uniqueId);
}
}
public record Selector(SRPlatformAdapter platform, SelectorType type) implements Resolvable {
@Override
public Collection<UUID> resolve(SRCommandSender commandSender) {
return switch (type) {
case ALL_PLAYERS -> platform.getOnlinePlayers(commandSender).stream().map(SRPlayer::getUniqueId).toList();
case RANDOM_PLAYER -> List.of(SRHelpers.getRandomEntry(platform.getOnlinePlayers(commandSender)).getUniqueId());
};
}
}
}
| 412 | 0.810655 | 1 | 0.810655 | game-dev | MEDIA | 0.561162 | game-dev | 0.522889 | 1 | 0.522889 |
Catacomb-Snatch/Catacomb-Snatch | 16,468 | Library/PackageCache/com.unity.textmeshpro@2.0.1/Scripts/Editor/TMP_GlyphPairAdjustmentRecordPropertyDrawer.cs | using UnityEngine;
using UnityEngine.TextCore;
using UnityEngine.TextCore.LowLevel;
using UnityEditor;
using System.Collections;
using System.Text.RegularExpressions;
namespace TMPro.EditorUtilities
{
[CustomPropertyDrawer(typeof(TMP_GlyphPairAdjustmentRecord))]
public class TMP_GlyphPairAdjustmentRecordPropertyDrawer : PropertyDrawer
{
private bool isEditingEnabled = false;
private bool isSelectable = false;
private string m_FirstCharacter = string.Empty;
private string m_SecondCharacter = string.Empty;
private string m_PreviousInput;
static GUIContent s_CharacterTextFieldLabel = new GUIContent("Char:", "Enter the character or its UTF16 or UTF32 Unicode character escape sequence. For UTF16 use \"\\uFF00\" and for UTF32 use \"\\UFF00FF00\" representation.");
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
SerializedProperty prop_FirstAdjustmentRecord = property.FindPropertyRelative("m_FirstAdjustmentRecord");
SerializedProperty prop_SecondAdjustmentRecord = property.FindPropertyRelative("m_SecondAdjustmentRecord");
SerializedProperty prop_FirstGlyphIndex = prop_FirstAdjustmentRecord.FindPropertyRelative("m_GlyphIndex");
SerializedProperty prop_FirstGlyphValueRecord = prop_FirstAdjustmentRecord.FindPropertyRelative("m_GlyphValueRecord");
SerializedProperty prop_SecondGlyphIndex = prop_SecondAdjustmentRecord.FindPropertyRelative("m_GlyphIndex");
SerializedProperty prop_SecondGlyphValueRecord = prop_SecondAdjustmentRecord.FindPropertyRelative("m_GlyphValueRecord");
SerializedProperty prop_FontFeatureLookupFlags = property.FindPropertyRelative("m_FeatureLookupFlags");
position.yMin += 2;
float width = position.width / 2;
float padding = 5.0f;
Rect rect;
isEditingEnabled = GUI.enabled;
isSelectable = label.text == "Selectable" ? true : false;
if (isSelectable)
GUILayoutUtility.GetRect(position.width, 75);
else
GUILayoutUtility.GetRect(position.width, 55);
GUIStyle style = new GUIStyle(EditorStyles.label);
style.richText = true;
// First Glyph
GUI.enabled = isEditingEnabled;
if (isSelectable)
{
rect = new Rect(position.x + 70, position.y, position.width, 49);
float labelWidth = GUI.skin.label.CalcSize(new GUIContent("ID: " + prop_FirstGlyphIndex.intValue)).x;
EditorGUI.LabelField(new Rect(position.x + (64 - labelWidth) / 2, position.y + 60, 64f, 18f), new GUIContent("ID: <color=#FFFF80>" + prop_FirstGlyphIndex.intValue + "</color>"), style);
GUI.enabled = isEditingEnabled;
EditorGUIUtility.labelWidth = 30f;
rect = new Rect(position.x + 70, position.y + 10, (width - 70) - padding, 18);
EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_XPlacement"), new GUIContent("OX:"));
rect.y += 20;
EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_YPlacement"), new GUIContent("OY:"));
rect.y += 20;
EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_XAdvance"), new GUIContent("AX:"));
//rect.y += 20;
//EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_YAdvance"), new GUIContent("AY:"));
DrawGlyph((uint)prop_FirstGlyphIndex.intValue, new Rect(position.x, position.y, position.width, position.height), property);
}
else
{
rect = new Rect(position.x, position.y, width / 2 * 0.8f - padding, 18);
EditorGUIUtility.labelWidth = 40f;
// First Character Lookup
GUI.SetNextControlName("FirstCharacterField");
EditorGUI.BeginChangeCheck();
string firstCharacter = EditorGUI.TextField(rect, s_CharacterTextFieldLabel, m_FirstCharacter);
if (GUI.GetNameOfFocusedControl() == "FirstCharacterField")
{
if (ValidateInput(firstCharacter))
{
//Debug.Log("1st Unicode value: [" + firstCharacter + "]");
uint unicode = GetUnicodeCharacter(firstCharacter);
// Lookup glyph index
TMP_SerializedPropertyHolder propertyHolder = property.serializedObject.targetObject as TMP_SerializedPropertyHolder;
TMP_FontAsset fontAsset = propertyHolder.fontAsset;
if (fontAsset != null)
{
prop_FirstGlyphIndex.intValue = (int)fontAsset.GetGlyphIndex(unicode);
propertyHolder.firstCharacter = unicode;
}
}
}
if (EditorGUI.EndChangeCheck())
m_FirstCharacter = firstCharacter;
// First Glyph Index
rect.x += width / 2 * 0.8f;
EditorGUIUtility.labelWidth = 25f;
EditorGUI.BeginChangeCheck();
EditorGUI.PropertyField(rect, prop_FirstGlyphIndex, new GUIContent("ID:"));
if (EditorGUI.EndChangeCheck())
{
}
GUI.enabled = isEditingEnabled;
EditorGUIUtility.labelWidth = 25f;
rect = new Rect(position.x, position.y + 20, width * 0.5f - padding, 18);
EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_XPlacement"), new GUIContent("OX"));
rect.x += width * 0.5f;
EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_YPlacement"), new GUIContent("OY"));
rect.x = position.x;
rect.y += 20;
EditorGUI.PropertyField(rect, prop_FirstGlyphValueRecord.FindPropertyRelative("m_XAdvance"), new GUIContent("AX"));
//rect.x += width * 0.5f;
//EditorGUI.PropertyField(rect, prop_FirstGlyphAdjustment.FindPropertyRelative("m_YAdvance"), new GUIContent("AY"));
}
// Second Glyph
GUI.enabled = isEditingEnabled;
if (isSelectable)
{
float labelWidth = GUI.skin.label.CalcSize(new GUIContent("ID: " + prop_SecondGlyphIndex.intValue)).x;
EditorGUI.LabelField(new Rect(position.width / 2 + 20 + (64 - labelWidth) / 2, position.y + 60, 64f, 18f), new GUIContent("ID: <color=#FFFF80>" + prop_SecondGlyphIndex.intValue + "</color>"), style);
GUI.enabled = isEditingEnabled;
EditorGUIUtility.labelWidth = 30f;
rect = new Rect(position.width / 2 + 20 + 70, position.y + 10, (width - 70) - padding, 18);
EditorGUI.PropertyField(rect, prop_SecondGlyphValueRecord.FindPropertyRelative("m_XPlacement"), new GUIContent("OX:"));
rect.y += 20;
EditorGUI.PropertyField(rect, prop_SecondGlyphValueRecord.FindPropertyRelative("m_YPlacement"), new GUIContent("OY:"));
rect.y += 20;
EditorGUI.PropertyField(rect, prop_SecondGlyphValueRecord.FindPropertyRelative("m_XAdvance"), new GUIContent("AX:"));
//rect.y += 20;
//EditorGUI.PropertyField(rect, prop_SecondGlyphAdjustment.FindPropertyRelative("m_YAdvance"), new GUIContent("AY"));
DrawGlyph((uint)prop_SecondGlyphIndex.intValue, new Rect(position.width / 2 + 20, position.y, position.width, position.height), property);
}
else
{
rect = new Rect(position.width / 2 + 20, position.y, width / 2 * 0.8f - padding, 18);
EditorGUIUtility.labelWidth = 40f;
// Second Character Lookup
GUI.SetNextControlName("SecondCharacterField");
EditorGUI.BeginChangeCheck();
string secondCharacter = EditorGUI.TextField(rect, s_CharacterTextFieldLabel, m_SecondCharacter);
if (GUI.GetNameOfFocusedControl() == "SecondCharacterField")
{
if (ValidateInput(secondCharacter))
{
//Debug.Log("2nd Unicode value: [" + secondCharacter + "]");
uint unicode = GetUnicodeCharacter(secondCharacter);
// Lookup glyph index
TMP_SerializedPropertyHolder propertyHolder = property.serializedObject.targetObject as TMP_SerializedPropertyHolder;
TMP_FontAsset fontAsset = propertyHolder.fontAsset;
if (fontAsset != null)
{
prop_SecondGlyphIndex.intValue = (int)fontAsset.GetGlyphIndex(unicode);
propertyHolder.secondCharacter = unicode;
}
}
}
if (EditorGUI.EndChangeCheck())
m_SecondCharacter = secondCharacter;
// Second Glyph Index
rect.x += width / 2 * 0.8f;
EditorGUIUtility.labelWidth = 25f;
EditorGUI.BeginChangeCheck();
EditorGUI.PropertyField(rect, prop_SecondGlyphIndex, new GUIContent("ID:"));
if (EditorGUI.EndChangeCheck())
{
}
GUI.enabled = isEditingEnabled;
EditorGUIUtility.labelWidth = 25f;
rect = new Rect(position.width / 2 + 20, position.y + 20, width * 0.5f - padding, 18);
EditorGUI.PropertyField(rect, prop_SecondGlyphValueRecord.FindPropertyRelative("m_XPlacement"), new GUIContent("OX"));
rect.x += width * 0.5f;
EditorGUI.PropertyField(rect, prop_SecondGlyphValueRecord.FindPropertyRelative("m_YPlacement"), new GUIContent("OY"));
rect.x = position.width / 2 + 20;
rect.y += 20;
EditorGUI.PropertyField(rect, prop_SecondGlyphValueRecord.FindPropertyRelative("m_XAdvance"), new GUIContent("AX"));
//rect.x += width * 0.5f;
//EditorGUI.PropertyField(rect, prop_SecondGlyphAdjustment.FindPropertyRelative("m_YAdvance"), new GUIContent("AY"));
}
// Font Feature Lookup Flags
if (isSelectable)
{
EditorGUIUtility.labelWidth = 55f;
rect.x = position.width - 255;
rect.y += 23;
rect.width = 270; // width - 70 - padding;
FontFeatureLookupFlags flags = (FontFeatureLookupFlags)prop_FontFeatureLookupFlags.intValue;
EditorGUI.BeginChangeCheck();
flags = (FontFeatureLookupFlags)EditorGUI.EnumFlagsField(rect, new GUIContent("Options:"), flags);
if (EditorGUI.EndChangeCheck())
{
prop_FontFeatureLookupFlags.intValue = (int)flags;
}
}
}
bool ValidateInput(string source)
{
int length = string.IsNullOrEmpty(source) ? 0 : source.Length;
////Filter out unwanted characters.
Event evt = Event.current;
char c = evt.character;
if (c != '\0')
{
switch (length)
{
case 0:
break;
case 1:
if (source != m_PreviousInput)
return true;
if ((source[0] == '\\' && (c == 'u' || c == 'U')) == false)
evt.character = '\0';
break;
case 2:
case 3:
case 4:
case 5:
if ((c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F'))
evt.character = '\0';
break;
case 6:
case 7:
case 8:
case 9:
if (source[1] == 'u' || (c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F'))
evt.character = '\0';
// Validate input
if (length == 6 && source[1] == 'u' && source != m_PreviousInput)
return true;
break;
case 10:
if (source != m_PreviousInput)
return true;
evt.character = '\0';
break;
}
}
m_PreviousInput = source;
return false;
}
uint GetUnicodeCharacter (string source)
{
uint unicode;
if (source.Length == 1)
unicode = source[0];
else if (source.Length == 6)
unicode = (uint)TMP_TextUtilities.StringHexToInt(source.Replace("\\u", ""));
else
unicode = (uint)TMP_TextUtilities.StringHexToInt(source.Replace("\\U", ""));
return unicode;
}
void DrawGlyph(uint glyphIndex, Rect position, SerializedProperty property)
{
// Get a reference to the sprite texture
TMP_FontAsset fontAsset = property.serializedObject.targetObject as TMP_FontAsset;
if (fontAsset == null)
return;
// Check if glyph currently exists in the atlas texture.
if (!fontAsset.glyphLookupTable.TryGetValue(glyphIndex, out Glyph glyph))
return;
// Get reference to atlas texture.
int atlasIndex = fontAsset.m_AtlasTextureIndex;
Texture2D atlasTexture = fontAsset.atlasTextures.Length > atlasIndex ? fontAsset.atlasTextures[atlasIndex] : null;
if (atlasTexture == null)
return;
Material mat;
if (((GlyphRasterModes)fontAsset.atlasRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP)
{
mat = TMP_FontAssetEditor.internalBitmapMaterial;
if (mat == null)
return;
mat.mainTexture = atlasTexture;
}
else
{
mat = TMP_FontAssetEditor.internalSDFMaterial;
if (mat == null)
return;
mat.mainTexture = atlasTexture;
mat.SetFloat(ShaderUtilities.ID_GradientScale, fontAsset.atlasPadding + 1);
}
// Draw glyph from atlas texture.
Rect glyphDrawPosition = new Rect(position.x, position.y + 2, 64, 60);
GlyphRect glyphRect = glyph.glyphRect;
float normalizedHeight = fontAsset.faceInfo.ascentLine - fontAsset.faceInfo.descentLine;
float scale = glyphDrawPosition.width / normalizedHeight;
// Compute the normalized texture coordinates
Rect texCoords = new Rect((float)glyphRect.x / atlasTexture.width, (float)glyphRect.y / atlasTexture.height, (float)glyphRect.width / atlasTexture.width, (float)glyphRect.height / atlasTexture.height);
if (Event.current.type == EventType.Repaint)
{
glyphDrawPosition.x += (glyphDrawPosition.width - glyphRect.width * scale) / 2;
glyphDrawPosition.y += (glyphDrawPosition.height - glyphRect.height * scale) / 2;
glyphDrawPosition.width = glyphRect.width * scale;
glyphDrawPosition.height = glyphRect.height * scale;
// Could switch to using the default material of the font asset which would require passing scale to the shader.
Graphics.DrawTexture(glyphDrawPosition, atlasTexture, texCoords, 0, 0, 0, 0, new Color(1f, 1f, 1f), mat);
}
}
}
} | 412 | 0.895428 | 1 | 0.895428 | game-dev | MEDIA | 0.924744 | game-dev | 0.961113 | 1 | 0.961113 |
OmixVisualization/qtjambi | 6,862 | src/cpp/QtJambiPositioning/hashes.h | /****************************************************************************
**
** Copyright (C) 2009-2025 Dr. Peter Droste, Omix Visualization GmbH & Co. KG. All rights reserved.
**
** This file is part of Qt Jambi.
**
** $BEGIN_LICENSE$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
** $END_LICENSE$
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/
#ifndef QTJAMBIPOSITIONING_HASHES_H
#define QTJAMBIPOSITIONING_HASHES_H
#include <QtCore/QtCore>
#include <QtPositioning/QtPositioning>
#include <QtJambi/Global>
#include <QtJambiCore/hashes.h>
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
hash_type qHash(const QGeoAddress &value, hash_type seed = 0);
hash_type qHash(const QGeoShape &value, hash_type seed = 0);
#endif
hash_type qHash(const QGeoRectangle &value, hash_type seed = 0);
hash_type qHash(const QGeoPath &value, hash_type seed = 0);
hash_type qHash(const QGeoCircle &value, hash_type seed = 0);
hash_type qHash(const QGeoPolygon &value, hash_type seed = 0);
inline hash_type qHash(const QGeoCircle &value, hash_type seed)
{
if(!value.isValid())
return 0;
#if QT_VERSION < QT_VERSION_CHECK(6, 10, 0)
QtPrivate::QHashCombine hash;
#else
QtPrivate::QHashCombine hash(seed);
#endif
seed = hash(seed, value.radius());
seed = hash(seed, value.isEmpty());
seed = hash(seed, value.center());
return seed;
}
inline hash_type qHash(const QGeoPath &value, hash_type seed)
{
if(!value.isValid())
return 0;
#if QT_VERSION < QT_VERSION_CHECK(6, 10, 0)
QtPrivate::QHashCombine hash;
#else
QtPrivate::QHashCombine hash(seed);
#endif
seed = hash(seed, value.path());
seed = hash(seed, value.isEmpty());
seed = hash(seed, value.center());
return seed;
}
inline hash_type qHash(const QGeoPolygon &value, hash_type seed)
{
if(!value.isValid())
return 0;
#if QT_VERSION < QT_VERSION_CHECK(6, 10, 0)
QtPrivate::QHashCombine hash;
#else
QtPrivate::QHashCombine hash(seed);
#endif
seed = hash(seed,
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
value.path());
#else
value.perimeter());
#endif
seed = hash(seed, value.isEmpty());
seed = hash(seed, value.center());
return seed;
}
inline hash_type qHash(const QGeoRectangle &value, hash_type seed)
{
if(!value.isValid())
return 0;
#if QT_VERSION < QT_VERSION_CHECK(6, 10, 0)
QtPrivate::QHashCombine hash;
#else
QtPrivate::QHashCombine hash(seed);
#endif
seed = hash(seed, value.width());
seed = hash(seed, value.isEmpty());
seed = hash(seed, value.center());
seed = hash(seed, value.height());
return seed;
}
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
inline hash_type qHash(const QGeoLocation &value, hash_type seed = 0)
{
QtPrivate::QHashCombine hash;
seed = hash(seed, value.address());
seed = hash(seed, value.coordinate());
seed = hash(seed, value.boundingBox());
seed = hash(seed, value.isEmpty());
return seed;
}
inline hash_type qHash(const QGeoAreaMonitorInfo &value, hash_type seed = 0)
{
if(!value.isValid())
return 0;
QtPrivate::QHashCombine hash;
seed = hash(seed, value.area());
seed = hash(seed, value.name());
seed = hash(seed, value.expiration());
seed = hash(seed, value.identifier());
seed = hash(seed, value.isPersistent());
return seed;
}
inline hash_type qHash(const QGeoSatelliteInfo &value, hash_type seed = 0)
{
QtPrivate::QHashCombine hash;
seed = hash(seed, value.signalStrength());
seed = hash(seed, value.satelliteSystem());
seed = hash(seed, value.satelliteIdentifier());
for(int a=QGeoSatelliteInfo::Elevation; a<=QGeoSatelliteInfo::Azimuth; ++a){
if(value.hasAttribute(QGeoSatelliteInfo::Attribute(a))){
seed = hash(seed, value.attribute(QGeoSatelliteInfo::Attribute(a)));
}else{
seed = hash(seed, false);
}
}
return seed;
}
inline hash_type qHash(const QGeoPositionInfo &value, hash_type seed = 0)
{
if(!value.isValid())
return 0;
QtPrivate::QHashCombine hash;
seed = hash(seed, value.timestamp());
seed = hash(seed, value.coordinate());
for(int a=QGeoPositionInfo::Direction; a<=QGeoPositionInfo::VerticalAccuracy; ++a){
if(value.hasAttribute(QGeoPositionInfo::Attribute(a))){
seed = hash(seed, value.attribute(QGeoPositionInfo::Attribute(a)));
}else{
seed = hash(seed, false);
}
}
return seed;
}
inline hash_type qHash(const QGeoShape &value, hash_type seed)
{
if(!value.isValid())
return 0;
switch(value.type()){
case QGeoShape::RectangleType:
return qHash(static_cast<const QGeoRectangle &>(value), seed);
case QGeoShape::CircleType:
return qHash(static_cast<const QGeoCircle &>(value), seed);
case QGeoShape::PathType:
return qHash(static_cast<const QGeoPath &>(value), seed);
case QGeoShape::PolygonType:
return qHash(static_cast<const QGeoPolygon &>(value), seed);
default:
QtPrivate::QHashCombine hash;
seed = hash(seed, value.type());
seed = hash(seed, value.isEmpty());
seed = hash(seed, value.center());
return seed;
}
}
inline hash_type qHash(const QGeoAddress &value, hash_type seed)
{
QtPrivate::QHashCombine hash;
seed = hash(seed, value.city());
seed = hash(seed, value.text());
seed = hash(seed, value.state());
seed = hash(seed, value.county());
seed = hash(seed, value.street());
seed = hash(seed, value.country());
seed = hash(seed, value.district());
seed = hash(seed, value.postalCode());
seed = hash(seed, value.countryCode());
seed = hash(seed, value.isTextGenerated());
seed = hash(seed, value.isEmpty());
return seed;
}
#endif
#endif // QTJAMBI_POSITIONING_HASHES_H
| 412 | 0.859197 | 1 | 0.859197 | game-dev | MEDIA | 0.41294 | game-dev,security-crypto | 0.891623 | 1 | 0.891623 |
cmangos/mangos-tbc | 4,445 | dep/recastnavigation/RecastDemo/Source/OffMeshConnectionTool.cpp | //
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <float.h>
#include "SDL.h"
#include "SDL_opengl.h"
#ifdef __APPLE__
# include <OpenGL/glu.h>
#else
# include <GL/glu.h>
#endif
#include "imgui.h"
#include "OffMeshConnectionTool.h"
#include "InputGeom.h"
#include "Sample.h"
#include "Recast.h"
#include "RecastDebugDraw.h"
#include "DetourDebugDraw.h"
#ifdef WIN32
# define snprintf _snprintf
#endif
OffMeshConnectionTool::OffMeshConnectionTool() :
m_sample(0),
m_hitPosSet(0),
m_bidir(true),
m_oldFlags(0)
{
}
OffMeshConnectionTool::~OffMeshConnectionTool()
{
if (m_sample)
{
m_sample->setNavMeshDrawFlags(m_oldFlags);
}
}
void OffMeshConnectionTool::init(Sample* sample)
{
if (m_sample != sample)
{
m_sample = sample;
m_oldFlags = m_sample->getNavMeshDrawFlags();
m_sample->setNavMeshDrawFlags(m_oldFlags & ~DU_DRAWNAVMESH_OFFMESHCONS);
}
}
void OffMeshConnectionTool::reset()
{
m_hitPosSet = false;
}
void OffMeshConnectionTool::handleMenu()
{
if (imguiCheck("One Way", !m_bidir))
m_bidir = false;
if (imguiCheck("Bidirectional", m_bidir))
m_bidir = true;
}
void OffMeshConnectionTool::handleClick(const float* /*s*/, const float* p, bool shift)
{
if (!m_sample) return;
InputGeom* geom = m_sample->getInputGeom();
if (!geom) return;
if (shift)
{
// Delete
// Find nearest link end-point
float nearestDist = FLT_MAX;
int nearestIndex = -1;
const float* verts = geom->getOffMeshConnectionVerts();
for (int i = 0; i < geom->getOffMeshConnectionCount()*2; ++i)
{
const float* v = &verts[i*3];
float d = rcVdistSqr(p, v);
if (d < nearestDist)
{
nearestDist = d;
nearestIndex = i/2; // Each link has two vertices.
}
}
// If end point close enough, delete it.
if (nearestIndex != -1 &&
sqrtf(nearestDist) < m_sample->getAgentRadius())
{
geom->deleteOffMeshConnection(nearestIndex);
}
}
else
{
// Create
if (!m_hitPosSet)
{
rcVcopy(m_hitPos, p);
m_hitPosSet = true;
}
else
{
const unsigned char area = SAMPLE_POLYAREA_JUMP;
const unsigned short flags = SAMPLE_POLYFLAGS_JUMP;
geom->addOffMeshConnection(m_hitPos, p, m_sample->getAgentRadius(), m_bidir ? 1 : 0, area, flags);
m_hitPosSet = false;
}
}
}
void OffMeshConnectionTool::handleToggle()
{
}
void OffMeshConnectionTool::handleStep()
{
}
void OffMeshConnectionTool::handleUpdate(const float /*dt*/)
{
}
void OffMeshConnectionTool::handleRender()
{
duDebugDraw& dd = m_sample->getDebugDraw();
const float s = m_sample->getAgentRadius();
if (m_hitPosSet)
duDebugDrawCross(&dd, m_hitPos[0],m_hitPos[1]+0.1f,m_hitPos[2], s, duRGBA(0,0,0,128), 2.0f);
InputGeom* geom = m_sample->getInputGeom();
if (geom)
geom->drawOffMeshConnections(&dd, true);
}
void OffMeshConnectionTool::handleRenderOverlay(double* proj, double* model, int* view)
{
GLdouble x, y, z;
// Draw start and end point labels
if (m_hitPosSet && gluProject((GLdouble)m_hitPos[0], (GLdouble)m_hitPos[1], (GLdouble)m_hitPos[2],
model, proj, view, &x, &y, &z))
{
imguiDrawText((int)x, (int)(y-25), IMGUI_ALIGN_CENTER, "Start", imguiRGBA(0,0,0,220));
}
// Tool help
const int h = view[3];
if (!m_hitPosSet)
{
imguiDrawText(280, h-40, IMGUI_ALIGN_LEFT, "LMB: Create new connection. SHIFT+LMB: Delete existing connection, click close to start or end point.", imguiRGBA(255,255,255,192));
}
else
{
imguiDrawText(280, h-40, IMGUI_ALIGN_LEFT, "LMB: Set connection end point and finish.", imguiRGBA(255,255,255,192));
}
}
| 412 | 0.950077 | 1 | 0.950077 | game-dev | MEDIA | 0.641194 | game-dev | 0.874916 | 1 | 0.874916 |
OpenXRay/xray-15 | 11,239 | cs/engine/utils/xrAI/game_graph_inline.h | ////////////////////////////////////////////////////////////////////////////
// Module : game_graph_inline.h
// Created : 18.02.2003
// Modified : 13.11.2003
// Author : Dmitriy Iassenev
// Description : Game graph inline functions
////////////////////////////////////////////////////////////////////////////
#pragma once
#ifdef AI_COMPILER
IC CGameGraph::CGameGraph (LPCSTR file_name, u32 current_version)
{
m_reader = FS.r_open(file_name);
VERIFY (m_reader);
m_header.load (m_reader);
R_ASSERT2 (header().version() == XRAI_CURRENT_VERSION,"Graph version mismatch!");
m_nodes = (CVertex*)m_reader->pointer();
m_current_level_some_vertex_id = _GRAPH_ID(-1);
m_enabled.assign (header().vertex_count(),true);
u8 *temp = (u8*)(m_nodes + header().vertex_count());
temp += header().edge_count()*sizeof(CGameGraph::CEdge);
m_cross_tables = (u32*)(((CLevelPoint*)temp) + header().death_point_count());
m_current_level_cross_table = 0;
}
#endif // AI_COMPILER
IC CGameGraph::CGameGraph (const IReader &_stream)
{
IReader &stream = const_cast<IReader&>(_stream);
m_header.load (&stream);
R_ASSERT2 (header().version() == XRAI_CURRENT_VERSION,"Graph version mismatch!");
m_nodes = (CVertex*)stream.pointer();
m_current_level_some_vertex_id = _GRAPH_ID(-1);
m_enabled.assign (header().vertex_count(),true);
u8 *temp = (u8*)(m_nodes + header().vertex_count());
temp += header().edge_count()*sizeof(CGameGraph::CEdge);
m_cross_tables = (u32*)(((CLevelPoint*)temp) + header().death_point_count());
m_current_level_cross_table = 0;
}
IC CGameGraph::~CGameGraph ()
{
xr_delete (m_current_level_cross_table);
#ifdef AI_COMPILER
FS.r_close (m_reader);
#endif // AI_COMPILER
}
IC const CGameGraph::CHeader &CGameGraph::header () const
{
return (m_header);
}
IC bool CGameGraph::mask (const svector<_LOCATION_ID,GameGraph::LOCATION_TYPE_COUNT> &M, const _LOCATION_ID E[GameGraph::LOCATION_TYPE_COUNT]) const
{
for (int i=0; i<GameGraph::LOCATION_TYPE_COUNT; ++i)
if ((M[i] != E[i]) && (255 != M[i]))
return(false);
return(true);
}
IC bool CGameGraph::mask (const _LOCATION_ID M[GameGraph::LOCATION_TYPE_COUNT], const _LOCATION_ID E[GameGraph::LOCATION_TYPE_COUNT]) const
{
for (int i=0; i<GameGraph::LOCATION_TYPE_COUNT; ++i)
if ((M[i] != E[i]) && (255 != M[i]))
return(false);
return(true);
}
IC float CGameGraph::distance (const _GRAPH_ID tGraphID0, const _GRAPH_ID tGraphID1) const
{
const_iterator i, e;
begin (tGraphID0,i,e);
for ( ; i != e; ++i)
if (value(tGraphID0,i) == tGraphID1)
return (edge_weight(i));
R_ASSERT2 (false,"There is no proper graph point neighbour!");
return (_GRAPH_ID(-1));
}
IC bool CGameGraph::accessible (u32 const vertex_id) const
{
VERIFY (valid_vertex_id(vertex_id));
return (m_enabled[vertex_id]);
}
IC void CGameGraph::accessible (u32 const vertex_id, bool value) const
{
VERIFY (valid_vertex_id(vertex_id));
m_enabled[vertex_id] = value;
}
IC bool CGameGraph::valid_vertex_id (u32 const vertex_id) const
{
return (vertex_id < header().vertex_count());
}
IC void CGameGraph::begin (u32 const vertex_id, const_iterator &start, const_iterator &end) const
{
end = (start = (const CEdge *)((BYTE *)m_nodes + vertex(_GRAPH_ID(vertex_id))->edge_offset())) + vertex(_GRAPH_ID(vertex_id))->edge_count();
}
IC const CGameGraph::_GRAPH_ID &CGameGraph::value (u32 const vertex_id, const_iterator &i) const
{
return (i->vertex_id());
}
IC const float &CGameGraph::edge_weight (const_iterator i) const
{
return (i->distance());
}
IC const CGameGraph::CVertex *CGameGraph::vertex (u32 const vertex_id) const
{
return (m_nodes + vertex_id);
}
IC const u8 &CGameGraph::CHeader::version () const
{
return (m_version);
}
IC GameGraph::_LEVEL_ID GameGraph::CHeader::level_count () const
{
VERIFY (m_levels.size() < (u32(1) << (8*sizeof(GameGraph::_LEVEL_ID))));
return ((GameGraph::_LEVEL_ID)m_levels.size());
}
IC const GameGraph::_GRAPH_ID &GameGraph::CHeader::vertex_count () const
{
return (m_vertex_count);
}
IC u32 const& GameGraph::CHeader::edge_count () const
{
return (m_edge_count);
}
IC u32 const& GameGraph::CHeader::death_point_count () const
{
return (m_death_point_count);
}
IC const GameGraph::LEVEL_MAP &GameGraph::CHeader::levels () const
{
return (m_levels);
}
IC const GameGraph::SLevel &GameGraph::CHeader::level (const _LEVEL_ID &id) const
{
LEVEL_MAP::const_iterator I = levels().find(id);
R_ASSERT2 (I != levels().end(),make_string("there is no specified level in the game graph : %d",id));
return ((*I).second);
}
IC const GameGraph::SLevel &GameGraph::CHeader::level (LPCSTR level_name) const
{
LEVEL_MAP::const_iterator I = levels().begin();
LEVEL_MAP::const_iterator E = levels().end();
for ( ; I != E; ++I)
if (!xr_strcmp((*I).second.name(),level_name))
return ((*I).second);
#ifdef DEBUG
Msg ("! There is no specified level %s in the game graph!",level_name);
return (levels().begin()->second);
#else
R_ASSERT3 (false,"There is no specified level in the game graph!",level_name);
NODEFAULT;
#endif
}
IC const GameGraph::SLevel *GameGraph::CHeader::level (LPCSTR level_name, bool) const
{
LEVEL_MAP::const_iterator I = levels().begin();
LEVEL_MAP::const_iterator E = levels().end();
for ( ; I != E; ++I)
if (!xr_strcmp((*I).second.name(),level_name))
return (&(*I).second);
return (0);
}
IC const xrGUID &CGameGraph::CHeader::guid () const
{
return (m_guid);
}
IC const Fvector &GameGraph::CVertex::level_point () const
{
return (tLocalPoint);
}
IC const Fvector &GameGraph::CVertex::game_point () const
{
return (tGlobalPoint);
}
IC GameGraph::_LEVEL_ID GameGraph::CVertex::level_id () const
{
return (tLevelID);
}
IC u32 GameGraph::CVertex::level_vertex_id () const
{
return (tNodeID);
}
IC const u8 *GameGraph::CVertex::vertex_type () const
{
return (tVertexTypes);
}
IC const u8 &GameGraph::CVertex::edge_count () const
{
return (tNeighbourCount);
}
IC const u8 &GameGraph::CVertex::death_point_count () const
{
return (tDeathPointCount);
}
IC u32 const& GameGraph::CVertex::edge_offset () const
{
return (dwEdgeOffset);
}
IC u32 const& GameGraph::CVertex::death_point_offset () const
{
return (dwPointOffset);
}
IC const GameGraph::_GRAPH_ID &GameGraph::CEdge::vertex_id () const
{
return (m_vertex_id);
}
IC const float &GameGraph::CEdge::distance () const
{
return (m_path_distance);
}
IC void CGameGraph::begin_spawn (u32 const vertex_id, const_spawn_iterator &start, const_spawn_iterator &end) const
{
const CVertex *object = vertex(vertex_id);
start = (const_spawn_iterator)((u8*)m_nodes + object->death_point_offset());
end = start + object->death_point_count();
}
IC void CGameGraph::set_invalid_vertex (_GRAPH_ID &vertex_id) const
{
vertex_id = _GRAPH_ID(-1);
VERIFY (!valid_vertex_id(vertex_id));
}
IC GameGraph::_GRAPH_ID CGameGraph::vertex_id (const CGameGraph::CVertex *vertex) const
{
VERIFY (valid_vertex_id(_GRAPH_ID(vertex - m_nodes)));
return (_GRAPH_ID(vertex - m_nodes));
}
IC const GameGraph::_GRAPH_ID &CGameGraph::current_level_vertex () const
{
VERIFY (valid_vertex_id(m_current_level_some_vertex_id));
return (m_current_level_some_vertex_id);
}
IC void GameGraph::SLevel::load (IReader *reader)
{
reader->r_stringZ (m_name);
reader->r_fvector3 (m_offset);
reader->r (&m_id,sizeof(m_id));
reader->r_stringZ (m_section);
reader->r (&m_guid,sizeof(m_guid));
}
IC void GameGraph::SLevel::save (IWriter *writer)
{
writer->w_stringZ (m_name);
writer->w_fvector3 (m_offset);
writer->w (&m_id,sizeof(m_id));
writer->w_stringZ (m_section);
writer->w (&m_guid,sizeof(m_guid));
}
IC void GameGraph::CHeader::load (IReader *reader)
{
reader->r (&m_version, sizeof(m_version));
reader->r (&m_vertex_count, sizeof(m_vertex_count));
reader->r (&m_edge_count, sizeof(m_edge_count));
reader->r (&m_death_point_count, sizeof(m_death_point_count));
reader->r (&m_guid, sizeof(m_guid));
u32 level_count = reader->r_u8();
m_levels.clear ();
for (u32 i=0; i<level_count; ++i) {
SLevel l_tLevel;
l_tLevel.load (reader);
m_levels.insert (mk_pair(l_tLevel.id(),l_tLevel));
}
}
IC void GameGraph::CHeader::save (IWriter *writer)
{
writer->w (&m_version, sizeof(m_version));
writer->w (&m_vertex_count, sizeof(m_vertex_count));
writer->w (&m_edge_count, sizeof(m_edge_count));
writer->w (&m_death_point_count, sizeof(m_death_point_count));
writer->w (&m_guid, sizeof(m_guid));
VERIFY (m_levels.size() < u32((1) << (8*sizeof(u8))));
writer->w_u8 ((u8)m_levels.size());
LEVEL_MAP::iterator I = m_levels.begin();
LEVEL_MAP::iterator E = m_levels.end();
for ( ; I != E; ++I)
(*I).second.save (writer);
}
IC void CGameGraph::set_current_level (u32 const level_id)
{
xr_delete (m_current_level_cross_table);
u32 *current_cross_table = m_cross_tables;
GameGraph::LEVEL_MAP::const_iterator I = header().levels().begin();
GameGraph::LEVEL_MAP::const_iterator E = header().levels().end();
for ( ; I != E; ++I) {
if (level_id != (*I).first) {
current_cross_table = (u32*)((u8*)current_cross_table + *current_cross_table);
continue;
}
m_current_level_cross_table = new CGameLevelCrossTable(current_cross_table + 1,*current_cross_table);
break;
}
VERIFY (m_current_level_cross_table);
m_current_level_some_vertex_id = _GRAPH_ID(-1);
for (_GRAPH_ID i=0, n = header().vertex_count(); i<n; ++i) {
if (level_id != vertex(i)->level_id())
continue;
m_current_level_some_vertex_id = i;
break;
}
VERIFY (valid_vertex_id(m_current_level_some_vertex_id));
}
IC const CGameLevelCrossTable &CGameGraph::cross_table () const
{
VERIFY (m_current_level_cross_table);
return (*m_current_level_cross_table);
}
#ifdef AI_COMPILER
IC void CGameGraph::save (IWriter &stream)
{
m_header.save (&stream);
u8 *buffer = (u8*)m_nodes;
stream.w (buffer,header().vertex_count()*sizeof(CVertex));
buffer += header().vertex_count()*sizeof(CVertex);
stream.w (buffer,header().edge_count()*sizeof(CGameGraph::CEdge));
buffer += header().edge_count()*sizeof(CGameGraph::CEdge);
stream.w (buffer,header().death_point_count()*sizeof(CLevelPoint));
buffer += header().death_point_count()*sizeof(CLevelPoint);
VERIFY ((u8*)m_cross_tables == buffer);
GameGraph::LEVEL_MAP::const_iterator I = header().levels().begin();
GameGraph::LEVEL_MAP::const_iterator E = header().levels().end();
for ( ; I != E; ++I) {
u32 size = *(u32*)buffer;
stream.w (buffer,size);
buffer += size;
}
}
#endif // AI_COMPILER | 412 | 0.875523 | 1 | 0.875523 | game-dev | MEDIA | 0.556681 | game-dev | 0.895543 | 1 | 0.895543 |
gunatppcap/shield-stack | 15,782 | common/task_executor/src/lib.rs | mod metrics;
mod rayon_pool_provider;
pub mod test_utils;
use futures::channel::mpsc::Sender;
use futures::prelude::*;
use std::sync::{Arc, Weak};
use tokio::runtime::{Handle, Runtime};
use tracing::debug;
use crate::rayon_pool_provider::RayonPoolProvider;
pub use crate::rayon_pool_provider::RayonPoolType;
pub use tokio::task::JoinHandle;
/// Provides a reason when Lighthouse is shut down.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum ShutdownReason {
/// The node shut down successfully.
Success(&'static str),
/// The node shut down due to an error condition.
Failure(&'static str),
}
impl ShutdownReason {
pub fn message(&self) -> &'static str {
match self {
ShutdownReason::Success(msg) => msg,
ShutdownReason::Failure(msg) => msg,
}
}
}
/// Provides a `Handle` by either:
///
/// 1. Holding a `Weak<Runtime>` and calling `Runtime::handle`.
/// 2. Directly holding a `Handle` and cloning it.
///
/// This enum allows the `TaskExecutor` to work in production where a `Weak<Runtime>` is directly
/// accessible and in testing where the `Runtime` is hidden outside our scope.
#[derive(Clone)]
pub enum HandleProvider {
Runtime(Weak<Runtime>),
Handle(Handle),
}
impl From<Handle> for HandleProvider {
fn from(handle: Handle) -> Self {
HandleProvider::Handle(handle)
}
}
impl From<Weak<Runtime>> for HandleProvider {
fn from(weak_runtime: Weak<Runtime>) -> Self {
HandleProvider::Runtime(weak_runtime)
}
}
impl HandleProvider {
/// Returns a `Handle` to a `Runtime`.
///
/// May return `None` if the weak reference to the `Runtime` has been dropped (this generally
/// means Lighthouse is shutting down).
pub fn handle(&self) -> Option<Handle> {
match self {
HandleProvider::Runtime(weak_runtime) => weak_runtime
.upgrade()
.map(|runtime| runtime.handle().clone()),
HandleProvider::Handle(handle) => Some(handle.clone()),
}
}
}
/// A wrapper over a runtime handle which can spawn async and blocking tasks.
#[derive(Clone)]
pub struct TaskExecutor {
/// The handle to the runtime on which tasks are spawned
handle_provider: HandleProvider,
/// The receiver exit future which on receiving shuts down the task
exit: async_channel::Receiver<()>,
/// Sender given to tasks, so that if they encounter a state in which execution cannot
/// continue they can request that everything shuts down.
///
/// The task must provide a reason for shutting down.
signal_tx: Sender<ShutdownReason>,
/// The name of the service for inclusion in the logger output.
// FIXME(sproul): delete?
#[allow(dead_code)]
service_name: String,
rayon_pool_provider: Arc<RayonPoolProvider>,
}
impl TaskExecutor {
/// Create a new task executor.
///
/// ## Note
///
/// This function should only be used during testing. In production, prefer to obtain an
/// instance of `Self` via a `environment::RuntimeContext` (see the `lighthouse/environment`
/// crate).
pub fn new<T: Into<HandleProvider>>(
handle: T,
exit: async_channel::Receiver<()>,
signal_tx: Sender<ShutdownReason>,
service_name: String,
) -> Self {
Self {
handle_provider: handle.into(),
exit,
signal_tx,
service_name,
rayon_pool_provider: Arc::new(RayonPoolProvider::default()),
}
}
/// Clones the task executor adding a service name.
pub fn clone_with_name(&self, service_name: String) -> Self {
TaskExecutor {
handle_provider: self.handle_provider.clone(),
exit: self.exit.clone(),
signal_tx: self.signal_tx.clone(),
service_name,
rayon_pool_provider: self.rayon_pool_provider.clone(),
}
}
/// A convenience wrapper for `Self::spawn` which ignores a `Result` as long as both `Ok`/`Err`
/// are of type `()`.
///
/// The purpose of this function is to create a compile error if some function which previously
/// returned `()` starts returning something else. Such a case may otherwise result in
/// accidental error suppression.
pub fn spawn_ignoring_error(
&self,
task: impl Future<Output = Result<(), ()>> + Send + 'static,
name: &'static str,
) {
self.spawn(task.map(|_| ()), name)
}
/// Spawn a task to monitor the completion of another task.
///
/// If the other task exits by panicking, then the monitor task will shut down the executor.
fn spawn_monitor<R: Send>(
&self,
task_handle: impl Future<Output = Result<R, tokio::task::JoinError>> + Send + 'static,
name: &'static str,
) {
let mut shutdown_sender = self.shutdown_sender();
if let Some(handle) = self.handle() {
let fut = async move {
let timer = metrics::start_timer_vec(&metrics::TASKS_HISTOGRAM, &[name]);
if let Err(join_error) = task_handle.await
&& let Ok(_panic) = join_error.try_into_panic()
{
let _ =
shutdown_sender.try_send(ShutdownReason::Failure("Panic (fatal error)"));
}
drop(timer);
};
#[cfg(tokio_unstable)]
tokio::task::Builder::new()
.name(&format!("{name}-monitor"))
.spawn_on(fut, &handle)
.expect("Failed to spawn monitor task");
#[cfg(not(tokio_unstable))]
handle.spawn(fut);
} else {
debug!("Couldn't spawn monitor task. Runtime shutting down")
}
}
/// Spawn a future on the tokio runtime.
///
/// The future is wrapped in an `async-channel::Receiver`. The task is cancelled when the corresponding
/// Sender is dropped.
///
/// The future is monitored via another spawned future to ensure that it doesn't panic. In case
/// of a panic, the executor will be shut down via `self.signal_tx`.
///
/// This function generates prometheus metrics on number of tasks and task duration.
pub fn spawn(&self, task: impl Future<Output = ()> + Send + 'static, name: &'static str) {
if let Some(task_handle) = self.spawn_handle(task, name) {
self.spawn_monitor(task_handle, name)
}
}
/// Spawn a future on the tokio runtime. This function does not wrap the task in an `async-channel::Receiver`
/// like [spawn](#method.spawn).
/// The caller of this function is responsible for wrapping up the task with an `async-channel::Receiver` to
/// ensure that the task gets cancelled appropriately.
/// This function generates prometheus metrics on number of tasks and task duration.
///
/// This is useful in cases where the future to be spawned needs to do additional cleanup work when
/// the task is completed/canceled (e.g. writing local variables to disk) or the task is created from
/// some framework which does its own cleanup (e.g. a hyper server).
pub fn spawn_without_exit(
&self,
task: impl Future<Output = ()> + Send + 'static,
name: &'static str,
) {
if let Some(int_gauge) = metrics::get_int_gauge(&metrics::ASYNC_TASKS_COUNT, &[name]) {
let int_gauge_1 = int_gauge.clone();
let future = task.then(move |_| {
int_gauge_1.dec();
futures::future::ready(())
});
int_gauge.inc();
if let Some(handle) = self.handle() {
#[cfg(tokio_unstable)]
tokio::task::Builder::new()
.name(name)
.spawn_on(future, &handle)
.expect("Failed to spawn task");
#[cfg(not(tokio_unstable))]
handle.spawn(future);
} else {
debug!("Couldn't spawn task. Runtime shutting down");
}
}
}
/// Spawn a blocking task on a dedicated tokio thread pool wrapped in an exit future.
/// This function generates prometheus metrics on number of tasks and task duration.
pub fn spawn_blocking<F>(&self, task: F, name: &'static str)
where
F: FnOnce() + Send + 'static,
{
if let Some(task_handle) = self.spawn_blocking_handle(task, name) {
self.spawn_monitor(task_handle, name)
}
}
/// Spawns a blocking task on a dedicated tokio thread pool and installs a rayon context within it.
pub fn spawn_blocking_with_rayon<F>(
self,
task: F,
rayon_pool_type: RayonPoolType,
name: &'static str,
) where
F: FnOnce() + Send + 'static,
{
let thread_pool = self.rayon_pool_provider.get_thread_pool(rayon_pool_type);
self.spawn_blocking(
move || {
thread_pool.install(|| {
task();
});
},
name,
)
}
/// Spawns a blocking computation on a rayon thread pool and awaits the result.
pub async fn spawn_blocking_with_rayon_async<F, R>(
&self,
rayon_pool_type: RayonPoolType,
task: F,
) -> Result<R, tokio::sync::oneshot::error::RecvError>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
let thread_pool = self.rayon_pool_provider.get_thread_pool(rayon_pool_type);
let (tx, rx) = tokio::sync::oneshot::channel();
thread_pool.spawn(move || {
let result = task();
let _ = tx.send(result);
});
rx.await
}
/// Spawn a future on the tokio runtime wrapped in an `async-channel::Receiver` returning an optional
/// join handle to the future.
/// The task is cancelled when the corresponding async-channel is dropped.
///
/// This function generates prometheus metrics on number of tasks and task duration.
pub fn spawn_handle<R: Send + 'static>(
&self,
task: impl Future<Output = R> + Send + 'static,
name: &'static str,
) -> Option<tokio::task::JoinHandle<Option<R>>> {
let exit = self.exit();
if let Some(int_gauge) = metrics::get_int_gauge(&metrics::ASYNC_TASKS_COUNT, &[name]) {
// Task is shutdown before it completes if `exit` receives
let int_gauge_1 = int_gauge.clone();
int_gauge.inc();
if let Some(handle) = self.handle() {
let fut = async move {
futures::pin_mut!(exit);
let result = match future::select(Box::pin(task), exit).await {
future::Either::Left((value, _)) => Some(value),
future::Either::Right(_) => {
debug!(task = name, "Async task shutdown, exit received");
None
}
};
int_gauge_1.dec();
result
};
#[cfg(tokio_unstable)]
return Some(
tokio::task::Builder::new()
.name(name)
.spawn_on(fut, &handle)
.expect("Failed to spawn task"),
);
#[cfg(not(tokio_unstable))]
Some(handle.spawn(fut))
} else {
debug!("Couldn't spawn task. Runtime shutting down");
None
}
} else {
None
}
}
/// Spawn a blocking task on a dedicated tokio thread pool wrapped in an exit future returning
/// a join handle to the future.
/// If the runtime doesn't exist, this will return None.
/// The Future returned behaves like the standard JoinHandle which can return an error if the
/// task failed.
/// This function generates prometheus metrics on number of tasks and task duration.
pub fn spawn_blocking_handle<F, R>(
&self,
task: F,
name: &'static str,
) -> Option<impl Future<Output = Result<R, tokio::task::JoinError>> + Send + 'static + use<F, R>>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
let timer = metrics::start_timer_vec(&metrics::BLOCKING_TASKS_HISTOGRAM, &[name]);
metrics::inc_gauge_vec(&metrics::BLOCKING_TASKS_COUNT, &[name]);
let join_handle = if let Some(handle) = self.handle() {
handle.spawn_blocking(task)
} else {
debug!("Couldn't spawn task. Runtime shutting down");
return None;
};
let future = async move {
let result = match join_handle.await {
Ok(result) => Ok(result),
Err(error) => {
debug!(%error, "Blocking task ended unexpectedly");
Err(error)
}
};
drop(timer);
metrics::dec_gauge_vec(&metrics::BLOCKING_TASKS_COUNT, &[name]);
result
};
Some(future)
}
/// Block the current (non-async) thread on the completion of some future.
///
/// ## Warning
///
/// This method is "dangerous" since calling it from an async thread will result in a panic! Any
/// use of this outside of testing should be very deeply considered as Lighthouse has been
/// burned by this function in the past.
///
/// Determining what is an "async thread" is rather challenging; just because a function isn't
/// marked as `async` doesn't mean it's not being called from an `async` function or there isn't
/// a `tokio` context present in the thread-local storage due to some `rayon` funkiness. Talk to
/// @paulhauner if you plan to use this function in production. He has put metrics in here to
/// track any use of it, so don't think you can pull a sneaky one on him.
pub fn block_on_dangerous<F: Future>(
&self,
future: F,
name: &'static str,
) -> Option<F::Output> {
let timer = metrics::start_timer_vec(&metrics::BLOCK_ON_TASKS_HISTOGRAM, &[name]);
metrics::inc_gauge_vec(&metrics::BLOCK_ON_TASKS_COUNT, &[name]);
let handle = self.handle()?;
let exit = self.exit();
debug!(name, "Starting block_on task");
handle.block_on(async {
let output = tokio::select! {
output = future => {
debug!(
name,
"Completed block_on task"
);
Some(output)
}
_ = exit => {
debug!(
name,
"Cancelled block_on task"
);
None
}
};
metrics::dec_gauge_vec(&metrics::BLOCK_ON_TASKS_COUNT, &[name]);
drop(timer);
output
})
}
/// Returns a `Handle` to the current runtime.
pub fn handle(&self) -> Option<Handle> {
self.handle_provider.handle()
}
/// Returns a future that completes when `async-channel::Sender` is dropped or () is sent,
/// which translates to the exit signal being triggered.
pub fn exit(&self) -> impl Future<Output = ()> + 'static {
let exit = self.exit.clone();
async move {
let _ = exit.recv().await;
}
}
/// Get a channel to request shutting down.
pub fn shutdown_sender(&self) -> Sender<ShutdownReason> {
self.signal_tx.clone()
}
}
| 412 | 0.978639 | 1 | 0.978639 | game-dev | MEDIA | 0.321704 | game-dev | 0.989037 | 1 | 0.989037 |
ProjectIgnis/CardScripts | 2,752 | unofficial/c511001050.lua | --幻影騎士団シャドーベイル (Anime)
--The Phantom Knights of Shadow Veil (Anime)
local s,id=GetID()
function s.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DEFCHANGE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(s.target)
e1:SetOperation(s.activate)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_ATTACK_ANNOUNCE)
e2:SetRange(LOCATION_GRAVE)
e2:SetCondition(s.spcon)
e2:SetTarget(s.sptg)
e2:SetOperation(s.spop)
c:RegisterEffect(e2)
end
s.listed_names={77462146}
function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsFaceup() end
if chk==0 then return Duel.IsExistingTarget(Card.IsFaceup,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,Card.IsFaceup,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_DEFENSE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
e1:SetValue(300)
tc:RegisterEffect(e1)
end
end
function s.spcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetAttacker():IsControler(1-tp) and Duel.GetAttackTarget()==nil
end
function s.filter(c,e,tp)
return c:IsCode(77462146) and Duel.IsPlayerCanSpecialSummonMonster(tp,77462146,0x10db,0x11,4,0,300,RACE_WARRIOR,ATTRIBUTE_DARK)
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(s.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp)end
local g=Duel.GetMatchingGroup(s.filter,tp,LOCATION_GRAVE,0,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ft<=0 then return end
local g=Duel.SelectMatchingCard(tp,s.filter,tp,LOCATION_GRAVE,0,1,ft,nil,e,tp)
if #g>0 then
local tc=g:GetFirst()
for tc in aux.Next(g) do
tc:AddMonsterAttribute(TYPE_NORMAL)
Duel.SpecialSummonStep(tc,0,tp,tp,true,false,POS_FACEUP)
tc:AddMonsterAttributeComplete()
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_TO_GRAVE_REDIRECT)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetReset(RESET_EVENT+RESETS_REDIRECT)
e1:SetValue(LOCATION_REMOVED)
tc:RegisterEffect(e1,true)
end
Duel.SpecialSummonComplete()
end
end | 412 | 0.961106 | 1 | 0.961106 | game-dev | MEDIA | 0.993685 | game-dev | 0.928224 | 1 | 0.928224 |
Kermalis/PokemonBattleEngine | 5,245 | PokemonBattleEngineTests/Abilities/IntimidateTests.cs | using Kermalis.PokemonBattleEngine.Battle;
using Kermalis.PokemonBattleEngine.Data;
using Xunit;
using Xunit.Abstractions;
namespace Kermalis.PokemonBattleEngineTests.Abilities;
[Collection("Utils")]
public class IntimidateTests
{
public IntimidateTests(TestUtils _, ITestOutputHelper output)
{
TestUtils.SetOutputHelper(output);
}
[Fact]
public void Intimidate_Works()
{
#region Setup
PBEDataProvider.GlobalRandom.Seed = 0;
PBESettings settings = PBESettings.DefaultSettings;
var p0 = new TestPokemonCollection(3);
p0[0] = new TestPokemon(settings, PBESpecies.Shuckle, 0, 100, PBEMove.Splash);
p0[1] = new TestPokemon(settings, PBESpecies.Magikarp, 0, 100, PBEMove.Splash);
p0[2] = new TestPokemon(settings, PBESpecies.Happiny, 0, 100, PBEMove.Splash);
var p1 = new TestPokemonCollection(2);
p1[0] = new TestPokemon(settings, PBESpecies.Luxray, 0, 100, PBEMove.Splash)
{
Ability = PBEAbility.Intimidate
};
p1[1] = new TestPokemon(settings, PBESpecies.Skitty, 0, 100, PBEMove.Splash);
var battle = PBEBattle.CreateTrainerBattle(PBEBattleFormat.Triple, settings, new PBETrainerInfo(p0, "Trainer 0", false), new PBETrainerInfo(p1, "Trainer 1", false));
battle.OnNewEvent += PBEBattle.ConsoleBattleEventHandler;
PBETrainer t0 = battle.Trainers[0];
PBETrainer t1 = battle.Trainers[1];
PBEBattlePokemon shuckle = t0.Party[0];
PBEBattlePokemon magikarp = t0.Party[1];
PBEBattlePokemon happiny = t0.Party[2];
PBEBattlePokemon luxray = t1.Party[0];
PBEBattlePokemon skitty = t1.Party[1];
battle.Begin();
#endregion
#region Check
Assert.True(battle.VerifyAbilityHappened(luxray, luxray, PBEAbility.Intimidate, PBEAbilityAction.Stats) // Activated
&& happiny.AttackChange < 0 && magikarp.AttackChange < 0 && shuckle.AttackChange == 0 && skitty.AttackChange == 0); // Hit only surrounding foes
#endregion
#region Cleanup
battle.OnNewEvent -= PBEBattle.ConsoleBattleEventHandler;
#endregion
}
[Fact]
public void Intimidate_Does_Not_Announce_If_No_Foes()
{
#region Setup
PBEDataProvider.GlobalRandom.Seed = 0;
PBESettings settings = PBESettings.DefaultSettings;
var p0 = new TestPokemonCollection(1);
p0[0] = new TestPokemon(settings, PBESpecies.Shuckle, 0, 100, PBEMove.Splash);
var p1 = new TestPokemonCollection(2);
p1[0] = new TestPokemon(settings, PBESpecies.Luxray, 0, 100, PBEMove.Splash)
{
Ability = PBEAbility.Intimidate
};
p1[1] = new TestPokemon(settings, PBESpecies.Skitty, 0, 100, PBEMove.Splash);
var battle = PBEBattle.CreateTrainerBattle(PBEBattleFormat.Triple, settings, new PBETrainerInfo(p0, "Trainer 0", false), new PBETrainerInfo(p1, "Trainer 1", false));
battle.OnNewEvent += PBEBattle.ConsoleBattleEventHandler;
PBETrainer t0 = battle.Trainers[0];
PBETrainer t1 = battle.Trainers[1];
PBEBattlePokemon shuckle = t0.Party[0];
PBEBattlePokemon luxray = t1.Party[0];
PBEBattlePokemon skitty = t1.Party[1];
battle.Begin();
#endregion
#region Check
Assert.False(battle.VerifyAbilityHappened(luxray, luxray, PBEAbility.Intimidate, PBEAbilityAction.Stats)); // Did not activate
#endregion
#region Cleanup
battle.OnNewEvent -= PBEBattle.ConsoleBattleEventHandler;
#endregion
}
[Fact]
public void Intimidate_Does_Not_Hit_Through_Substitute()
{
#region Setup
PBEDataProvider.GlobalRandom.Seed = 0;
PBESettings settings = PBESettings.DefaultSettings;
var p0 = new TestPokemonCollection(1);
p0[0] = new TestPokemon(settings, PBESpecies.Shuckle, 0, 100, PBEMove.Substitute, PBEMove.Splash);
var p1 = new TestPokemonCollection(2);
p1[0] = new TestPokemon(settings, PBESpecies.Skitty, 0, 100, PBEMove.Splash);
p1[1] = new TestPokemon(settings, PBESpecies.Luxray, 0, 100, PBEMove.Splash)
{
Ability = PBEAbility.Intimidate
};
var battle = PBEBattle.CreateTrainerBattle(PBEBattleFormat.Single, settings, new PBETrainerInfo(p0, "Trainer 0", false), new PBETrainerInfo(p1, "Trainer 1", false));
battle.OnNewEvent += PBEBattle.ConsoleBattleEventHandler;
PBETrainer t0 = battle.Trainers[0];
PBETrainer t1 = battle.Trainers[1];
PBEBattlePokemon shuckle = t0.Party[0];
PBEBattlePokemon skitty = t1.Party[0];
PBEBattlePokemon luxray = t1.Party[1];
battle.Begin();
#endregion
#region Use Substitute
Assert.True(t0.SelectActionsIfValid(out _, new PBETurnAction(shuckle, PBEMove.Substitute, PBETurnTarget.AllyCenter)));
Assert.True(t1.SelectActionsIfValid(out _, new PBETurnAction(skitty, PBEMove.Splash, PBETurnTarget.AllyCenter)));
battle.RunTurn();
Assert.True(shuckle.Status2.HasFlag(PBEStatus2.Substitute));
#endregion
#region Switch in Luxray and check
Assert.True(t0.SelectActionsIfValid(out _, new PBETurnAction(shuckle, PBEMove.Splash, PBETurnTarget.AllyCenter)));
Assert.True(t1.SelectActionsIfValid(out _, new PBETurnAction(skitty, luxray)));
battle.RunTurn();
Assert.True(battle.VerifyAbilityHappened(luxray, luxray, PBEAbility.Intimidate, PBEAbilityAction.Stats) // Activated
&& battle.VerifyMoveResultHappened(luxray, shuckle, PBEResult.Ineffective_Substitute) && shuckle.AttackChange == 0); // Did not affect
#endregion
#region Cleanup
battle.OnNewEvent -= PBEBattle.ConsoleBattleEventHandler;
#endregion
}
}
| 412 | 0.837745 | 1 | 0.837745 | game-dev | MEDIA | 0.9514 | game-dev | 0.546835 | 1 | 0.546835 |
frengor/UltimateAdvancementAPI | 3,590 | NMS/1_18_R2/src/main/java/com/fren_gor/ultimateAdvancementAPI/nms/v1_18_R2/advancement/AdvancementDisplayWrapper_v1_18_R2.java | package com.fren_gor.ultimateAdvancementAPI.nms.v1_18_R2.advancement;
import com.fren_gor.ultimateAdvancementAPI.nms.v1_18_R2.Util;
import com.fren_gor.ultimateAdvancementAPI.nms.wrappers.advancement.AdvancementDisplayWrapper;
import com.fren_gor.ultimateAdvancementAPI.nms.wrappers.advancement.AdvancementFrameTypeWrapper;
import net.md_5.bungee.api.chat.BaseComponent;
import net.minecraft.advancements.DisplayInfo;
import net.minecraft.advancements.FrameType;
import net.minecraft.resources.ResourceLocation;
import org.bukkit.craftbukkit.v1_18_R2.inventory.CraftItemStack;
import org.bukkit.craftbukkit.v1_18_R2.util.CraftChatMessage;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class AdvancementDisplayWrapper_v1_18_R2 extends AdvancementDisplayWrapper {
private final DisplayInfo display;
private final AdvancementFrameTypeWrapper frameType;
public AdvancementDisplayWrapper_v1_18_R2(@NotNull ItemStack icon, @NotNull String title, @NotNull String description, @NotNull AdvancementFrameTypeWrapper frameType, float x, float y, boolean showToast, boolean announceChat, boolean hidden, @Nullable String backgroundTexture) {
ResourceLocation background = backgroundTexture == null ? null : new ResourceLocation(backgroundTexture);
this.display = new DisplayInfo(CraftItemStack.asNMSCopy(icon), Util.fromString(title), Util.fromString(description), background, (FrameType) frameType.toNMS(), showToast, announceChat, hidden);
this.display.setLocation(x, y);
this.frameType = frameType;
}
public AdvancementDisplayWrapper_v1_18_R2(@NotNull ItemStack icon, @NotNull BaseComponent title, @NotNull BaseComponent description, @NotNull AdvancementFrameTypeWrapper frameType, float x, float y, boolean showToast, boolean announceChat, boolean hidden, @Nullable String backgroundTexture) {
ResourceLocation background = backgroundTexture == null ? null : new ResourceLocation(backgroundTexture);
this.display = new DisplayInfo(CraftItemStack.asNMSCopy(icon), Util.fromComponent(title), Util.fromComponent(description), background, (FrameType) frameType.toNMS(), showToast, announceChat, hidden);
this.display.setLocation(x, y);
this.frameType = frameType;
}
@Override
@NotNull
public ItemStack getIcon() {
return CraftItemStack.asBukkitCopy(display.getIcon());
}
@Override
@NotNull
public String getTitle() {
return CraftChatMessage.fromComponent(display.getTitle());
}
@Override
@NotNull
public String getDescription() {
return CraftChatMessage.fromComponent(display.getDescription());
}
@Override
@NotNull
public AdvancementFrameTypeWrapper getAdvancementFrameType() {
return frameType;
}
@Override
public float getX() {
return display.getX();
}
@Override
public float getY() {
return display.getY();
}
@Override
public boolean doesShowToast() {
return display.shouldShowToast();
}
@Override
public boolean doesAnnounceToChat() {
return display.shouldAnnounceChat();
}
@Override
public boolean isHidden() {
return display.isHidden();
}
@Override
@Nullable
public String getBackgroundTexture() {
ResourceLocation r = display.getBackground();
return r == null ? null : r.toString();
}
@Override
@NotNull
public DisplayInfo toNMS() {
return display;
}
}
| 412 | 0.872851 | 1 | 0.872851 | game-dev | MEDIA | 0.940143 | game-dev | 0.83844 | 1 | 0.83844 |
PetteriM1/NukkitPetteriM1Edition | 2,664 | src/main/java/cn/nukkit/level/util/Pow2BitArray.java | package cn.nukkit.level.util;
import cn.nukkit.math.MathHelper;
import java.util.Arrays;
public class Pow2BitArray implements BitArray {
/**
* Array used to store data
*/
private final int[] words;
/**
* Palette version information
*/
private final BitArrayVersion version;
/**
* Number of entries in this palette (<b>not</b> the length of the words array that internally backs this palette)
*/
private final int size;
Pow2BitArray(BitArrayVersion version, int size, int[] words) {
this.size = size;
this.version = version;
this.words = words;
int expectedWordsLength = MathHelper.ceil((float) size / version.entriesPerWord);
if (words.length != expectedWordsLength) {
throw new IllegalArgumentException("Invalid length given for storage, got: " + words.length +
" but expected: " + expectedWordsLength);
}
}
/**
* Sets the entry at the given location to the given value
*/
public void set(int index, int value) {
if (index < 0 || index >= this.size) {
throw new IndexOutOfBoundsException();
}
if (value < 0 || value > this.version.maxEntryValue) {
throw new IllegalArgumentException(String.format("Max value: %s. Received value %s", this.version.maxEntryValue, value));
}
int bitIndex = index * this.version.bits;
int arrayIndex = bitIndex >> 5;
int offset = bitIndex & 31;
this.words[arrayIndex] = this.words[arrayIndex] & ~(this.version.maxEntryValue << offset) | (value & this.version.maxEntryValue) << offset;
}
/**
* Gets the entry at the given index
*/
public int get(int index) {
if (index < 0 || index >= this.size) {
throw new IndexOutOfBoundsException();
}
int bitIndex = index * this.version.bits;
int arrayIndex = bitIndex >> 5;
int wordOffset = bitIndex & 31;
return this.words[arrayIndex] >>> wordOffset & this.version.maxEntryValue;
}
/**
* Gets the long array that is used to store the data in this BitArray. This is useful for sending packet data.
*/
public int size() {
return this.size;
}
/**
* {@inheritDoc}
*
* @return {@inheritDoc}
*/
@Override
public int[] getWords() {
return this.words;
}
public BitArrayVersion getVersion() {
return version;
}
@Override
public BitArray copy() {
return new Pow2BitArray(this.version, this.size, Arrays.copyOf(this.words, this.words.length));
}
}
| 412 | 0.872261 | 1 | 0.872261 | game-dev | MEDIA | 0.271963 | game-dev | 0.879415 | 1 | 0.879415 |
magefree/mage | 3,754 | Mage.Sets/src/mage/cards/c/ChainsOfMephistopheles.java |
package mage.cards.c;
import java.util.UUID;
import mage.abilities.Ability;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.effects.Effect;
import mage.abilities.effects.ReplacementEffectImpl;
import mage.abilities.effects.common.MillCardsTargetEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.game.Game;
import mage.game.events.GameEvent;
import mage.players.Player;
import mage.target.targetpointer.FixedTarget;
import mage.watchers.common.CardsDrawnDuringDrawStepWatcher;
/**
*
* @author LevelX2
*/
public final class ChainsOfMephistopheles extends CardImpl {
public ChainsOfMephistopheles(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT},"{1}{B}");
// If a player would draw a card except the first one they draw in their draw step each turn, that player discards a card instead. If the player discards a card this way, they draw a card. If the player doesn't discard a card this way, they put the top card of their library into their graveyard.
this.addAbility(new SimpleStaticAbility(new ChainsOfMephistophelesReplacementEffect()), new CardsDrawnDuringDrawStepWatcher());
}
private ChainsOfMephistopheles(final ChainsOfMephistopheles card) {
super(card);
}
@Override
public ChainsOfMephistopheles copy() {
return new ChainsOfMephistopheles(this);
}
}
class ChainsOfMephistophelesReplacementEffect extends ReplacementEffectImpl {
ChainsOfMephistophelesReplacementEffect() {
super(Duration.WhileOnBattlefield, Outcome.Benefit);
staticText = "If a player would draw a card except the first one they draw in each of their draw steps, that player discards a card instead. If the player discards a card this way, they draw a card. If the player doesn't discard a card this way, they mill a card";
}
private ChainsOfMephistophelesReplacementEffect(final ChainsOfMephistophelesReplacementEffect effect) {
super(effect);
}
@Override
public ChainsOfMephistophelesReplacementEffect copy() {
return new ChainsOfMephistophelesReplacementEffect(this);
}
@Override
public boolean replaceEvent(GameEvent event, Ability source, Game game) {
Player player = game.getPlayer(event.getPlayerId());
if (player != null) {
if (player.getHand().isEmpty()) {
// they put the top card of their library into their graveyard
Effect effect = new MillCardsTargetEffect(1);
effect.setTargetPointer(new FixedTarget(event.getPlayerId()));
effect.apply(game, source);
return true;
} else {
// discards a card instead. If the player discards a card this way, they draw a card.
player.discard(1, false, false, source, game);
return false; // because player draws a card, the draw event is kept
}
}
return false;
}
@Override
public boolean checksEventType(GameEvent event, Game game) {
return event.getType() == GameEvent.EventType.DRAW_CARD;
}
@Override
public boolean applies(GameEvent event, Ability source, Game game) {
if (game.isActivePlayer(event.getPlayerId()) && game.getPhase().getStep().getType() == PhaseStep.DRAW) {
CardsDrawnDuringDrawStepWatcher watcher = game.getState().getWatcher(CardsDrawnDuringDrawStepWatcher.class);
if (watcher != null && watcher.getAmountCardsDrawn(event.getPlayerId()) > 0) {
return true;
}
} else {
return true;
}
return false;
}
}
| 412 | 0.982348 | 1 | 0.982348 | game-dev | MEDIA | 0.949493 | game-dev | 0.941544 | 1 | 0.941544 |
LordOfDragons/dragengine | 2,645 | src/deigde/editors/conversation/src/undosys/action/coordSystemRemove/ceUCACoordSysRemoveSetCoordSysID.cpp | /*
* MIT License
*
* Copyright (C) 2024, DragonDreams GmbH (info@dragondreams.ch)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "ceUCACoordSysRemoveSetCoordSysID.h"
#include "../../../conversation/ceConversation.h"
#include "../../../conversation/action/ceCACoordSystemRemove.h"
#include "../../../conversation/topic/ceConversationTopic.h"
#include <dragengine/common/exceptions.h>
// Class ceUCACoordSysRemoveSetCoordSysID
///////////////////////////////////////////
// Constructor, destructor
////////////////////////////
ceUCACoordSysRemoveSetCoordSysID::ceUCACoordSysRemoveSetCoordSysID( ceConversationTopic *topic,
ceCACoordSystemRemove *action, const char *newCoordSystemID ){
if( ! topic || ! newCoordSystemID ){
DETHROW( deeInvalidParam );
}
pTopic = NULL;
pAction = NULL;
pOldCoordSystemID = action->GetCoordSystemID();
pNewCoordSystemID = newCoordSystemID;
SetShortInfo( "Coord system remove set coord system id" );
pTopic = topic;
topic->AddReference();
pAction = action;
action->AddReference();
}
ceUCACoordSysRemoveSetCoordSysID::~ceUCACoordSysRemoveSetCoordSysID(){
if( pAction ){
pAction->FreeReference();
}
if( pTopic ){
pTopic->FreeReference();
}
}
// Management
///////////////
void ceUCACoordSysRemoveSetCoordSysID::Undo(){
pAction->SetCoordSystemID( pOldCoordSystemID.GetString() );
pTopic->NotifyActionChanged( pAction );
}
void ceUCACoordSysRemoveSetCoordSysID::Redo(){
pAction->SetCoordSystemID( pNewCoordSystemID.GetString() );
pTopic->NotifyActionChanged( pAction );
}
| 412 | 0.936718 | 1 | 0.936718 | game-dev | MEDIA | 0.720093 | game-dev | 0.683843 | 1 | 0.683843 |
getnamo/MassCommunitySample | 3,416 | Source/MassCommunitySample/Common/Misc/SpacedGridLocationsSpawnDataGenerator.h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "MassEntitySpawnDataGeneratorBase.h"
#include "MassSpawnLocationProcessor.h"
#include "MassSpawnerTypes.h"
#include "SpacedGridLocationsSpawnDataGenerator.generated.h"
/**
*
*/
UCLASS(BlueprintType)
class MASSCOMMUNITYSAMPLE_API USpacedGridLocationsSpawnDataGenerator : public UMassEntitySpawnDataGeneratorBase
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere,BlueprintReadWrite)
double Spacing = 100.0f;
virtual void Generate(UObject& QueryOwner, TConstArrayView<FMassSpawnedEntityType> EntityTypes, int32 Count,
FFinishedGeneratingSpawnDataSignature& FinishedGeneratingSpawnPointsDelegate) const override
{
const FTransform& OwnerTransform = CastChecked<AActor>(&QueryOwner)->GetTransform();
if (Count <= 0 || !OwnerTransform.IsValid())
{
FinishedGeneratingSpawnPointsDelegate.Execute(TArray<FMassEntitySpawnDataGeneratorResult>());
}
TArray<FMassEntitySpawnDataGeneratorResult> Results;
BuildResultsFromEntityTypes(Count, EntityTypes, Results);
TArray<int32> NumLeftPerResults;
{
int32 CountPostBuildResults = 0;
for (FMassEntitySpawnDataGeneratorResult& Res : Results)
{
Res.SpawnDataProcessor = UMassSpawnLocationProcessor::StaticClass();
Res.SpawnData.InitializeAs<FMassTransformsSpawnData>();
FMassTransformsSpawnData& Transforms = Res.SpawnData.GetMutable<FMassTransformsSpawnData>();
Transforms.Transforms.SetNumUninitialized(Res.NumEntities);
NumLeftPerResults.Add(Res.NumEntities);
CountPostBuildResults += Res.NumEntities;
}
Count = CountPostBuildResults;
}
int32 SquaredRows = FMath::Sqrt((float)Count);
const FVector BaseLocation = OwnerTransform.GetLocation();
// Distribute points in the grid
TArray<int32> Grid;
Grid.SetNum(SquaredRows);
for (int32 i = 0; i < SquaredRows; i++)
{
Grid[i] = SquaredRows;
}
// Handle leftover points
int32 Remaining = Count - (SquaredRows * SquaredRows);
while (Remaining > 0)
{
if (Remaining >= SquaredRows)
{
// If there's enough points to fill a row, add a row
int32 NewRow = SquaredRows;
Grid.Add(NewRow);
Remaining -= SquaredRows;
}
else
{
// If there's less than a row's worth of points, add them to a new row
int32 NewRow = Remaining;
Grid.Add(NewRow);
Remaining = 0;
}
}
// Stuff them all into our results randomly
int32 ResultsIndex = 0;
for (int32 i = 0; i < Grid.Num(); i++)
{
for (int32 j = 0; j < Grid[i]; ++j)
{
FTransform NewTransform = FTransform(BaseLocation + FVector(i*Spacing,j*Spacing,0));
NewTransform.SetRotation(OwnerTransform.Rotator().Quaternion());
// scatter the transforms we make over the results instead of making more arrays
while(ResultsIndex <= NumLeftPerResults.Num())
{
int32 ResultNumLeft = NumLeftPerResults[ResultsIndex];
if(ResultNumLeft > 0)
{
FMassEntitySpawnDataGeneratorResult& Res = Results[ResultsIndex];
FMassTransformsSpawnData& TransformData = Res.SpawnData.GetMutable<FMassTransformsSpawnData>();
TransformData.Transforms[ResultNumLeft - 1] = NewTransform;
--NumLeftPerResults[ResultsIndex];
break;
}
ResultsIndex++;
}
}
}
FinishedGeneratingSpawnPointsDelegate.Execute(Results);
};
};
| 412 | 0.840195 | 1 | 0.840195 | game-dev | MEDIA | 0.177396 | game-dev | 0.955191 | 1 | 0.955191 |
qiutang98/flower | 4,601 | source/engine/asset/asset_manager.cpp | #include "asset_manager.h"
#include "../graphics/context.h"
#include "../engine.h"
namespace engine
{
AssetManager* engine::getAssetManager()
{
static AssetManager* manager = Engine::get()->getRuntimeModule<AssetManager>();
return manager;
}
void AssetManager::registerCheck(Engine* engine)
{
}
bool AssetManager::init()
{
return true;
}
bool AssetManager::tick(const RuntimeModuleTickData& tickData)
{
return true;
}
bool AssetManager::beforeRelease()
{
return true;
}
bool AssetManager::release()
{
return true;
}
void AssetManager::setupProject(const std::filesystem::path& inProjectPath)
{
ZoneScopedN("vAssetManager::setupProject(const std::filesystem::path&)");
m_bProjectSetup = true;
m_projectConfig.rootPath = inProjectPath.parent_path().u16string();
m_projectConfig.projectFilePath = inProjectPath.u16string();
m_projectConfig.projectName = inProjectPath.filename().replace_extension().u16string();
m_projectConfig.assetPath = (inProjectPath.parent_path() / "asset" ).u16string();
m_projectConfig.cachePath = (inProjectPath.parent_path() / "cache" ).u16string();
m_projectConfig.configPath = (inProjectPath.parent_path() / "config").u16string();
m_projectConfig.logPath = (inProjectPath.parent_path() / "log" ).u16string();
// Scan whole asset folder to setup asset uuid map.
setupProjectRecursive(m_projectConfig.assetPath);
}
void AssetManager::setupProjectRecursive(const std::filesystem::path& path)
{
ZoneScopedN("AssetManager::setupProjectRecursive(const std::filesystem::path&)");
const bool bFolder = std::filesystem::is_directory(path);
if (bFolder)
{
for (const auto& entry : std::filesystem::directory_iterator(path))
{
setupProjectRecursive(entry);
}
}
else
{
const auto extension = path.extension().string();
if (extension.starts_with(".dark"))
{
tryLoadAsset(path);
}
}
}
void AssetManager::onAssetDirty(std::shared_ptr<AssetInterface> asset)
{
std::lock_guard<std::recursive_mutex> lock(m_assetManagerMutex);
const auto& id = asset->getSaveInfo().getUUID();
// You must mark asset self dirty before register in manager.
CHECK(asset->isDirty());
// Asset must exist.
CHECK(m_assets.at(id));
// Add asset to dirty asset map.
m_dirtyAssetIds.insert(asset->getSaveInfo().getUUID());
}
void AssetManager::onAssetChangeSaveInfo(
std::shared_ptr<AssetInterface> asset, const AssetSaveInfo& newInfo)
{
std::lock_guard<std::recursive_mutex> lock(m_assetManagerMutex);
if (asset->getSaveInfo() != newInfo)
{
CHECK(m_assets.at(asset->getSaveInfo().getUUID()));
CHECK(!m_assets.contains(newInfo.getUUID()));
const auto& uuid = asset->getSaveInfo().getUUID();
removeAsset(uuid, true);
insertAsset(newInfo.getUUID(), asset, true);
}
}
void AssetManager::onAssetSaved(std::shared_ptr<AssetInterface> asset)
{
std::lock_guard<std::recursive_mutex> lock(m_assetManagerMutex);
const auto& id = asset->getSaveInfo().getUUID();
// Must dirty before call discard.
CHECK(m_dirtyAssetIds.contains(id));
// Clear cache in dirty asset map and asset map.
m_dirtyAssetIds.erase(id);
}
std::shared_ptr<AssetInterface> AssetManager::removeAsset(const UUID& id, bool bClearDirty)
{
std::lock_guard<std::recursive_mutex> lock(m_assetManagerMutex);
if (std::shared_ptr<AssetInterface> asset = m_assets[id])
{
std::filesystem::path savePath = asset->getSaveInfo().getStorePath();
if (bClearDirty)
{
m_dirtyAssetIds.erase(id);
}
m_assets.erase(id);
m_assetTypeMap[savePath.extension().string()].erase(id);
return asset;
}
return nullptr;
}
void AssetManager::insertAsset(const UUID& uuid, std::shared_ptr<AssetInterface> asset, bool bCareDirtyState)
{
std::filesystem::path savePath = asset->getSaveInfo().getStorePath();
m_assets[uuid] = asset;
m_assetTypeMap[savePath.extension().string()].insert(uuid);
if (asset->isDirty() && bCareDirtyState)
{
m_dirtyAssetIds.insert(uuid);
}
}
void AssetManager::onAssetUnload(std::shared_ptr<AssetInterface> asset)
{
std::lock_guard<std::recursive_mutex> lock(m_assetManagerMutex);
removeAsset(asset->getSaveInfo().getUUID(), false);
}
void AssetManager::onDiscardChanged(std::shared_ptr<AssetInterface> asset)
{
std::lock_guard<std::recursive_mutex> lock(m_assetManagerMutex);
const auto& id = asset->getSaveInfo().getUUID();
// Must dirty before call discard.
CHECK(asset->isDirty());
// Discard id all cache.
removeAsset(id, true);
}
} | 412 | 0.993102 | 1 | 0.993102 | game-dev | MEDIA | 0.903865 | game-dev | 0.899015 | 1 | 0.899015 |
MagmaGuy/FreeMinecraftModels | 1,572 | src/main/java/com/magmaguy/freeminecraftmodels/commands/DisguiseCommand.java | package com.magmaguy.freeminecraftmodels.commands;
import com.magmaguy.freeminecraftmodels.customentity.PlayerDisguiseEntity;
import com.magmaguy.freeminecraftmodels.dataconverter.FileModelConverter;
import com.magmaguy.magmacore.command.AdvancedCommand;
import com.magmaguy.magmacore.command.CommandData;
import com.magmaguy.magmacore.command.SenderType;
import com.magmaguy.magmacore.command.arguments.ListStringCommandArgument;
import com.magmaguy.magmacore.util.Logger;
import java.util.ArrayList;
import java.util.List;
public class DisguiseCommand extends AdvancedCommand {
List<String> entityIDs = new ArrayList<>();
public DisguiseCommand() {
super(List.of("disguise"));
setDescription("Disguises a player as a model");
setPermission("freeminecraftmodels.*");
setDescription("/fmm disguise <modelID>");
setSenderType(SenderType.PLAYER);
entityIDs = new ArrayList<>();
FileModelConverter.getConvertedFileModels().values().forEach(fileModelConverter -> entityIDs.add(fileModelConverter.getID()));
addArgument("models", new ListStringCommandArgument(entityIDs, "<modelID>"));
}
@Override
public void execute(CommandData commandData) {
if (!entityIDs.contains(commandData.getStringArgument("models"))) {
Logger.sendMessage(commandData.getCommandSender(), "Invalid entity ID!");
return;
}
PlayerDisguiseEntity.create(
commandData.getStringArgument("models"),
commandData.getPlayerSender());
}
}
| 412 | 0.879996 | 1 | 0.879996 | game-dev | MEDIA | 0.90889 | game-dev | 0.869302 | 1 | 0.869302 |
natbro/kaon | 18,028 | lsteamclient/lsteamclient/steamworks_sdk_116x/isteamremotestorage.h | //====== Copyright 1996-2008, Valve Corporation, All rights reserved. =======
//
// Purpose: public interface to user remote file storage in Steam
//
//=============================================================================
#ifndef ISTEAMREMOTESTORAGE_H
#define ISTEAMREMOTESTORAGE_H
#ifdef _WIN32
#pragma once
#endif
#include "isteamclient.h"
//-----------------------------------------------------------------------------
// Purpose: Structure that contains an array of const char * strings and the number of those strings
//-----------------------------------------------------------------------------
#pragma pack( push, 8 )
struct SteamParamStringArray_t
{
const char ** m_ppStrings;
int32 m_nNumStrings;
};
#pragma pack( pop )
// A handle to a piece of user generated content
typedef uint64 UGCHandle_t;
typedef uint64 PublishedFileId_t;
const UGCHandle_t k_UGCHandleInvalid = 0xffffffffffffffffull;
const uint32 k_cchPublishedDocumentTitleMax = 128 + 1;
const uint32 k_cchPublishedDocumentDescriptionMax = 256 + 1;
const uint32 k_unEnumeratePublishedFilesMaxResults = 50;
const uint32 k_cchTagListMax = 1024 + 1;
const uint32 k_cchFilenameMax = 260;
// Ways to handle a synchronization conflict
enum EResolveConflict
{
k_EResolveConflictKeepClient = 1, // The local version of each file will be used to overwrite the server version
k_EResolveConflictKeepServer = 2, // The server version of each file will be used to overwrite the local version
};
enum ERemoteStoragePlatform
{
k_ERemoteStoragePlatformNone = 0,
k_ERemoteStoragePlatformWindows = (1 << 0),
k_ERemoteStoragePlatformOSX = (1 << 1 ),
k_ERemoteStoragePlatformPS3 = (1 << 2),
k_ERemoteStoragePlatformReserved1 = (1 << 3),
k_ERemoteStoragePlatformReserved2 = (1 << 4),
k_ERemoteStoragePlatformAll = 0xffffffff
};
enum ERemoteStoragePublishedFileVisibility
{
k_ERemoteStoragePublishedFileVisibilityPublic = 0,
k_ERemoteStoragePublishedFileVisibilityFriendsOnly = 1,
k_ERemoteStoragePublishedFileVisibilityPrivate = 2,
};
//-----------------------------------------------------------------------------
// Purpose: helper structure for making updates to published files.
// make sure to update serialization/deserialization in interfacemap.cpp if new properties are added
//-----------------------------------------------------------------------------
#pragma pack( push, 8 )
struct RemoteStorageUpdatePublishedFileRequest_t
{
public:
RemoteStorageUpdatePublishedFileRequest_t()
{
Initialize( k_GIDNil );
}
RemoteStorageUpdatePublishedFileRequest_t( PublishedFileId_t unPublishedFileId )
{
Initialize( unPublishedFileId );
}
PublishedFileId_t GetPublishedFileId() { return m_unPublishedFileId; }
void SetFile( const char *pchFile )
{
m_pchFile = pchFile;
m_bUpdateFile = true;
}
const char *GetFile() { return m_pchFile; }
bool BUpdateFile() { return m_bUpdateFile; }
void SetPreviewFile( const char *pchPreviewFile )
{
m_pchPreviewFile = pchPreviewFile;
m_bUpdatePreviewFile = true;
}
const char *GetPreviewFile() { return m_pchPreviewFile; }
bool BUpdatePreviewFile() { return m_bUpdatePreviewFile; }
void SetTitle( const char *pchTitle )
{
m_pchTitle = pchTitle;
m_bUpdateTitle = true;
}
const char *GetTitle() { return m_pchTitle; }
bool BUpdateTitle() { return m_bUpdateTitle; }
void SetDescription( const char *pchDescription )
{
m_pchDescription = pchDescription;
m_bUpdateDescription = true;
}
const char *GetDescription() { return m_pchDescription; }
bool BUpdateDescription() { return m_bUpdateDescription; }
void SetVisibility( ERemoteStoragePublishedFileVisibility eVisibility )
{
m_eVisibility = eVisibility;
m_bUpdateVisibility = true;
}
const ERemoteStoragePublishedFileVisibility GetVisibility() { return m_eVisibility; }
bool BUpdateVisibility() { return m_bUpdateVisibility; }
void SetTags( SteamParamStringArray_t *pTags )
{
m_pTags = pTags;
m_bUpdateTags = true;
}
SteamParamStringArray_t *GetTags() { return m_pTags; }
bool BUpdateTags() { return m_bUpdateTags; }
SteamParamStringArray_t **GetTagsPointer() { return &m_pTags; }
void Initialize( PublishedFileId_t unPublishedFileId )
{
m_unPublishedFileId = unPublishedFileId;
m_pchFile = 0;
m_pchPreviewFile = 0;
m_pchTitle = 0;
m_pchDescription = 0;
m_pTags = 0;
m_bUpdateFile = false;
m_bUpdatePreviewFile = false;
m_bUpdateTitle = false;
m_bUpdateDescription = false;
m_bUpdateTags = false;
m_bUpdateVisibility = false;
}
private:
PublishedFileId_t m_unPublishedFileId;
const char *m_pchFile;
const char *m_pchPreviewFile;
const char *m_pchTitle;
const char *m_pchDescription;
ERemoteStoragePublishedFileVisibility m_eVisibility;
SteamParamStringArray_t *m_pTags;
bool m_bUpdateFile;
bool m_bUpdatePreviewFile;
bool m_bUpdateTitle;
bool m_bUpdateDescription;
bool m_bUpdateVisibility;
bool m_bUpdateTags;
};
#pragma pack( pop )
//-----------------------------------------------------------------------------
// Purpose: Functions for accessing, reading and writing files stored remotely
// and cached locally
//-----------------------------------------------------------------------------
class ISteamRemoteStorage
{
public:
// NOTE
//
// Filenames are case-insensitive, and will be converted to lowercase automatically.
// So "foo.bar" and "Foo.bar" are the same file, and if you write "Foo.bar" then
// iterate the files, the filename returned will be "foo.bar".
//
// file operations
virtual bool FileWrite( const char *pchFile, const void *pvData, int32 cubData ) = 0;
virtual int32 FileRead( const char *pchFile, void *pvData, int32 cubDataToRead ) = 0;
virtual bool FileForget( const char *pchFile ) = 0;
virtual bool FileDelete( const char *pchFile ) = 0;
virtual SteamAPICall_t FileShare( const char *pchFile ) = 0;
virtual bool SetSyncPlatforms( const char *pchFile, ERemoteStoragePlatform eRemoteStoragePlatform ) = 0;
// file information
virtual bool FileExists( const char *pchFile ) = 0;
virtual bool FilePersisted( const char *pchFile ) = 0;
virtual int32 GetFileSize( const char *pchFile ) = 0;
virtual int64 GetFileTimestamp( const char *pchFile ) = 0;
virtual ERemoteStoragePlatform GetSyncPlatforms( const char *pchFile ) = 0;
// iteration
virtual int32 GetFileCount() = 0;
virtual const char *GetFileNameAndSize( int iFile, int32 *pnFileSizeInBytes ) = 0;
// configuration management
virtual bool GetQuota( int32 *pnTotalBytes, int32 *puAvailableBytes ) = 0;
virtual bool IsCloudEnabledForAccount() = 0;
virtual bool IsCloudEnabledForApp() = 0;
virtual void SetCloudEnabledForApp( bool bEnabled ) = 0;
// user generated content
virtual SteamAPICall_t UGCDownload( UGCHandle_t hContent ) = 0;
virtual bool GetUGCDetails( UGCHandle_t hContent, AppId_t *pnAppID, char **ppchName, int32 *pnFileSizeInBytes, CSteamID *pSteamIDOwner ) = 0;
virtual int32 UGCRead( UGCHandle_t hContent, void *pvData, int32 cubDataToRead ) = 0;
// user generated content iteration
virtual int32 GetCachedUGCCount() = 0;
virtual UGCHandle_t GetCachedUGCHandle( int32 iCachedContent ) = 0;
// The following functions are only necessary on the Playstation 3. On PC & Mac, the Steam client will handle these operations for you
// On Playstation 3, the game controls which files are stored in the cloud, via FilePersist, FileFetch, and FileForget.
#if defined(_PS3) || defined(_SERVER)
// Connect to Steam and get a list of files in the Cloud - results in a RemoteStorageAppSyncStatusCheck_t callback
virtual void GetFileListFromServer() = 0;
// Indicate this file should be downloaded in the next sync
virtual bool FileFetch( const char *pchFile ) = 0;
// Indicate this file should be persisted in the next sync
virtual bool FilePersist( const char *pchFile ) = 0;
// Pull any requested files down from the Cloud - results in a RemoteStorageAppSyncedClient_t callback
virtual bool SynchronizeToClient() = 0;
// Upload any requested files to the Cloud - results in a RemoteStorageAppSyncedServer_t callback
virtual bool SynchronizeToServer() = 0;
// Reset any fetch/persist/etc requests
virtual bool ResetFileRequestState() = 0;
#endif
// publishing UGC
virtual SteamAPICall_t PublishFile( const char *pchFile, const char *pchPreviewFile, AppId_t nConsumerAppId, const char *pchTitle, const char *pchDescription, ERemoteStoragePublishedFileVisibility eVisibility, SteamParamStringArray_t *pTags ) = 0;
virtual SteamAPICall_t PublishWorkshopFile( const char *pchFile, const char *pchPreviewFile, AppId_t nConsumerAppId, const char *pchTitle, const char *pchDescription, SteamParamStringArray_t *pTags ) = 0;
virtual SteamAPICall_t UpdatePublishedFile( RemoteStorageUpdatePublishedFileRequest_t updatePublishedFileRequest ) = 0;
virtual SteamAPICall_t GetPublishedFileDetails( PublishedFileId_t unPublishedFileId ) = 0;
virtual SteamAPICall_t DeletePublishedFile( PublishedFileId_t unPublishedFileId ) = 0;
virtual SteamAPICall_t EnumerateUserPublishedFiles( uint32 unStartIndex ) = 0;
virtual SteamAPICall_t SubscribePublishedFile( PublishedFileId_t unPublishedFileId ) = 0;
virtual SteamAPICall_t EnumerateUserSubscribedFiles( uint32 unStartIndex ) = 0;
virtual SteamAPICall_t UnsubscribePublishedFile( PublishedFileId_t unPublishedFileId ) = 0;
};
#define STEAMREMOTESTORAGE_INTERFACE_VERSION "STEAMREMOTESTORAGE_INTERFACE_VERSION005"
// callbacks
#pragma pack( push, 8 )
//-----------------------------------------------------------------------------
// Purpose: sent when the local file cache is fully synced with the server for an app
// That means that an application can be started and has all latest files
//-----------------------------------------------------------------------------
struct RemoteStorageAppSyncedClient_t
{
enum { k_iCallback = k_iClientRemoteStorageCallbacks + 1 };
AppId_t m_nAppID;
EResult m_eResult;
int m_unNumDownloads;
};
//-----------------------------------------------------------------------------
// Purpose: sent when the server is fully synced with the local file cache for an app
// That means that we can shutdown Steam and our data is stored on the server
//-----------------------------------------------------------------------------
struct RemoteStorageAppSyncedServer_t
{
enum { k_iCallback = k_iClientRemoteStorageCallbacks + 2 };
AppId_t m_nAppID;
EResult m_eResult;
int m_unNumUploads;
};
//-----------------------------------------------------------------------------
// Purpose: Status of up and downloads during a sync session
//
//-----------------------------------------------------------------------------
struct RemoteStorageAppSyncProgress_t
{
enum { k_iCallback = k_iClientRemoteStorageCallbacks + 3 };
char m_rgchCurrentFile[k_cchFilenameMax]; // Current file being transferred
AppId_t m_nAppID; // App this info relates to
uint32 m_uBytesTransferredThisChunk; // Bytes transferred this chunk
double m_dAppPercentComplete; // Percent complete that this app's transfers are
bool m_bUploading; // if false, downloading
};
//
// IMPORTANT! k_iClientRemoteStorageCallbacks + 4 is used, see iclientremotestorage.h
//
//-----------------------------------------------------------------------------
// Purpose: Sent after we've determined the list of files that are out of sync
// with the server.
//-----------------------------------------------------------------------------
struct RemoteStorageAppSyncStatusCheck_t
{
enum { k_iCallback = k_iClientRemoteStorageCallbacks + 5 };
AppId_t m_nAppID;
EResult m_eResult;
};
//-----------------------------------------------------------------------------
// Purpose: Sent after a conflict resolution attempt.
//-----------------------------------------------------------------------------
struct RemoteStorageConflictResolution_t
{
enum { k_iCallback = k_iClientRemoteStorageCallbacks + 6 };
AppId_t m_nAppID;
EResult m_eResult;
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to FileShare()
//-----------------------------------------------------------------------------
struct RemoteStorageFileShareResult_t
{
enum { k_iCallback = k_iClientRemoteStorageCallbacks + 7 };
EResult m_eResult; // The result of the operation
UGCHandle_t m_hFile; // The handle that can be shared with users and features
};
// k_iClientRemoteStorageCallbacks + 8 is deprecated! Do not reuse
//-----------------------------------------------------------------------------
// Purpose: The result of a call to PublishFile()
//-----------------------------------------------------------------------------
struct RemoteStoragePublishFileResult_t
{
enum { k_iCallback = k_iClientRemoteStorageCallbacks + 9 };
EResult m_eResult; // The result of the operation.
PublishedFileId_t m_nPublishedFileId;
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to GetPublishedFileDetails()
//-----------------------------------------------------------------------------
struct RemoteStorageGetPublishedFileDetailsResult_t
{
enum { k_iCallback = k_iClientRemoteStorageCallbacks + 10 };
EResult m_eResult; // The result of the operation.
PublishedFileId_t m_nPublishedFileId;
AppId_t m_nCreatorAppID; // ID of the app that created this file.
AppId_t m_nConsumerAppID; // ID of the app that created this file.
char m_rgchTitle[k_cchPublishedDocumentTitleMax]; // title of document
char m_rgchDescription[k_cchPublishedDocumentDescriptionMax]; // description of document
UGCHandle_t m_hFile; // The handle of the primary file
UGCHandle_t m_hPreviewFile; // The handle of the preview file
uint64 m_ulSteamIDOwner; // Steam ID of the user who created this content.
uint32 m_rtimeCreated; // time when the published file was created
uint32 m_rtimeUpdated; // time when the published file was last updated
ERemoteStoragePublishedFileVisibility m_eVisibility;
bool m_bBanned;
char m_rgchTags[k_cchTagListMax]; // comma separated list of all tags associated with this file
bool m_bTagsTruncated; // whether the list of tags was too long to be returned in the provided buffer
char m_pchFileName[k_cchFilenameMax]; // The name of the primary file
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to DeletePublishedFile()
//-----------------------------------------------------------------------------
struct RemoteStorageDeletePublishedFileResult_t
{
enum { k_iCallback = k_iClientRemoteStorageCallbacks + 11 };
EResult m_eResult; // The result of the operation.
PublishedFileId_t m_nPublishedFileId;
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to EnumerateUserPublishedFiles()
//-----------------------------------------------------------------------------
struct RemoteStorageEnumerateUserPublishedFilesResult_t
{
enum { k_iCallback = k_iClientRemoteStorageCallbacks + 12 };
EResult m_eResult; // The result of the operation.
int32 m_nResultsReturned;
int32 m_nTotalResultCount;
PublishedFileId_t m_rgPublishedFileId[ k_unEnumeratePublishedFilesMaxResults ];
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to SubscribePublishedFile()
//-----------------------------------------------------------------------------
struct RemoteStorageSubscribePublishedFileResult_t
{
enum { k_iCallback = k_iClientRemoteStorageCallbacks + 13 };
EResult m_eResult; // The result of the operation.
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to EnumerateSubscribePublishedFiles()
//-----------------------------------------------------------------------------
struct RemoteStorageEnumerateUserSubscribedFilesResult_t
{
enum { k_iCallback = k_iClientRemoteStorageCallbacks + 14 };
EResult m_eResult; // The result of the operation.
int32 m_nResultsReturned;
int32 m_nTotalResultCount;
PublishedFileId_t m_rgPublishedFileId[ k_unEnumeratePublishedFilesMaxResults ];
uint32 m_rgRTimeSubscribed[ k_unEnumeratePublishedFilesMaxResults ];
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to UnsubscribePublishedFile()
//-----------------------------------------------------------------------------
struct RemoteStorageUnsubscribePublishedFileResult_t
{
enum { k_iCallback = k_iClientRemoteStorageCallbacks + 15 };
EResult m_eResult; // The result of the operation.
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to UpdatePublishedFile()
//-----------------------------------------------------------------------------
struct RemoteStorageUpdatePublishedFileResult_t
{
enum { k_iCallback = k_iClientRemoteStorageCallbacks + 16 };
EResult m_eResult; // The result of the operation.
PublishedFileId_t m_nPublishedFileId;
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to UGCDownload()
//-----------------------------------------------------------------------------
struct RemoteStorageDownloadUGCResult_t
{
enum { k_iCallback = k_iClientRemoteStorageCallbacks + 17 };
EResult m_eResult; // The result of the operation.
UGCHandle_t m_hFile; // The handle to the file that was attempted to be downloaded.
AppId_t m_nAppID; // ID of the app that created this file.
int32 m_nSizeInBytes; // The size of the file that was downloaded, in bytes.
char m_pchFileName[k_cchFilenameMax]; // The name of the file that was downloaded.
uint64 m_ulSteamIDOwner; // Steam ID of the user who created this content.
};
#pragma pack( pop )
#endif // ISTEAMREMOTESTORAGE_H
| 412 | 0.963939 | 1 | 0.963939 | game-dev | MEDIA | 0.808231 | game-dev,networking | 0.597796 | 1 | 0.597796 |
ggnkua/Atari_ST_Sources | 6,881 | ASM/the Serious Cybernetics corporation (TSCC)/wlf05src/inc/Doors.s | *********************************
*
* Rules for door operation
*
* door->position holds the amount the door is open, ranging from 0 to TILEGLOBAL-1
*
* The number of doors is limited to 64 because various fields are only 6 bits
*
* Open doors conect two areas, so sounds will travel between them and sight
* will be checked when the player is in a connected area.
*
* areaconnect has a list of connected area #'s, used to create the table areabyplayer
*
* Every time a door opens or closes the areabyplayer matrix gets recalculated.
* An area is True if it connects with the player's current spor.
*
*********************************
*********************************
*
* Static door struct
*
*********************************
MAXDOORS = 64
OPENTICS = 500
DR_OPEN = 0 ; Door is fully open
DR_CLOSED = 1 ; Door is fully closed
DR_OPENING = 2 ; Door is opening
DR_CLOSING = 3 ; Door is closing
DR_WEDGEDOPEN = 4 ; Door is permenantly open
rsreset
action rs.b 1 ; Action code (See above) for door
position rs.b 1 ; Pixel position of door (0=Closed)
ticcount rs.w 1 ; Time delay before automatic closing
tilespot rs.w 1 ; Tile of the door
info rs.w 1 ; Texture of the door (Steel,Elevator)
door_t = __RS ; Length of door type
ifeq 1
rsreset
Area1 rs.b 1 ; First area
Area2 rs.b 1 ; Second area
connect_t = __RS
endc
section bss
doors ds.b MAXDOORS*door_t
*temporary*
* include 'temp\doors.s'
section text
numdoors dc.w -1
*********************************
*
* void macro OpenDoor(u32 *Door,u8 Action)
*
* Start a door opening
*
*********************************
OpenDoor macro
;cmpi.b #DR_OPEN,\2 ; Already open?
tst.b \2
bne.s .\@door_not_open
clr.w ticcount(\1) ; Reset open time (Keep open)
bra.s .\@exit
.\@door_not_open
move.b #DR_OPENING,action(\1) ; start it opening
.\@exit ; The door will be made passable when it is totally open
endm
*********************************
*
* void macro CloseDoor(u32 *Door)
*
* Start a door closing
*
*********************************
TilePtr equr d7
CloseDoor macro
; Don't close on anything solid
lea.l Actorat,a6 ; Get pointer to tile map
move.w tilespot(\1),TilePtr
adda.w TilePtr,a6
cmpi.b #DR_OPENING,action(\1) ; In the middle of opening?
beq.s .\@opening
; Don't close on an actor or bonus item
ifeq 1
tile = TilePtr[0]; /* What's the tile? */
if (tile & TI_BODY) {
door->action = DR_WEDGEDOPEN; /* bodies never go away */
return;
}
if (tile & (TI_ACTOR | TI_GETABLE) ) { /* Removable? */
door->ticcount = 60; /* wait a while before trying to close again */
return;
}
endc
btst.b #TI_THING,(a6)
bne.s .\@return
; Don't close on the player
move.w player.x,d6
move.w TilePtr,d5
add.w d5,d5 ; Faster than lsl.w #2,d5
add.w d5,d5
move.b #$80,d5
sub.w d5,d6
.\@abs_1 neg.w d6
bmi.s .\@abs_1
cmpi.w #$82+PLAYERSIZE,d6
bgt.s .\@opening
move.w player.y,d6
move.w TilePtr,d5
andi.b #63,d5
lsl.w #8,d5
move.b #$80,d5
sub.w d5,d6
.\@abs_2 neg.w d6
bmi.s .\@abs_2
cmpi.w #$82+PLAYERSIZE,d6
ble.s .\@return ; It's touching the player!
.\@opening move.b #DR_CLOSING,action(\1) ; Close the door
; make the door space a solid tile
ori.b #(1<<TI_BLOCKMOVE)|(1<<TI_BLOCKSIGHT),(a6)
move.l a0,-(sp)
movea.l SND_OPENDOOR(pc),a0
bsr.w PlaySound
movea.l (sp)+,a0
.\@return
endm
*********************************
*
* void macro OperateDoor(u16 Dooron)
*
* Open or Close a door (Press space at a door)
*
*********************************
OperateDoor macro
lea.l doors,a0 ; Which door?
adda.w \1,a0
ifeq 1
type = door->info>>1; /* Get the door type */
if ( (type==1 && !(gamestate.keys&1)) || (type==2 && !(gamestate.keys&2)) ) {
PlaySound(SND_LOCKEDDOOR); /* The door is locked */
return;
}
endc
move.b action(a0),d1
;cmpi.b #DR_OPEN,d1
;tst.b d1
beq.s .\@close_door
cmpi.b #DR_CLOSED,d1
beq.s .\@open_door
cmpi.b #DR_CLOSING,d1
beq.s .\@open_door
cmpi.b #DR_OPENING,d1
bne.s .\@break
.\@close_door CloseDoor a0 ; Close the door
bra.s .\@break
.\@open_door OpenDoor a0,d1 ; Open the door
.\@break
endm
*********************************
*
* void macro DoorOpen(u32 *Door)
*
* Close the door after a few seconds
*
*********************************
DoorOpen macro
move.w ticcounter(pc),d0
add.w d0,ticcount(\1) ; Inc the tic value
cmpi.w #OPENTICS,ticcount(\1) ; Time up?
blt.s .\@exit
move.w #OPENTICS-1,ticcount(\1) ; So if the door can't close it will keep trying
CloseDoor \1 ; Try to close the door
.\@exit
endm
*********************************
*
* void macro DoorOpening(u32 *Door)
*
* Step the door animation for open, mark as DR_OPEN if all the way open
*
*********************************
DoorOpening macro
moveq.l #0,d0
move.b position(\1),d0 ; Get the pixel position
bne.s .\@not_closed ; Fully closed?
move.l a0,-(sp)
movea.l SND_OPENDOOR(pc),a0 ; Play the door sound
bsr.w PlaySound
movea.l (sp)+,a0
.\@not_closed
; Slide the door open a bit
add.w ticcounter(pc),d0 ; Move the door a bit
cmpi.w #TILEGLOBAL-1,d0 ; Fully open?
blt.s .\@not_opened
; Door is all the way open
moveq.l #TILEGLOBAL-1,d0 ; Set to maximum
clr.w ticcount(\1) ; Reset the timer for closing
;move.b #DR_OPEN,action(\1) ; Mark as open
clr.b action(\1)
lea.l Actorat,a6 ; Mark as enterable
adda.w tilespot(\1),a6
andi.b #~(1<<TI_BLOCKMOVE)|(1<<TI_BLOCKSIGHT),(a6)
.\@not_opened move.b d0,position(\1) ; Set the new position
endm
*********************************
*
* void macro DoorClosing(u32 *Door)
*
* Step the door animation for close,
* mark as DR_CLOSED if all the way closed
*
*********************************
DoorClosing macro
moveq.l #0,d0
move.b position(\1),d0
sub.w ticcounter(pc),d0 ; Close a little more
bgt.s .\@not_closed ; Will I close now?
moveq.l #0,d0 ; Mark as closed
move.b #DR_CLOSED,action(\1) ; It's close
.\@not_closed move.b d0,position(\1) ; Set the new position
endm
*********************************
*
* void MoveDoors()
*
* Process all the doors each game loop
*
*********************************
MoveDoors move.w numdoors(pc),d2 ; How many doors to scan?
bmi.w .exit ; Any doors at all?
lea.l doors,a1 ; Pointer to the first door
.process_doors move.b action(a1),d3 ; Call the action code
;cmpi.b #DR_OPEN,d3 ; Check to close the door
;tst.b d3
bne.s .dont_open
DoorOpen a1
bra.s .break
.dont_open cmpi.b #DR_OPENING,d3 ; Continue the door opening
bne.s .not_opening
DoorOpening a1
bra.s .break
.not_opening cmpi.b #DR_CLOSING,d3 ; Close the door
bne.s .break
DoorClosing a1
.break addq.l #door_t,a1 ; Next pointer
;lea door_t(a1),a1
dbra d2,.process_doors ; Repeat until all doors are done
.exit rts | 412 | 0.63809 | 1 | 0.63809 | game-dev | MEDIA | 0.773546 | game-dev | 0.799424 | 1 | 0.799424 |
mixandjam/MGR-BladeMode | 3,908 | Assets/ezy-slice-master/EzySlice-Examples/Assets/Examples/Scripts/Editor/PlaneUsageExampleEditor.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using EzySlice;
/**
* This is a simple Editor helper script for rapid testing/prototyping!
*/
[CustomEditor(typeof(PlaneUsageExample))]
public class PlaneUsageExampleEditor : Editor {
public GameObject source;
public Material crossMat;
public bool recursiveSlice;
public override void OnInspectorGUI() {
PlaneUsageExample plane = (PlaneUsageExample)target;
source = (GameObject) EditorGUILayout.ObjectField(source, typeof(GameObject), true);
if (source == null) {
EditorGUILayout.LabelField("Add a GameObject to Slice.");
return;
}
if (!source.activeInHierarchy) {
EditorGUILayout.LabelField("Object is Hidden. Cannot Slice.");
return;
}
if (source.GetComponent<MeshFilter>() == null) {
EditorGUILayout.LabelField("GameObject must have a MeshFilter.");
return;
}
crossMat = (Material) EditorGUILayout.ObjectField(crossMat, typeof(Material), true);
recursiveSlice = (bool) EditorGUILayout.Toggle("Recursive Slice", recursiveSlice);
if (GUILayout.Button("Cut Object")) {
// only slice the parent object
if (!recursiveSlice) {
SlicedHull hull = plane.SliceObject(source, crossMat);
if (hull != null) {
hull.CreateLowerHull(source, crossMat);
hull.CreateUpperHull(source, crossMat);
source.SetActive(false);
}
}
else {
// in here we slice both the parent and all child objects
SliceObjectRecursive(plane, source, crossMat);
source.SetActive(false);
}
}
}
/**
* This function will recursively slice the provided object and all it's children.
* Returns a list of SlicedHull objects which represents the cuts for the object
* and all its children (if any)
*/
public GameObject[] SliceObjectRecursive(PlaneUsageExample plane, GameObject obj, Material crossSectionMaterial) {
// finally slice the requested object and return
SlicedHull finalHull = plane.SliceObject(obj, crossSectionMaterial);
if (finalHull != null) {
GameObject lowerParent = finalHull.CreateLowerHull(obj, crossMat);
GameObject upperParent = finalHull.CreateUpperHull(obj, crossMat);
if (obj.transform.childCount > 0) {
foreach (Transform child in obj.transform) {
if (child != null && child.gameObject != null) {
// if the child has chilren, we need to recurse deeper
if (child.childCount > 0) {
GameObject[] children = SliceObjectRecursive(plane, child.gameObject, crossSectionMaterial);
if (children != null) {
// add the lower hull of the child if available
if (children[0] != null && lowerParent != null) {
children[0].transform.SetParent(lowerParent.transform, false);
}
// add the upper hull of this child if available
if (children[1] != null && upperParent != null) {
children[1].transform.SetParent(upperParent.transform, false);
}
}
}
else {
// otherwise, just slice the child object
SlicedHull hull = plane.SliceObject(child.gameObject, crossSectionMaterial);
if (hull != null) {
GameObject childLowerHull = hull.CreateLowerHull(child.gameObject, crossMat);
GameObject childUpperHull = hull.CreateUpperHull(child.gameObject, crossMat);
// add the lower hull of the child if available
if (childLowerHull != null && lowerParent != null) {
childLowerHull.transform.SetParent(lowerParent.transform, false);
}
// add the upper hull of the child if available
if (childUpperHull != null && upperParent != null) {
childUpperHull.transform.SetParent(upperParent.transform, false);
}
}
}
}
}
}
return new GameObject[] {lowerParent, upperParent};
}
return null;
}
}
| 412 | 0.727231 | 1 | 0.727231 | game-dev | MEDIA | 0.550106 | game-dev | 0.855918 | 1 | 0.855918 |
mikecann/Unity-Helpers | 4,146 | README.md | ## NOTE
I havent updated this project in a long time, so I have archived it. Please dont use it unless you are aware that its probably very much out of date :)
---
Unity-Helpers
=============
A set of utils and extensions for making unity development easier.
Unity is a great tool for making games however there are a few annoyances with its API that I have tried to fix with this library.
One such annoyance is the innability to use interfaces in GetComponent(), so I wrote some extension methods to help with that:
```
using UnityHelpers;
var obj = new GameObject();
obj.AddComponent<MyComponent>();
obj.Has<MyComponent>(); // Returns true or false
obj.HasComponentOrInterface<IMyComponent>(); // Can also handle interfaces
obj.Get<MyComponent>(); // Returns the first component
obj.GetComponentOrInterface<IMyComponent>(); // Returns the first component that implements the interface
obj.GetAll<MyComponent>(); // Gets all the components
obj.GetAllComponentsOrInterfaces<IMyComponent>(); // Gets all the components that implement the interface
```
Another utility is for adding children to GameObjects:
```
using UnityHelpers;
var obj = new GameObject();
obj.AddChild("Mike"); // Creates a new GameObject named "Mike" and adds it as a child
var player = obj.AddChild<Player>("Dave"); // Creates a new GameObject named "Dave" and adds the component "Player" returning it
obj.AddChild(typeof(Player), typeof(Friendly), typeof(AI)); // Creates a new GameObject and adds a number of components
```
There are a number of useful utils for loading assets into GameObjects too:
```
using UnityHelpers;
var obj = new GameObject();
obj.Load("Prefabs/Spaceship"); // Loads the Spaceship prefab from the Resources folder and adds it as a child
```
Most of the Utils also can be accessed via the UnityUtils.* class too rather than just extension methods:
```
using UnityHelerps;
var player = UnityUtils.Load<Player>("Prefabs/Spaceship");
```
Enumerate Resources
===================

Enumerate Resources is a handy util for creating type-safe resource references. Traditionally you have to manually create constant strings to load resources at runtime:
```
Resources.Load("Prefabs/Cars/Porsche");
```
This is fragile. If the asset is moved you wont know about the crash until you run the game, this line of code may not be executed often and hence introduces a bug that may only present itself at a later date.
Enumerate Resources scans a resources directory and generates a type-safe alternative:
```
Resources.Load(GameResources.Prefabs.Cars.Porsche);
```
Now if you move the resource and run the enumerator you will get a compile error.
For added sugar there is a method to add the loaded resource as a child of a game object (handy for prefabs):
```
obj.LoadChild(GameResources.Prefabs.Icons.IndicatorArror);
```
ViewStateController
===================

The ViewStateController is a utility for UnityUI that allows you to manage view states. Simply add the states to a list then use the dropdown in the inspector to toggle between which one is active.
At runtime use the methods to change the states:
```
var states = GetComponent<ViewStateController>();
states.SetState("Main Menu"); // Sets the main menu state
states.SetState(someOtherStateGameObject); // Sets another state using the gameobject reference
```
FPSCounter
==========
Attach this component to a gameobject with a Text component and output the current FPS to the screen.
Misc Hacks
==========
The UnityHelpers.MiscHacks class contains a few helpful hacks, such as opening the SpriteEditorWindow directly from code (Unity provides no way of doing this).
Tests
=====
I have included a number of Unit Tests with the project. If you would like to run the tests yourself then just make sure you include the "Unity Test Tools" project from the asset store.
Installation
============
Simply include the source in your project, to use the extension methods dont forget to include the namespace:
```
using UnityHelpers;
```
| 412 | 0.773234 | 1 | 0.773234 | game-dev | MEDIA | 0.99377 | game-dev | 0.622476 | 1 | 0.622476 |
kishikawakatsumi/Mozc-for-iOS | 5,987 | src/unix/ibus/engine_registrar.cc | // Copyright 2010-2014, Google Inc.
// 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.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "unix/ibus/engine_registrar.h"
#include "base/logging.h"
#include "unix/ibus/engine_interface.h"
namespace {
mozc::ibus::EngineInterface *g_engine = NULL;
}
namespace mozc {
namespace ibus {
bool EngineRegistrar::Register(EngineInterface *engine,
IBusEngineClass *engine_class) {
DCHECK(engine) << "engine is NULL";
DCHECK(!g_engine) << "engine is already registered";
g_engine = engine;
engine_class->cursor_down = CursorDown;
engine_class->candidate_clicked = CandidateClicked;
engine_class->cursor_down = CursorDown;
engine_class->cursor_up = CursorUp;
engine_class->disable = Disable;
engine_class->enable = Enable;
engine_class->focus_in = FocusIn;
engine_class->focus_out = FocusOut;
engine_class->page_down = PageDown;
engine_class->page_up = PageUp;
engine_class->process_key_event = ProcessKeyEvent;
engine_class->property_activate = PropertyActivate;
engine_class->property_hide = PropertyHide;
engine_class->property_show = PropertyShow;
engine_class->reset = Reset;
engine_class->set_capabilities = SetCapabilities;
engine_class->set_cursor_location = SetCursorLocation;
#if defined(MOZC_ENABLE_IBUS_INPUT_PURPOSE)
engine_class->set_content_type = SetContentType;
#endif // MOZC_ENABLE_IBUS_INPUT_PURPOSE
return true;
}
EngineInterface *EngineRegistrar::Unregister(IBusEngineClass *engine_class) {
DCHECK(g_engine) << "engine is not registered";
engine_class->cursor_down = NULL;
engine_class->candidate_clicked = NULL;
engine_class->cursor_down = NULL;
engine_class->cursor_up = NULL;
engine_class->disable = NULL;
engine_class->enable = NULL;
engine_class->focus_in = NULL;
engine_class->focus_out = NULL;
engine_class->page_down = NULL;
engine_class->page_up = NULL;
engine_class->process_key_event = NULL;
engine_class->property_activate = NULL;
engine_class->property_hide = NULL;
engine_class->property_show = NULL;
engine_class->reset = NULL;
engine_class->set_capabilities = NULL;
engine_class->set_cursor_location = NULL;
#if defined(MOZC_ENABLE_IBUS_INPUT_PURPOSE)
engine_class->set_content_type = NULL;
#endif // MOZC_ENABLE_IBUS_INPUT_PURPOSE
mozc::ibus::EngineInterface *previous = g_engine;
g_engine = NULL;
return previous;
}
void EngineRegistrar::CandidateClicked(
IBusEngine *engine,
guint index,
guint button,
guint state) {
g_engine->CandidateClicked(engine, index, button, state);
}
void EngineRegistrar::CursorDown(IBusEngine *engine) {
g_engine->CursorDown(engine);
}
void EngineRegistrar::CursorUp(IBusEngine *engine) {
g_engine->CursorUp(engine);
}
void EngineRegistrar::Disable(IBusEngine *engine) {
g_engine->Disable(engine);
}
void EngineRegistrar::Enable(IBusEngine *engine) {
g_engine->Enable(engine);
}
void EngineRegistrar::FocusIn(IBusEngine *engine) {
g_engine->FocusIn(engine);
}
void EngineRegistrar::FocusOut(IBusEngine *engine) {
g_engine->FocusOut(engine);
}
void EngineRegistrar::PageDown(IBusEngine *engine) {
g_engine->PageDown(engine);
}
void EngineRegistrar::PageUp(IBusEngine *engine) {
g_engine->PageUp(engine);
}
gboolean EngineRegistrar::ProcessKeyEvent(
IBusEngine *engine,
guint keyval,
guint keycode,
guint state) {
return g_engine->ProcessKeyEvent(engine, keyval, keycode, state);
}
void EngineRegistrar::PropertyActivate(
IBusEngine *engine,
const gchar *property_name,
guint property_state) {
g_engine->PropertyActivate(engine, property_name, property_state);
}
void EngineRegistrar::PropertyHide(
IBusEngine *engine,
const gchar *property_name) {
g_engine->PropertyHide(engine, property_name);
}
void EngineRegistrar::PropertyShow(
IBusEngine *engine,
const gchar *property_name) {
g_engine->PropertyShow(engine, property_name);
}
void EngineRegistrar::Reset(IBusEngine *engine) {
g_engine->Reset(engine);
}
void EngineRegistrar::SetCapabilities(
IBusEngine *engine,
guint capabilities) {
g_engine->SetCapabilities(engine, capabilities);
}
void EngineRegistrar::SetCursorLocation(
IBusEngine *engine,
gint x,
gint y,
gint w,
gint h) {
g_engine->SetCursorLocation(engine, x, y, w, h);
}
void EngineRegistrar::SetContentType(
IBusEngine *engine,
guint purpose,
guint hints) {
g_engine->SetContentType(engine, purpose, hints);
}
} // namespace ibus
} // namespace mozc
| 412 | 0.583594 | 1 | 0.583594 | game-dev | MEDIA | 0.711712 | game-dev | 0.751972 | 1 | 0.751972 |
ark-bitcoin/bark | 2,693 | bark/src/movement.rs |
use ark::Vtxo;
use bitcoin::Amount;
use crate::vtxo_state::VtxoState;
#[derive(Debug, Deserialize, Serialize)]
pub enum MovementKind {
Board,
Round,
Offboard,
Exit,
ArkoorSend,
ArkoorReceive,
LightningSend,
LightningSendRevocation,
LightningReceive,
}
impl MovementKind {
pub fn from_str(s: &str) -> anyhow::Result<Self> {
match s {
"onboard" => Ok(MovementKind::Board),
"round" => Ok(MovementKind::Round),
"offboard" => Ok(MovementKind::Offboard),
"arkoor-send" => Ok(MovementKind::ArkoorSend),
"arkoor-receive" => Ok(MovementKind::ArkoorReceive),
"lightning-send" => Ok(MovementKind::LightningSend),
"lightning-send-revocation" => Ok(MovementKind::LightningSendRevocation),
"lightning-receive" => Ok(MovementKind::LightningReceive),
"exit" => Ok(MovementKind::Exit),
_ => bail!("Invalid movement kind: {}", s),
}
}
pub fn as_str(&self) -> &str {
match self {
MovementKind::Board => "onboard",
MovementKind::Round => "round",
MovementKind::Offboard => "offboard",
MovementKind::ArkoorSend => "arkoor-send",
MovementKind::ArkoorReceive => "arkoor-receive",
MovementKind::LightningSend => "lightning-send",
MovementKind::LightningSendRevocation => "lightning-send-revocation",
MovementKind::LightningReceive => "lightning-receive",
MovementKind::Exit => "exit",
}
}
}
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct MovementRecipient {
/// Can either be a publickey, spk or a bolt11 invoice
pub recipient: String,
/// Amount sent to the recipient
#[serde(rename = "amount_sat", with = "bitcoin::amount::serde::as_sat")]
pub amount: Amount
}
/// A [`Movement`] represents any offchain balance change,
/// either by receiving, sending or refreshing VTXO
#[derive(Debug)]
pub struct Movement {
pub id: u32,
/// Movement kind
pub kind: MovementKind,
/// Fees paid for the movement
pub fees: Amount,
/// wallet's VTXOs spent in this movement
pub spends: Vec<Vtxo>,
/// Received VTXOs from this movement
pub receives: Vec<Vtxo>,
/// External recipients of the movement
pub recipients: Vec<MovementRecipient>,
/// Movement date
pub created_at: String,
}
/// Arguments used to create a movement
pub struct MovementArgs<'a> {
/// Movement kind
pub kind: MovementKind,
/// VTXOs that are spent in the movement.
///
/// They will be marked as spent and linked to the created movement
pub spends: &'a [&'a Vtxo],
/// New VTXOs to store and link to the created movement
pub receives: &'a [(&'a Vtxo, VtxoState)],
/// External destinations of the movement
pub recipients: &'a [(&'a str, Amount)],
/// Optional offchain fees paid for the movement
pub fees: Option<Amount>
}
| 412 | 0.875915 | 1 | 0.875915 | game-dev | MEDIA | 0.503088 | game-dev | 0.821937 | 1 | 0.821937 |
shiversoftdev/t8-src | 2,123 | script_3b584c12e643589.gsc | // Decompiled by Serious. Credits to Scoba for his original tool, Cerberus, which I heavily upgraded to support remaining features, other games, and other platforms.
#using scripts\core_common\system_shared.csc;
#using scripts\mp_common\item_world.csc;
#using scripts\core_common\struct.csc;
#namespace namespace_d0937679;
/*
Name: __init__system__
Namespace: namespace_d0937679
Checksum: 0x5C02DD36
Offset: 0xC8
Size: 0x3C
Parameters: 0
Flags: AutoExec
*/
function autoexec __init__system__()
{
system::register(#"hash_1f56d362760c2c6b", &__init__, undefined, undefined);
}
/*
Name: __init__
Namespace: namespace_d0937679
Checksum: 0xCA3DB4B1
Offset: 0x110
Size: 0x74
Parameters: 0
Flags: Linked
*/
function __init__()
{
level.var_fdbdcdfd = (isdefined(getgametypesetting(#"hash_6fbf57e2af153e5f")) ? getgametypesetting(#"hash_6fbf57e2af153e5f") : 0);
level thread function_61a426a5();
}
/*
Name: function_61a426a5
Namespace: namespace_d0937679
Checksum: 0xA2DF7F99
Offset: 0x190
Size: 0x202
Parameters: 0
Flags: Linked
*/
function function_61a426a5()
{
debug_pos = getdvarint(#"hash_79ed3a19e0cdd3c5", -1);
if(debug_pos < 0)
{
debug_pos = undefined;
}
zombie_apoc_homunculus = getdynent("zombie_apoc_homunculus");
if(!isdefined(zombie_apoc_homunculus) && (!(isdefined(level.var_fdbdcdfd) && level.var_fdbdcdfd)))
{
return;
}
item_world::function_4de3ca98();
if(isdefined(zombie_apoc_homunculus))
{
points = struct::get_array("zombie_apoc_homunculus_point", "targetname");
if(isdefined(points))
{
for(index = 0; index < points.size; index++)
{
randindex = function_d59c2d03(points.size);
var_521b73a = points[index];
points[index] = points[randindex];
points[randindex] = var_521b73a;
}
randindex = function_d59c2d03(points.size);
if(isdefined(debug_pos))
{
zombie_apoc_homunculus.origin = points[debug_pos].origin;
zombie_apoc_homunculus.angles = points[debug_pos].angles;
}
else
{
zombie_apoc_homunculus.origin = points[randindex].origin;
zombie_apoc_homunculus.angles = points[randindex].angles;
}
}
}
}
| 412 | 0.760564 | 1 | 0.760564 | game-dev | MEDIA | 0.878569 | game-dev | 0.689326 | 1 | 0.689326 |
jmilktea/jtea | 1,899 | sample/bytebuddy/src/main/java/agent/AgentApplication.java | package agent;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.SuperCall;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.utility.JavaModule;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
/**
* @author huangyb1
* @date 2022/6/27
*/
public class AgentApplication {
private static final String timeWatch = "com.jmilktea.sample.demo.bytebuddy.TimeWatch";
public static void premain(String agentArgs, Instrumentation inst) {
System.out.println("agent premain run");
AgentBuilder.Transformer transformer = new AgentBuilder.Transformer() {
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, JavaModule module) {
return builder
.method(ElementMatchers.<MethodDescription>isAnnotatedWith(ElementMatchers.named(timeWatch)))
.intercept(MethodDelegation.to(TimeWatchInterceptor.class));
}
};
new AgentBuilder.Default().type(ElementMatchers.<TypeDescription>nameStartsWith("com.jmilktea")).transform(transformer).installOn(inst);
}
public static class TimeWatchInterceptor {
@RuntimeType
public static Object intercept(@Origin Method method,
@SuperCall Callable<?> callable) throws Exception {
long start = System.currentTimeMillis();
try {
return callable.call();
} finally {
System.out.println(method.getName() + " use:" + (System.currentTimeMillis() - start));
}
}
}
}
| 412 | 0.659216 | 1 | 0.659216 | game-dev | MEDIA | 0.343162 | game-dev | 0.817204 | 1 | 0.817204 |
cake-tech/cake_wallet | 4,330 | lib/src/widgets/seed_language_picker.dart | import 'package:flutter/material.dart';
import 'package:cake_wallet/src/widgets/picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/entities/seed_type.dart';
class SeedLanguagePickerOption {
SeedLanguagePickerOption(this.name, this.nameLocalized, this.image, this.supportedSeedTypes);
final String name;
final String nameLocalized;
final Image image;
final List<MoneroSeedType> supportedSeedTypes;
}
final List<SeedLanguagePickerOption> seedLanguages = [
SeedLanguagePickerOption(
'English',
S.current.seed_language_english,
Image.asset('assets/images/flags/usa.png'),
[MoneroSeedType.legacy, MoneroSeedType.polyseed, MoneroSeedType.bip39],
),
SeedLanguagePickerOption('Chinese (Simplified)', S.current.seed_language_chinese,
Image.asset('assets/images/flags/chn.png'), [MoneroSeedType.legacy, MoneroSeedType.polyseed]),
SeedLanguagePickerOption('Chinese (Traditional)', S.current.seed_language_chinese_traditional,
Image.asset('assets/images/flags/chn.png'), [MoneroSeedType.polyseed]),
SeedLanguagePickerOption('Dutch', S.current.seed_language_dutch,
Image.asset('assets/images/flags/nld.png'), [MoneroSeedType.legacy]),
SeedLanguagePickerOption('German', S.current.seed_language_german,
Image.asset('assets/images/flags/deu.png'), [MoneroSeedType.legacy]),
SeedLanguagePickerOption('Japanese', S.current.seed_language_japanese,
Image.asset('assets/images/flags/jpn.png'), [MoneroSeedType.legacy, MoneroSeedType.polyseed]),
SeedLanguagePickerOption('Korean', S.current.seed_language_korean,
Image.asset('assets/images/flags/kor.png'), [MoneroSeedType.polyseed]),
SeedLanguagePickerOption('Portuguese', S.current.seed_language_portuguese,
Image.asset('assets/images/flags/prt.png'), [MoneroSeedType.legacy, MoneroSeedType.polyseed]),
SeedLanguagePickerOption('Russian', S.current.seed_language_russian,
Image.asset('assets/images/flags/rus.png'), [MoneroSeedType.legacy]),
SeedLanguagePickerOption('Czech', S.current.seed_language_czech,
Image.asset('assets/images/flags/czk.png'), [MoneroSeedType.polyseed]),
SeedLanguagePickerOption('Spanish', S.current.seed_language_spanish,
Image.asset('assets/images/flags/esp.png'), [MoneroSeedType.legacy, MoneroSeedType.polyseed]),
SeedLanguagePickerOption('French', S.current.seed_language_french,
Image.asset('assets/images/flags/fra.png'), [MoneroSeedType.legacy, MoneroSeedType.polyseed]),
SeedLanguagePickerOption('Italian', S.current.seed_language_italian,
Image.asset('assets/images/flags/ita.png'), [MoneroSeedType.legacy, MoneroSeedType.polyseed]),
];
const defaultSeedLanguage = 'English';
enum Places { topLeft, topRight, bottomLeft, bottomRight, inside }
class SeedLanguagePicker extends StatefulWidget {
SeedLanguagePicker({
Key? key,
this.selected = defaultSeedLanguage,
this.seedType = MoneroSeedType.defaultSeedType,
required this.onItemSelected,
}) : super(key: key);
final MoneroSeedType seedType;
final String selected;
final Function(String) onItemSelected;
@override
SeedLanguagePickerState createState() => SeedLanguagePickerState(
selected: selected, onItemSelected: onItemSelected, seedType: seedType);
}
class SeedLanguagePickerState extends State<SeedLanguagePicker> {
SeedLanguagePickerState(
{required this.selected, required this.onItemSelected, required this.seedType});
final MoneroSeedType seedType;
final String selected;
final Function(String) onItemSelected;
@override
Widget build(BuildContext context) {
final availableSeedLanguages = seedLanguages
.where((SeedLanguagePickerOption e) => e.supportedSeedTypes.contains(seedType));
return Picker(
selectedAtIndex: availableSeedLanguages.map((e) => e.name).toList().indexOf(selected),
items: availableSeedLanguages.map((e) => e.name).toList(),
images: availableSeedLanguages.map((e) => e.image).toList(),
isGridView: true,
title: S.of(context).seed_choose,
hintText: S.of(context).seed_choose,
matchingCriteria: (String language, String searchText) {
return language.toLowerCase().contains(searchText);
},
onItemSelected: onItemSelected,
);
}
}
| 412 | 0.515507 | 1 | 0.515507 | game-dev | MEDIA | 0.728501 | game-dev | 0.555696 | 1 | 0.555696 |
Toxocious/Moonlight | 5,455 | Server/src/main/java/net/swordie/ms/world/field/obtacleatom/ObtacleAtomInfo.java | package net.swordie.ms.world.field.obtacleatom;
import net.swordie.ms.connection.OutPacket;
import net.swordie.ms.util.Position;
/**
* Created on 5/30/2018.
*/
public class ObtacleAtomInfo {
private int atomType;
private int key;
private Position startPos;
private Position endPos;
private int hitBoxRange;
private int trueDamR;
private int mobDamR;
private int createDelay;
private int height;
private int vPerSec;
private int maxP;
private int length;
private int angle;
private ObtacleDiagonalInfo obtacleDiagonalInfo;
public ObtacleAtomInfo() {
}
public ObtacleAtomInfo(int atomType, int key, Position startPos, Position endPos, int hitBoxRange, int trueDamR,
int mobDamR, int createDelay, int height, int vPerSec, int maxP, int length, int angle) {
this.atomType = atomType;
this.key = key;
this.startPos = startPos;
this.endPos = endPos;
this.hitBoxRange = hitBoxRange;
this.trueDamR = trueDamR;
this.mobDamR = mobDamR;
this.createDelay = createDelay;
this.height = height;
this.vPerSec = vPerSec;
this.maxP = maxP;
this.length = length;
this.angle = angle;
}
public void encode(OutPacket outPacket) {
outPacket.encodeInt(getAtomType());
outPacket.encodeInt(getKey());
outPacket.encodeInt(getStartPos().getX());
outPacket.encodeInt(getStartPos().getY());
outPacket.encodeInt(getEndPos().getX());
outPacket.encodeInt(getEndPos().getY());
outPacket.encodeInt(getHitBoxRange());
outPacket.encodeInt(getTrueDamR());
outPacket.encodeInt(getMobDamR());
outPacket.encodeInt(getCreateDelay());
outPacket.encodeInt(getHeight());
outPacket.encodeInt(getvPerSec());
outPacket.encodeInt(getMaxP());
outPacket.encodeInt(getLength());
outPacket.encodeInt(getAngle());
}
public int getAtomType() {
return atomType;
}
public void setAtomType(int atomType) {
this.atomType = atomType;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public Position getStartPos() {
return startPos;
}
public void setStartPos(Position startPos) {
this.startPos = startPos;
}
public Position getEndPos() {
return endPos;
}
public void setEndPos(Position endPos) {
this.endPos = endPos;
}
public int getHitBoxRange() {
return hitBoxRange;
}
public void setHitBoxRange(int hitBoxRange) {
this.hitBoxRange = hitBoxRange;
}
public int getTrueDamR() {
return trueDamR;
}
public void setTrueDamR(int trueDamR) {
this.trueDamR = trueDamR;
}
public int getMobDamR() {
return mobDamR;
}
public void setMobDamR(int mobDamR) {
this.mobDamR = mobDamR;
}
public int getCreateDelay() {
return createDelay;
}
public void setCreateDelay(int createDelay) {
this.createDelay = createDelay;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getvPerSec() {
return vPerSec;
}
public void setvPerSec(int vPerSec) {
this.vPerSec = vPerSec;
}
public int getMaxP() {
return maxP;
}
public void setMaxP(int maxP) {
this.maxP = maxP;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getAngle() {
return angle;
}
public void setAngle(int angle) {
this.angle = angle;
}
public ObtacleDiagonalInfo getObtacleDiagonalInfo() {
return obtacleDiagonalInfo;
}
public void setObtacleDiagonalInfo(ObtacleDiagonalInfo obtacleDiagonalInfo) {
this.obtacleDiagonalInfo = obtacleDiagonalInfo;
}
/**
* Calculates the angle at which the ObstacleAtom must go to reach the wanted Ending Position.
*
* @param startPos Starting Position of the ObstacleAtom
* @param endPos Ending Position of the ObstacleAtom
* @return The angle the ObstacleAtom must travel to hit the wanted End Position.
*/
public static double getAngleByPositions(Position startPos, Position endPos) {
double width = startPos.getX() - endPos.getX();
width = width < 0 ? -width : width;
double hypotenuse = getLengthByPositions(startPos, endPos);
return Math.asin(width/hypotenuse);
}
/**
* Calculates the Length the ObstacleAtom must travel to reach the wanted Ending Position.
*
* @param startPos Starting Position of the ObstacleAtom
* @param endPos Ending Position of the ObstacleAtom
* @return The Length the obstacleAtom must travel to hit the wanted End Position.
*/
public static double getLengthByPositions(Position startPos, Position endPos) {
int height = startPos.getY() - endPos.getY();
height = height < 0 ? -height : height;
int width = startPos.getX() - endPos.getX();
width = width < 0 ? -width : width;
return Math.round(Math.sqrt(Math.round(Math.pow(height, 2)) + Math.round(Math.pow(width, 2))));
}
}
| 412 | 0.771141 | 1 | 0.771141 | game-dev | MEDIA | 0.300966 | game-dev | 0.824818 | 1 | 0.824818 |
cocos2d/cocos2d-html5 | 8,653 | extensions/cocostudio/armature/display/CCDisplayFactory.js | /****************************************************************************
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/**
* @ignore
*/
ccs.displayFactory = {
addDisplay: function (bone, decoDisplay, displayData) {
switch (displayData.displayType) {
case ccs.DISPLAY_TYPE_SPRITE:
this.addSpriteDisplay(bone, decoDisplay, displayData);
break;
case ccs.DISPLAY_TYPE_PARTICLE:
this.addParticleDisplay(bone, decoDisplay, displayData);
break;
case ccs.DISPLAY_TYPE_ARMATURE:
this.addArmatureDisplay(bone, decoDisplay, displayData);
break;
default:
break;
}
},
createDisplay: function (bone, decoDisplay) {
switch (decoDisplay.getDisplayData().displayType) {
case ccs.DISPLAY_TYPE_SPRITE:
this.createSpriteDisplay(bone, decoDisplay);
break;
case ccs.DISPLAY_TYPE_PARTICLE:
this.createParticleDisplay(bone, decoDisplay);
break;
case ccs.DISPLAY_TYPE_ARMATURE:
this.createArmatureDisplay(bone, decoDisplay);
break;
default:
break;
}
},
_helpTransform: {a:1, b:0, c:0, d:1, tx:0, ty:0},
updateDisplay: function (bone, dt, dirty) {
var display = bone.getDisplayRenderNode();
if(!display)
return;
switch (bone.getDisplayRenderNodeType()) {
case ccs.DISPLAY_TYPE_SPRITE:
if (dirty) {
display._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
display.updateArmatureTransform();
}
break;
case ccs.DISPLAY_TYPE_PARTICLE:
this.updateParticleDisplay(bone, display, dt);
break;
case ccs.DISPLAY_TYPE_ARMATURE:
this.updateArmatureDisplay(bone, display, dt);
break;
default:
var transform = bone.getNodeToArmatureTransform();
display.setAdditionalTransform(transform);
break;
}
if (ccs.ENABLE_PHYSICS_CHIPMUNK_DETECT || ccs.ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX) {
if (dirty) {
var decoDisplay = bone.getDisplayManager().getCurrentDecorativeDisplay();
var detector = decoDisplay.getColliderDetector();
if (detector) {
var node = decoDisplay.getDisplay();
var displayTransform = node.getNodeToParentTransform();
var helpTransform = this._helpTransform;
helpTransform.a = displayTransform.a;
helpTransform.b = displayTransform.b;
helpTransform.c = displayTransform.c;
helpTransform.d = displayTransform.d;
helpTransform.tx = displayTransform.tx;
helpTransform.ty = displayTransform.ty;
var anchorPoint = cc.pointApplyAffineTransform(node.getAnchorPointInPoints(), helpTransform);
helpTransform.tx = anchorPoint.x;
helpTransform.ty = anchorPoint.y;
var t = cc.affineTransformConcat(helpTransform, bone.getArmature().getNodeToParentTransform());
detector.updateTransform(t);
}
}
}
},
addSpriteDisplay: function (bone, decoDisplay, displayData) {
var sdp = new ccs.SpriteDisplayData();
sdp.copy(displayData);
decoDisplay.setDisplayData(sdp);
this.createSpriteDisplay(bone, decoDisplay);
},
createSpriteDisplay: function (bone, decoDisplay) {
var skin = null;
var displayData = decoDisplay.getDisplayData();
//! remove .xxx
var textureName = displayData.displayName;
var startPos = textureName.lastIndexOf(".");
if (startPos !== -1)
textureName = textureName.substring(0, startPos);
//! create display
if (textureName === "")
skin = new ccs.Skin();
else
skin = new ccs.Skin("#" + textureName + ".png");
decoDisplay.setDisplay(skin);
skin.setBone(bone);
this.initSpriteDisplay(bone, decoDisplay, displayData.displayName, skin);
var armature = bone.getArmature();
if (armature) {
if (armature.getArmatureData().dataVersion >= ccs.CONST_VERSION_COMBINED)
skin.setSkinData(displayData.skinData);
else
skin.setSkinData(bone.boneData);
}
},
initSpriteDisplay: function (bone, decoDisplay, displayName, skin) {
//! remove .xxx
var textureName = displayName;
var startPos = textureName.lastIndexOf(".");
if (startPos !== -1)
textureName = textureName.substring(0, startPos);
var textureData = ccs.armatureDataManager.getTextureData(textureName);
if (textureData) {
//! Init display anchorPoint, every Texture have a anchor point
skin.setAnchorPoint(cc.p(textureData.pivotX, textureData.pivotY));
}
if (ccs.ENABLE_PHYSICS_CHIPMUNK_DETECT || ccs.ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX) {
if (textureData && textureData.contourDataList.length > 0) {
//! create ContourSprite
var colliderDetector = new ccs.ColliderDetector(bone);
colliderDetector.addContourDataList(textureData.contourDataList);
decoDisplay.setColliderDetector(colliderDetector);
}
}
},
addArmatureDisplay: function (bone, decoDisplay, displayData) {
var adp = new ccs.ArmatureDisplayData();
adp.copy(displayData);
decoDisplay.setDisplayData(adp);
this.createArmatureDisplay(bone, decoDisplay);
},
createArmatureDisplay: function (bone, decoDisplay) {
var displayData = decoDisplay.getDisplayData();
var armature = new ccs.Armature(displayData.displayName, bone);
decoDisplay.setDisplay(armature);
},
updateArmatureDisplay: function (bone, armature, dt) {
if (armature) {
armature.sortAllChildren();
armature.update(dt);
}
},
addParticleDisplay: function (bone, decoDisplay, displayData) {
var adp = new ccs.ParticleDisplayData();
adp.copy(displayData);
decoDisplay.setDisplayData(adp);
this.createParticleDisplay(bone, decoDisplay);
},
createParticleDisplay: function (bone, decoDisplay) {
var displayData = decoDisplay.getDisplayData();
var system = new cc.ParticleSystem(displayData.displayName);
system.removeFromParent();
system.cleanup();
var armature = bone.getArmature();
if (armature)
system.setParent(bone.getArmature());
decoDisplay.setDisplay(system);
},
updateParticleDisplay: function (bone, particleSystem, dt) {
var node = new ccs.BaseData();
ccs.TransformHelp.matrixToNode(bone.nodeToArmatureTransform(), node);
particleSystem.setPosition(node.x, node.y);
particleSystem.setScaleX(node.scaleX);
particleSystem.setScaleY(node.scaleY);
particleSystem.update(dt);
}
}; | 412 | 0.850359 | 1 | 0.850359 | game-dev | MEDIA | 0.66667 | game-dev,graphics-rendering | 0.676783 | 1 | 0.676783 |
exult/exult | 109,748 | usecode/intrinsics.cc | /*
* Copyright (C) 2000-2025 The Exult Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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.
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "Audio.h"
#include "Book_gump.h"
#include "Face_stats.h"
#include "Gump.h"
#include "Gump_manager.h"
#include "Scroll_gump.h"
#include "ShortcutBar_gump.h"
#include "Sign_gump.h"
#include "actions.h"
#include "animate.h"
#include "barge.h"
#include "cheat.h"
#include "chunks.h"
#include "combat.h"
#include "conversation.h"
#include "effects.h"
#include "egg.h"
#include "exult.h"
#include "frflags.h"
#include "game.h"
#include "gameclk.h"
#include "gamemap.h"
#include "gamewin.h"
#include "gump_utils.h"
#include "ignore_unused_variable_warning.h"
#include "items.h"
#include "keyring.h"
#include "monsters.h"
#include "monstinf.h"
#include "mouse.h"
#include "palette.h"
#include "party.h"
#include "playscene.h"
#include "ready.h"
#include "rect.h"
#include "schedule.h"
#include "spellbook.h"
#include "stackframe.h"
#include "touchui.h"
#include "ucfunction.h"
#include "ucinternal.h"
#include "ucsched.h"
#include "ucscriptop.h"
#include "ucsymtbl.h"
#include "useval.h"
#include "virstone.h"
#include <array>
#include <cmath>
#include <limits>
#include <map>
#include <memory>
#include <string_view>
using std::cerr;
using std::cout;
using std::endl;
using std::rand;
using std::strchr;
extern Usecode_value no_ret;
static Game_object* sailor = nullptr; // The current barge captain. Maybe
// this needs to be saved/restored.
#define USECODE_INTRINSIC(NAME) \
Usecode_value Usecode_internal::UI_##NAME( \
int num_parms, Usecode_value parms[12])
USECODE_INTRINSIC(NOP) {
ignore_unused_variable_warning(num_parms, parms);
return no_ret;
}
USECODE_INTRINSIC(UNKNOWN) {
ignore_unused_variable_warning(num_parms, parms);
// Unhandled(num_parms, parms);
return no_ret;
}
USECODE_INTRINSIC(get_random) {
ignore_unused_variable_warning(num_parms);
const int range = parms[0].get_int_value();
if (range == 0) {
Usecode_value u(0);
return u;
}
Usecode_value u(1 + (rand() % range));
return u;
}
USECODE_INTRINSIC(execute_usecode_array) {
ignore_unused_variable_warning(num_parms);
COUT("Executing intrinsic 1");
// Start on next tick.
create_script(parms[0], parms[1], gwin->get_std_delay());
Usecode_value u(1);
return u;
}
USECODE_INTRINSIC(delayed_execute_usecode_array) {
ignore_unused_variable_warning(num_parms);
// Delay = .20 sec.?
// +++++Special problem with inf. loop:
if (Game::get_game_type() == BLACK_GATE && frame->eventid == internal_exec
&& parms[1].get_array_size() == 3
&& parms[1].get_elem(2).get_int_value() == 0x6f7) {
return no_ret;
}
const int delay = parms[2].get_int_value();
create_script(parms[0], parms[1], delay * gwin->get_std_delay());
COUT("Executing intrinsic 2");
Usecode_value u(1);
return u;
}
USECODE_INTRINSIC(show_npc_face) {
ignore_unused_variable_warning(num_parms);
show_npc_face(parms[0], parms[1]);
return no_ret;
}
USECODE_INTRINSIC(remove_npc_face) {
ignore_unused_variable_warning(num_parms);
remove_npc_face(parms[0]);
return no_ret;
}
USECODE_INTRINSIC(add_answer) {
ignore_unused_variable_warning(num_parms);
conv->add_answer(parms[0]);
// user_choice = 0;
return no_ret;
}
USECODE_INTRINSIC(remove_answer) {
ignore_unused_variable_warning(num_parms);
conv->remove_answer(parms[0]);
// Commented out 'user_choice = 0' 8/3/00 for Tseramed conversation.
// user_choice = 0;
return no_ret;
}
USECODE_INTRINSIC(push_answers) {
ignore_unused_variable_warning(num_parms, parms);
conv->push_answers();
return no_ret;
}
USECODE_INTRINSIC(pop_answers) {
ignore_unused_variable_warning(num_parms, parms);
if (!conv->stack_empty()) {
conv->pop_answers();
delete[] user_choice;
user_choice = nullptr; // Added 7/24/2000.
}
return no_ret;
}
USECODE_INTRINSIC(clear_answers) {
ignore_unused_variable_warning(num_parms, parms);
conv->clear_answers();
return no_ret;
}
USECODE_INTRINSIC(select_from_menu) {
ignore_unused_variable_warning(num_parms, parms);
delete[] user_choice;
user_choice = nullptr;
Usecode_value u(get_user_choice());
delete[] user_choice;
user_choice = nullptr;
return u;
}
USECODE_INTRINSIC(select_from_menu2) {
ignore_unused_variable_warning(num_parms, parms);
// Return index (1-n) of choice.
delete[] user_choice;
user_choice = nullptr;
Usecode_value val(get_user_choice_num() + 1);
delete[] user_choice;
user_choice = nullptr;
return val;
}
USECODE_INTRINSIC(input_numeric_value) {
ignore_unused_variable_warning(num_parms);
// Ask for # (min, max, step, default). Be sure to show conversation.
Usecode_value ret(gumpman->prompt_for_number(
parms[0].get_int_value(), parms[1].get_int_value(),
parms[2].get_int_value(), parms[3].get_int_value(), conv));
conv->clear_text_pending(); // Answered a question.
return ret;
}
USECODE_INTRINSIC(set_item_shape) {
ignore_unused_variable_warning(num_parms);
// Set item shape.
set_item_shape(parms[0], parms[1]);
return no_ret;
}
USECODE_INTRINSIC(find_nearest) {
ignore_unused_variable_warning(num_parms);
// Think it rets. nearest obj. near parm0.
Usecode_value u(find_nearest(parms[0], parms[1], parms[2]));
return u;
}
USECODE_INTRINSIC(die_roll) {
ignore_unused_variable_warning(num_parms);
// Rand. # within range.
int low = parms[0].get_int_value();
int high = parms[1].get_int_value();
if (low > high) {
const int tmp = low;
low = high;
high = tmp;
}
const int val = (rand() % (high - low + 1)) + low;
Usecode_value u(val);
return u;
}
USECODE_INTRINSIC(get_item_shape) {
ignore_unused_variable_warning(num_parms);
Game_object* item = get_item(parms[0]);
// Want the actual, not polymorph'd.
Actor* act = as_actor(item);
return Usecode_value(
item == nullptr
? 0
: (act ? act->get_shape_real() : item->get_shapenum()));
}
USECODE_INTRINSIC(get_item_frame) {
ignore_unused_variable_warning(num_parms);
// Returns frame without rotated bit.
Game_object* item = get_item(parms[0]);
// Don't count rotated frames.
return Usecode_value(item == nullptr ? 0 : item->get_framenum() & 31);
}
USECODE_INTRINSIC(set_item_frame) {
ignore_unused_variable_warning(num_parms);
// Set frame, but don't change rotated bit.
//++++++++Seems like in BG, this should be the same as
// set_item_frame_rot()??
set_item_frame(get_item(parms[0]), parms[1].get_int_value());
return no_ret;
}
USECODE_INTRINSIC(get_item_quality) {
ignore_unused_variable_warning(num_parms);
Game_object* obj = get_item(parms[0]);
if (!obj) {
return Usecode_value(0);
}
const Shape_info& info = obj->get_info();
return Usecode_value(info.has_quality() ? obj->get_quality() : 0);
}
USECODE_INTRINSIC(set_item_quality) {
ignore_unused_variable_warning(num_parms);
// Guessing it's
// set_quality(item, value).
const int qual = parms[1].get_int_value();
if (qual == c_any_qual) { // Leave alone (happens in SI)?
return Usecode_value(1);
}
Game_object* obj = get_item(parms[0]);
if (obj) {
const Shape_info& info = obj->get_info();
if (info.has_quality()) {
obj->set_quality(static_cast<unsigned int>(qual));
return Usecode_value(1);
}
}
return Usecode_value(0);
}
USECODE_INTRINSIC(get_item_quantity) {
ignore_unused_variable_warning(num_parms);
// Get quantity of an item.
// Get_quantity(item, mystery).
Usecode_value ret(0);
Game_object* obj = get_item(parms[0]);
if (obj) {
ret = Usecode_value(obj->get_quantity());
}
return ret;
}
USECODE_INTRINSIC(set_item_quantity) {
ignore_unused_variable_warning(num_parms);
// Set_quantity (item, newcount). Rets 1 iff item.has_quantity().
Usecode_value ret(0);
Game_object* obj = get_item(parms[0]);
const int newquant = parms[1].get_int_value();
if (obj && obj->get_info().has_quantity()) {
ret = Usecode_value(1);
// If not in world, don't delete!
if (newquant == 0 && obj->get_cx() == 255) {
return ret;
}
const int oldquant = obj->get_quantity();
const int delta = newquant - oldquant;
// Note: This can delete the obj.
obj->modify_quantity(delta);
}
return ret;
}
USECODE_INTRINSIC(get_object_position) {
ignore_unused_variable_warning(num_parms);
// Takes itemref. ?Think it rets.
// hotspot coords: (x, y, z).
Game_object* obj = get_item(parms[0]);
Tile_coord c(0, 0, 0);
if (obj) { // (Watch for animated objs' wiggles.)
c = obj->get_outermost()->get_original_tile_coord();
}
Usecode_value vx(c.tx);
Usecode_value vy(c.ty);
Usecode_value vz(c.tz);
Usecode_value arr(3, &vx);
arr.put_elem(1, vy);
arr.put_elem(2, vz);
return arr;
}
USECODE_INTRINSIC(get_distance) {
ignore_unused_variable_warning(num_parms);
// Distance from parm[0] -> parm[1]. Guessing how it's computed.
Game_object* obj0 = get_item(parms[0]);
Game_object* obj1 = get_item(parms[1]);
Usecode_value u(
(obj0 && obj1)
? obj0->get_outermost()->distance(obj1->get_outermost())
: 0);
return u;
}
USECODE_INTRINSIC(find_direction) {
ignore_unused_variable_warning(num_parms);
// Direction from parm[0] -> parm[1].
// Rets. 0-7. Is 0 east?
Usecode_value u = find_direction(parms[0], parms[1]);
return u;
}
USECODE_INTRINSIC(get_npc_object) {
ignore_unused_variable_warning(num_parms);
// Takes -npc. Returns object, or array of objects.
Usecode_value& v = parms[0];
if (v.is_array()) { // Do it for each element of array.
const int sz = v.get_array_size();
Usecode_value ret(sz, nullptr);
for (int i = 0; i < sz; i++) {
Usecode_value elem(get_item(v.get_elem(i)));
ret.put_elem(i, elem);
}
return ret;
}
Game_object* obj = get_item(parms[0]);
Usecode_value u(obj);
return u;
}
USECODE_INTRINSIC(get_schedule_type) {
ignore_unused_variable_warning(num_parms);
// GetSchedule(npc). Rets. schedtype.
Actor* npc = as_actor(get_item(parms[0]));
if (!npc) {
return Usecode_value(0);
}
Schedule* schedule = npc->get_schedule();
int sched = schedule ? schedule->get_actual_type(npc)
: npc->get_schedule_type();
// Path_run_usecode? (This is to fix
// a bug in the Fawn Trial.)
//+++++Should be a better way to check.
if (Game::get_game_type() == SERPENT_ISLE && npc->get_action()
&& npc->get_action()->as_usecode_path()) {
// Give a 'fake' schedule.
sched = Schedule::walk_to_schedule;
}
Usecode_value u(sched);
return u;
}
USECODE_INTRINSIC(set_schedule_type) {
ignore_unused_variable_warning(num_parms);
// SetSchedule?(npc, schedtype).
// Looks like 15=wait here, 11=go home, 0=train/fight... This is the
// 'bNum' field in schedules.
Actor* npc = as_actor(get_item(parms[0]));
if (npc) {
const int newsched = parms[1].get_int_value();
npc->set_schedule_type(newsched);
// Taking Avatar out of combat?
if (npc == gwin->get_main_actor() && gwin->in_combat()
&& newsched != Schedule::combat)
// End combat mode (for L.Field).
{
Audio::get_ptr()->stop_music();
gwin->toggle_combat();
}
}
return no_ret;
}
USECODE_INTRINSIC(add_to_party) {
ignore_unused_variable_warning(num_parms);
// NPC joins party.
Actor* npc = as_actor(get_item(parms[0]));
if (!partyman->add_to_party(npc)) {
return no_ret; // Can't add.
}
npc->set_schedule_type(Schedule::follow_avatar);
npc->set_alignment(Actor::good);
// cout << "NPC " << npc->get_npc_num() << " added to party." << endl;
return no_ret;
}
USECODE_INTRINSIC(remove_from_party) {
ignore_unused_variable_warning(num_parms);
// NPC leaves party.
Actor* npc = as_actor(get_item(parms[0]));
if (partyman->remove_from_party(npc)) {
npc->set_alignment(Actor::neutral);
}
return no_ret;
}
USECODE_INTRINSIC(get_npc_prop) {
ignore_unused_variable_warning(num_parms);
// Get NPC prop (item, prop_id).
Game_object* obj = get_item(parms[0]);
Actor* npc = as_actor(obj);
if (!obj) {
return Usecode_value(0);
}
if (!npc) {
if (parms[1].get_int_value() == static_cast<int>(Actor::health)) {
return Usecode_value(obj->get_obj_hp());
}
return Usecode_value(0);
}
const char* att = parms[1].get_str_value();
if (att) {
return Usecode_value(npc->get_attribute(att));
} else {
return Usecode_value(npc->get_property(parms[1].get_int_value()));
}
}
USECODE_INTRINSIC(set_npc_prop) {
ignore_unused_variable_warning(num_parms);
// Set NPC prop (item, prop_id, delta_value).
Game_object* obj = get_item(parms[0]);
Actor* npc = as_actor(obj);
if (npc) {
// NOTE: 3rd parm. is a delta!
const char* att = parms[1].get_str_value();
if (att) {
npc->set_attribute(
att, npc->get_attribute(att) + parms[2].get_int_value());
} else {
const int prop = parms[1].get_int_value();
int delta = parms[2].get_int_value();
if (prop == static_cast<int>(Actor::exp)) {
if (delta < 0) {
// There is a bug in Silver Seed when you plant the silver
// seed with more than 25600 exp: the intended exp bonus is
// 0xC800, which gets misinterpreted as -0x3800.
// In the original game, there seems to be a check that
// prevents negative exp bonuses from usecode; we will
// instead fix this here.
// If this is a 16-bit negative value, make it positive.
// Otherwise, bail out.
if (delta >= std::numeric_limits<int16_t>::min()) {
delta = static_cast<uint16_t>(delta);
} else {
return Usecode_value(1);
}
}
delta /= 2; // Verified.
}
if (prop != static_cast<int>(Actor::sex_flag)) {
delta += npc->get_property(prop); // NOT for gender.
}
npc->set_property(prop, delta);
}
return Usecode_value(1); // SI needs return.
} else if (obj) {
// Verified. Needed by serpent statue at end of SI.
const int prop = parms[1].get_int_value();
const int delta = parms[2].get_int_value();
if (prop == static_cast<int>(Actor::health)) {
obj->set_obj_hp(obj->get_obj_hp() + delta);
return Usecode_value(1);
}
}
return Usecode_value(0);
}
USECODE_INTRINSIC(get_avatar_ref) {
ignore_unused_variable_warning(num_parms, parms);
// Guessing it's Avatar's itemref.
Usecode_value u(gwin->get_main_actor());
return u;
}
USECODE_INTRINSIC(get_party_list) {
ignore_unused_variable_warning(num_parms, parms);
// Return array with party members.
Usecode_value u(get_party());
return u;
}
USECODE_INTRINSIC(create_new_object) {
ignore_unused_variable_warning(num_parms);
// create_new_object(shapenum). Stores it in 'last_created'.
const int shapenum = parms[0].get_int_value();
const Game_object_shared obj = create_object(shapenum, false);
Usecode_value u(obj.get());
return u;
}
USECODE_INTRINSIC(create_new_object2) {
ignore_unused_variable_warning(num_parms);
// create_new_object(shapenum, loc).
// Pretty sure this is for creating monsters with equipment!
const int shapenum = parms[0].get_int_value();
// Create, and equip if monster.
const Game_object_shared obj = create_object(shapenum, true);
if (obj) {
UI_update_last_created(1, &parms[1]);
}
Usecode_value u(obj);
return u;
}
USECODE_INTRINSIC(set_last_created) {
ignore_unused_variable_warning(num_parms);
// Take itemref off map and set last_created to it.
Game_object* obj = get_item(parms[0]);
// Don't do it for same object if already there.
for (auto& it : last_created) {
if (it.get() == obj) {
return Usecode_value(0);
}
}
modified_map = true;
Game_object_shared keep;
if (obj) {
add_dirty(obj); // Set to repaint area.
last_created.push_back(obj->shared_from_this());
obj->remove_this(&keep); // Remove, but don't delete.
}
Usecode_value u(obj);
return u;
}
USECODE_INTRINSIC(update_last_created) {
ignore_unused_variable_warning(num_parms);
// Think it takes array from 0x18,
// updates last-created object.
// ??guessing??
modified_map = true;
if (last_created.empty()) {
Usecode_value u(0);
return u;
}
const Game_object_shared obj = last_created.back();
last_created.pop_back();
obj->set_invalid(); // It's already been removed.
Usecode_value& arr = parms[0];
const size_t sz = arr.get_array_size();
if (sz >= 2) {
// arr is loc (x, y, z, map) if sz == 4,
//(x, y, z) for sz == 3 and (x, y) for sz == 2
const Tile_coord dest(
arr.get_elem(0).get_int_value(),
arr.get_elem(1).get_int_value(),
sz >= 3 ? arr.get_elem(2).get_int_value() : 0);
obj->move(
dest.tx, dest.ty, dest.tz,
sz < 4 ? -1 : arr.get_elem(3).get_int_value());
} else if (sz == 1) {
obj->remove_this();
}
#ifdef DEBUG
else {
cout << " { Intrinsic 0x26: ";
arr.print(cout);
cout << endl << "} ";
}
#endif
// gwin->paint_dirty(); // Problems in conversations.
// gwin->show(); // ??
Usecode_value u(1);
return u;
}
USECODE_INTRINSIC(get_npc_name) {
ignore_unused_variable_warning(num_parms);
// Get NPC name(s). Works on arrays, too.
static const char* unknown = "??name??";
auto get_name = [&](const Usecode_value& val) -> std::string {
Game_object* obj = get_item(val);
if (obj != nullptr) {
Actor* npc = as_actor(obj);
return npc != nullptr ? npc->get_npc_name() : obj->get_name();
}
return unknown;
};
const int cnt = parms[0].get_array_size();
Usecode_value ret;
if (cnt != 0) {
// Do array.
ret = Usecode_value(0, nullptr);
int size = 0;
for (int i = 0; i < cnt; i++) {
const std::string name = get_name(parms[0].get_elem(i));
if (name != unknown) {
Usecode_value v(name);
ret.resize(size + 1);
ret.put_elem(size, v);
size++;
}
}
return ret;
}
ret = get_name(parms[0]);
return ret;
}
USECODE_INTRINSIC(set_npc_name) {
ignore_unused_variable_warning(num_parms);
// Set NPC name.
Actor* npc = as_actor(get_item(parms[0]));
if (!npc) {
return no_ret;
}
npc->set_npc_name(parms[1].get_str_value());
return no_ret;
}
USECODE_INTRINSIC(count_objects) {
ignore_unused_variable_warning(num_parms);
// How many?
// ((npc?-357==party, -356=avatar),
// item, quality, frame (c_any_framenum = any)).
// Quality/frame -359 means any.
Usecode_value u(count_objects(parms[0], parms[1], parms[2], parms[3]));
return u;
}
USECODE_INTRINSIC(find_object) {
ignore_unused_variable_warning(num_parms);
// Find_object(container(-357=party) OR loc, shapenum, qual?? (-359=any),
// frame??(-359=any)).
const int shnum = parms[1].get_int_value();
const int qual = parms[2].get_int_value();
const int frnum = parms[3].get_int_value();
if (parms[0].get_array_size() == 3) {
// Location (x, y).
Game_object_vector vec;
Game_object::find_nearby(
vec,
Tile_coord(
parms[0].get_elem(0).get_int_value(),
parms[0].get_elem(1).get_int_value(),
parms[0].get_elem(2).get_int_value()),
shnum, 1, 0, qual, frnum);
if (vec.empty()) {
return Usecode_value(static_cast<Game_object*>(nullptr));
} else {
return Usecode_value(vec.front());
}
}
const int oval = parms[0].get_int_value();
if (oval == -359) { // Find on map (?)
Game_object_vector vec;
const TileRect scr = gwin->get_win_tile_rect();
Game_object::find_nearby(
vec, Tile_coord(scr.x + scr.w / 2, scr.y + scr.h / 2, 0), shnum,
scr.h / 2, 0, qual, frnum);
return vec.empty() ? Usecode_value(static_cast<Game_object*>(nullptr))
: Usecode_value(vec[0]);
}
if (oval != -357) { // Not the whole party?
// Find inside owner.
Game_object* obj = get_item(parms[0]);
if (!obj) {
return Usecode_value(static_cast<Game_object*>(nullptr));
}
Game_object* f = obj->find_item(shnum, qual, frnum);
return Usecode_value(f);
}
// Look through whole party.
Usecode_value party = get_party();
const int cnt = party.get_array_size();
for (int i = 0; i < cnt; i++) {
Game_object* obj = get_item(party.get_elem(i));
if (obj) {
Game_object* f = obj->find_item(shnum, qual, frnum);
if (f) {
return Usecode_value(f);
}
}
}
return Usecode_value(static_cast<Game_object*>(nullptr));
}
USECODE_INTRINSIC(get_cont_items) {
ignore_unused_variable_warning(num_parms);
// Get cont. items(container, shape, qual, frame).
// recursively find items in container
Usecode_value u(get_objects(parms[0], parms[1], parms[2], parms[3]));
return u;
}
USECODE_INTRINSIC(remove_party_items) {
ignore_unused_variable_warning(num_parms);
// Remove items(quantity, item, ??quality?? (-359), frame(-359), T/F).
return remove_party_items(parms[0], parms[1], parms[2], parms[3], parms[4]);
}
USECODE_INTRINSIC(add_party_items) {
ignore_unused_variable_warning(num_parms);
// Add items(num, item, ??quality?? (-359), frame (or -359), T/F).
// Returns array of NPC's (->'s) who got the items.
Usecode_value u(
add_party_items(parms[0], parms[1], parms[2], parms[3], parms[4]));
return u;
}
USECODE_INTRINSIC(get_music_track) {
ignore_unused_variable_warning(num_parms, parms);
// Returns the song currently playing. In the original BG, this
// returned a word: the high byte was the current song and the
// low byte could be the current song (most cases) or, in some
// cases, the song that was playing before and would be continued
// after the current song ends. For example, if you played song 12
// and then song 13, this function would return 0xD0C; after
// playing song 13, BG would resume playing song 12 because it is
// longer than song 13.
// In SI, it simply returns the current playing song.
// In Exult, we do it the SI way.
if (Audio::get_ptr()->get_midi()) {
return Usecode_value(Audio::get_ptr()->get_midi()->get_current_track());
} else {
return Usecode_value(-1);
}
}
USECODE_INTRINSIC(play_music) {
ignore_unused_variable_warning(num_parms);
// Play music(songnum, item).
// ??Show notes by item?
#ifdef DEBUG
cout << "Music request in usecode" << endl;
cout << "Parameter data follows" << endl;
cout << "0: " << ((parms[0].get_int_value() >> 8) & 0xff) << " "
<< ((parms[0].get_int_value()) & 0xff) << endl;
cout << "1: " << ((parms[1].get_int_value() >> 8) & 0x01) << " "
<< ((parms[1].get_int_value()) & 0x01) << endl;
#endif
const int track = parms[0].get_int_value() & 0xff;
if (track == 0xff) { // I think this is right:
Audio::get_ptr()->cancel_streams(); // Stop playing.
} else {
Audio::get_ptr()->start_music(
track, (parms[0].get_int_value() >> 8) & 0x01);
// If a number but not an NPC, get out (for e.g.,
// SI function 0x1D1).
if (parms[1].is_int()
&& (parms[1].get_int_value() >= 0
|| (parms[1].get_int_value() != -356
&& parms[1].get_int_value() < -gwin->get_num_npcs()))) {
return no_ret;
}
// Show notes.
Game_object* obj = get_item(parms[1]);
if (obj && !obj->is_pos_invalid()) {
gwin->get_effects()->add_effect(
std::make_unique<Sprites_effect>(24, obj, 0, 0, -2, -2));
}
}
return no_ret;
}
USECODE_INTRINSIC(npc_nearby) {
ignore_unused_variable_warning(num_parms);
// NPC nearby? (item).
Game_object* obj = get_item(parms[0]);
if (!obj) {
return Usecode_value(0);
}
const Tile_coord pos = obj->get_tile();
Actor* npc;
const bool is_near
= gwin->get_win_tile_rect().has_world_point(pos.tx, pos.ty) &&
// Guessing: true if non-NPC, false if NPC is dead, asleep or
// paralyzed.
((npc = as_actor(obj)) == nullptr || npc->can_act());
Usecode_value u(is_near);
return u;
}
USECODE_INTRINSIC(npc_nearby2) {
ignore_unused_variable_warning(num_parms);
// Guessing wildly (SI). Handles start of Moonshade trial where
// companions are a fair distance away.
Game_object* npc = get_item(parms[0]);
const bool is_near
= (npc != nullptr &&
// Guessing; being asleep, paralyzed or dead doesn't seem to
// affect this.
npc->distance(gwin->get_main_actor()) < 40);
Usecode_value u(is_near);
return u;
}
USECODE_INTRINSIC(find_nearby_avatar) {
ignore_unused_variable_warning(num_parms);
// Find objs. with given shape near Avatar?
Usecode_value av(gwin->get_main_actor());
// Try bigger # for Test of Love tree.
Usecode_value dist(/* 64 */ 192);
Usecode_value mask(0);
Usecode_value u(find_nearby(av, parms[0], dist, mask));
return u;
}
USECODE_INTRINSIC(is_npc) {
ignore_unused_variable_warning(num_parms);
// Is item an NPC?
Actor* npc = as_actor(get_item(parms[0]));
Usecode_value u(npc != nullptr);
return u;
}
USECODE_INTRINSIC(display_runes) {
ignore_unused_variable_warning(num_parms);
// Render text into runes for signs, tombstones, plaques and the like
// Display sign (gump #, array_of_text).
int cnt = parms[1].get_array_size();
if (!cnt) {
cnt = 1; // Try with 1 element.
}
{
Sign_gump sign(parms[0].get_int_value(), cnt);
for (int i = 0; i < cnt; i++) {
// Paint each line.
const Usecode_value& lval
= !i ? parms[1].get_elem0() : parms[1].get_elem(i);
const char* str = lval.get_str_value();
sign.add_text(i, str);
}
int x;
int y; // Paint it, and wait for click.
Get_click(x, y, Mouse::hand, nullptr, false, &sign);
}
gwin->paint();
return no_ret;
}
USECODE_INTRINSIC(click_on_item) {
ignore_unused_variable_warning(num_parms, parms);
// Doesn't ret. until user single-
// clicks on an item. Rets. item.
Game_object* obj;
Tile_coord t;
// intercept this click?
if (intercept_item) {
obj = intercept_item;
intercept_item = nullptr;
if (intercept_tile) {
delete intercept_tile;
intercept_tile = nullptr;
}
t = obj->get_tile();
} else if (intercept_tile) {
obj = nullptr;
t = *intercept_tile;
delete intercept_tile;
intercept_tile = nullptr;
}
// Special case for weapon hit:
else if (frame->eventid == weapon && caller_item) {
// Special hack for weapons (needed for hitting Draygan with
// sleep arrows (SI) and worms with worm hammer (also SI)).
// Spells cast from readied spellbook in combat have been
// changed to use the intercept_item instead, setting it
// to the caster's target and restoring the old value after
// it is used.
obj = caller_item.get();
t = obj->get_tile();
} else {
int x;
int y; // Allow dragging while here:
if (!Get_click(x, y, Mouse::greenselect, nullptr, true)) {
return Usecode_value(0);
}
// Get abs. tile coords. clicked on.
t = Tile_coord(
gwin->get_scrolltx() + x / c_tilesize,
gwin->get_scrollty() + y / c_tilesize, 0);
// Look for obj. in open gump.
Gump* gump = gumpman->find_gump(x, y);
if (gump) {
obj = gump->find_object(x, y);
if (!obj) {
obj = gump->find_actor(x, y);
}
} else { // Search rest of world.
obj = gwin->find_object(x, y);
if (obj) { // Found object? Use its coords.
t = obj->get_tile();
}
}
}
Usecode_value oval(obj); // Ret. array with obj as 1st elem.
Usecode_value ret(4, &oval);
Usecode_value xval(t.tx);
Usecode_value yval(t.ty);
Usecode_value zval(t.tz);
ret.put_elem(1, xval);
ret.put_elem(2, yval);
ret.put_elem(3, zval);
return ret;
}
/* Set item to be returned by next call to click_on_item().
* Added for Exult.
*/
USECODE_INTRINSIC(set_intercept_item) {
ignore_unused_variable_warning(num_parms);
intercept_item = get_item(parms[0]);
if (intercept_item) {
delete intercept_tile;
intercept_tile = nullptr;
} else {
// Not an item, or null item.
const int sz = parms[0].get_array_size();
switch (sz) {
case 2:
case 3:
case 4: {
const int off = sz == 4 ? 1 : 0;
// 2: (x, y) loc.
// 3: (x, y, z) loc.
// 4: (obj, x, y, z) loc.
intercept_tile = new Tile_coord(
parms[0].get_elem(0 + off).get_int_value(),
parms[0].get_elem(1 + off).get_int_value(),
sz >= 3 ? parms[0].get_elem(2 + off).get_int_value() : 0);
} break;
default: {
// Fallback to avatar's position.
// Maybe try avatar's target?
intercept_tile = new Tile_coord(gwin->get_main_actor()->get_tile());
break;
}
}
}
return no_ret;
}
USECODE_INTRINSIC(find_nearby) {
ignore_unused_variable_warning(num_parms);
// Think it rets. objs. near parm0.
Usecode_value u(find_nearby(parms[0], parms[1], parms[2], parms[3]));
return u;
}
USECODE_INTRINSIC(give_last_created) {
ignore_unused_variable_warning(num_parms);
// Think it's give_last_created(container).
Game_object* cont = get_item(parms[0]);
bool ret = false;
if (cont && !last_created.empty()) {
// Get object, but don't pop yet.
Game_object* obj = last_created.back().get();
// Might not have been removed from world yet.
if (!obj->get_owner() && obj->is_pos_invalid()) {
// Don't check vol. Causes failures.
ret = cont->add(obj, true);
}
if (ret) { // Pop only if added. Fixes chest/
// tooth bug in SI.
last_created.pop_back();
}
}
Usecode_value u(ret);
return u;
}
USECODE_INTRINSIC(is_dead) {
ignore_unused_variable_warning(num_parms);
// Return 1 if parm0 is a dead NPC.
Actor* npc = as_actor(get_item(parms[0]));
Usecode_value u(npc && npc->is_dead());
return u;
}
USECODE_INTRINSIC(game_day) {
ignore_unused_variable_warning(num_parms, parms);
Usecode_value u(gclock->get_day());
return u;
}
USECODE_INTRINSIC(game_hour) {
ignore_unused_variable_warning(num_parms, parms);
// Return. game time hour (0-23).
Usecode_value u(gclock->get_hour());
return u;
}
USECODE_INTRINSIC(game_minute) {
ignore_unused_variable_warning(num_parms, parms);
// Return minute (0-59).
Usecode_value u(gclock->get_minute());
return u;
}
USECODE_INTRINSIC(get_npc_number) {
ignore_unused_variable_warning(num_parms);
// Returns NPC# of item. (-356 =
// avatar).
Actor* npc = as_actor(get_item(parms[0]));
if (npc == gwin->get_main_actor()) {
Usecode_value u(-356);
return u;
}
const int num = npc ? npc->get_npc_num() : 0;
Usecode_value u(-num);
return u;
}
USECODE_INTRINSIC(part_of_day) {
ignore_unused_variable_warning(num_parms, parms);
// Return 3-hour # (0-7, 0=midnight).
Usecode_value u(gclock->get_hour() / 3);
return u;
}
USECODE_INTRINSIC(get_alignment) {
ignore_unused_variable_warning(num_parms);
// Get npc's alignment.
Actor* npc = as_actor(get_item(parms[0]));
Usecode_value u(npc ? npc->get_effective_alignment() : 0);
return u;
}
USECODE_INTRINSIC(set_alignment) {
ignore_unused_variable_warning(num_parms);
// Set npc's alignment.
// 2,3==bad towards Ava. 0==good.
Actor* npc = as_actor(get_item(parms[0]));
const int val = parms[1].get_int_value();
if (npc) {
const int oldalign = npc->get_effective_alignment();
npc->set_effective_alignment(val);
if (oldalign != val) { // Changed? Force search for new opp.
Combat_schedule::stop_attacking_npc(npc);
npc->set_target(nullptr);
}
// For fixing List Field fleeing:
if (npc->get_attack_mode() == Actor::flee) {
npc->set_attack_mode(Actor::nearest);
}
}
return no_ret;
}
USECODE_INTRINSIC(move_object) {
// move_object(obj(-357=party), (tx, ty, tz)).
Usecode_value& p = parms[1];
const Tile_coord tile(
p.get_elem(0).get_int_value(), p.get_elem(1).get_int_value(),
p.get_array_size() > 2 ? p.get_elem(2).get_int_value() : 0);
const int map = p.get_array_size() < 4 ? -1 : p.get_elem(3).get_int_value();
Actor* ava = gwin->get_main_actor();
modified_map = true;
if (parms[0].get_int_value() == -357) {
// Move whole party.
gwin->teleport_party(
tile, false, map,
num_parms > 2 ? parms[2].get_int_value() : false);
return no_ret;
}
Game_object* obj = get_item(parms[0]);
if (!obj) {
return no_ret;
}
const Tile_coord oldpos = obj->get_tile();
obj->move(tile.tx, tile.ty, tile.tz, map);
Actor* act = as_actor(obj);
if (act) {
act->set_action(nullptr);
if (act == ava) {
// Teleported Avatar?
// Make new loc. visible, test eggs.
if (map != -1) {
gwin->set_map(map);
}
gwin->center_view(tile);
Map_chunk::try_all_eggs(
ava, tile.tx, tile.ty, tile.tz, oldpos.tx, oldpos.ty);
}
// Close? Add to 'nearby' list.
else if (ava->distance(act) < gwin->get_game_width() / c_tilesize) {
Npc_actor* npc = act->as_npc();
if (npc) {
gwin->add_nearby_npc(npc);
}
}
}
return no_ret;
}
USECODE_INTRINSIC(remove_npc) {
ignore_unused_variable_warning(num_parms);
// Remove_npc(npc) - Remove npc from world.
Actor* npc = as_actor(get_item(parms[0]));
if (npc) {
modified_map = true;
// Don't want him/her coming back!
npc->set_schedule_type(Schedule::wait);
// Fixes #1892 SI: sacrificed Dupre back in party
// Might be able to always clear ident, but this is safer
if (npc->get_ident() == Schedule::follow_avatar) {
npc->set_ident(0);
}
gwin->add_dirty(npc);
Game_object_shared keep;
npc->remove_this(&keep); // Remove, but don't delete.
}
return no_ret;
}
USECODE_INTRINSIC(item_say) {
ignore_unused_variable_warning(num_parms);
// Show str. near item (item, str).
if (!conv->is_npc_text_pending()) {
item_say(parms[0], parms[1]); // Do it now.
}
return no_ret;
}
USECODE_INTRINSIC(clear_item_say) {
ignore_unused_variable_warning(num_parms);
// Clear str. near item (item).
Game_object* item = get_item(parms[0]);
if (item) {
gwin->get_effects()->remove_text_effect(item);
// Seems to be right (e.g., the avatar's barks after
// the teleport storm/Karnax vs Thoxa battle).
Usecode_script* scr = nullptr;
while ((scr = Usecode_script::find(item, scr)) != nullptr) {
scr->kill_barks();
}
}
return no_ret;
}
USECODE_INTRINSIC(set_to_attack) {
ignore_unused_variable_warning(num_parms);
// set_to_attack(fromnpc, to, weaponshape).
// fromnpc attacks the target 'to' with weapon weaponshape.
// 'to' can be a game object or the return of a click_on_item
// call (including the possibility of being a tile target).
Actor* from = as_actor(get_item(parms[0]));
if (!from) {
return Usecode_value(0);
}
const int shnum = parms[2].get_int_value();
if (shnum < 0) {
return Usecode_value(0);
}
const Weapon_info* winf = ShapeID::get_info(shnum).get_weapon_info();
if (!winf) {
return Usecode_value(0);
}
Usecode_value& tval = parms[1];
Game_object* to = get_item(tval.get_elem0());
int nelems;
if (to) {
// It is an object.
from->set_attack_target(to, shnum);
return Usecode_value(1);
} else if (tval.is_array() && (nelems = tval.get_array_size()) >= 3) {
// Tile return of click_on_item. Allowing size to be < 4 for safety.
const Tile_coord trg = Tile_coord(
tval.get_elem(1).get_int_value(),
tval.get_elem(2).get_int_value(),
nelems >= 4 ? tval.get_elem(3).get_int_value() : 0);
from->set_attack_target(trg, shnum);
return Usecode_value(1);
}
return Usecode_value(0); // Failure.
}
USECODE_INTRINSIC(get_lift) {
ignore_unused_variable_warning(num_parms);
// ?? Guessing rets. lift(item).
Game_object* obj = get_item(parms[0]);
Usecode_value u(obj ? Usecode_value(obj->get_lift()) : Usecode_value(0));
return u;
}
USECODE_INTRINSIC(set_lift) {
ignore_unused_variable_warning(num_parms);
// ?? Guessing setlift(item, lift).
Game_object* obj = get_item(parms[0]);
if (obj) {
const Tile_coord t = obj->get_tile();
const int lift = parms[1].get_int_value();
if (lift >= 0 && lift < 20) {
obj->move(t.tx, t.ty, lift);
}
gwin->paint();
gwin->show();
modified_map = true;
}
return no_ret;
}
USECODE_INTRINSIC(get_weather) {
ignore_unused_variable_warning(num_parms, parms);
// Get_weather()
return Usecode_value(gwin->get_effects()->get_weather());
}
USECODE_INTRINSIC(set_weather) {
ignore_unused_variable_warning(num_parms);
// Set_weather(i)
Egg_object::set_weather(parms[0].get_int_value());
return no_ret;
}
USECODE_INTRINSIC(sit_down) {
ignore_unused_variable_warning(num_parms);
// Sit_down(npc, chair).
Game_object* nobj = get_item(parms[0]);
Actor* npc = as_actor(nobj);
if (!npc) {
return no_ret; // Doesn't look like an NPC.
}
Game_object* chair = get_item(parms[1]);
if (!chair) {
return no_ret;
}
npc->set_schedule_type(
Schedule::sit, std::make_unique<Sit_schedule>(npc, chair));
return no_ret;
}
USECODE_INTRINSIC(summon) {
ignore_unused_variable_warning(num_parms);
// summon(shape, flag??). Create monster of desired shape.
const int shapenum = parms[0].get_int_value();
const Monster_info* info = ShapeID::get_info(shapenum).get_monster_info();
if (!info) {
return Usecode_value(0);
}
const Tile_coord start = gwin->get_main_actor()->get_tile();
const Tile_coord dest = Map_chunk::find_spot(
start, 5, shapenum, 0, 1, -1,
gwin->is_main_actor_inside() ? Map_chunk::inside
: Map_chunk::outside);
if (dest.tx == -1) {
return Usecode_value(0);
}
Actor* npc = as_actor(caller_item.get());
int align = Actor::good;
if (npc && !npc->is_in_party()) {
align = npc->get_effective_alignment();
}
const Game_object_shared monst
= Monster_actor::create(shapenum, dest, Schedule::combat, align);
return Usecode_value(monst.get());
}
/*
* Class to paint a shape centered.
*/
class Paint_centered : public Paintable, public Game_singletons {
protected:
ShapeID* sid; // ->shape.
int x, y; // Where to paint.
public:
Paint_centered(ShapeID* si) : sid(si) {
Shape_frame* s = sid->get_shape();
// Get coords. for centered view.
x = (gwin->get_game_width() - s->get_width()) / 2 + s->get_xleft();
y = (gwin->get_game_height() - s->get_height()) / 2 + s->get_yabove();
}
void paint() override {
sid->paint_shape(x, y);
}
};
/*
* Paint map.
*/
class Paint_map : public Paint_centered {
bool show_loc;
public:
Paint_map(ShapeID* s, bool loc) : Paint_centered(s), show_loc(loc) {}
void paint() override {
Paint_centered::paint();
if (show_loc) {
// mark location
int xx;
int yy;
const Tile_coord t = gwin->get_main_actor()->get_tile();
if (Game::get_game_type() == BLACK_GATE) {
xx = std::lround(t.tx / 16.05 + 5);
yy = std::lround(t.ty / 15.95 + 4);
} else if (Game::get_game_type() == SERPENT_ISLE) {
xx = std::lround(t.tx / 16.0 + 18);
yy = std::lround(t.ty / 16.0 + 9.4);
} else {
xx = std::lround(t.tx / 16.0 + 5);
yy = std::lround(t.ty / 16.0 + 5);
}
Shape_frame* s = sid->get_shape();
xx += x - s->get_xleft();
yy += y - s->get_yabove();
gwin->get_win()->fill8(50, 1, 5, xx, yy - 2);
gwin->get_win()->fill8(50, 5, 1, xx - 2, yy);
}
}
};
USECODE_INTRINSIC(display_map) {
ignore_unused_variable_warning(num_parms, parms);
// count all sextants in party
Usecode_value v_357(-357);
Usecode_value v650(650);
Usecode_value v_359(-359);
const long sextants
= count_objects(v_357, v650, v_359, v_359).get_int_value();
const bool loc = !gwin->is_main_actor_inside() && (sextants > 0);
// Display map.
if (touchui != nullptr) {
touchui->hideGameControls();
}
if (Face_stats::Visible()) {
Face_stats::HideGump();
}
if (ShortcutBar_gump::Visible()) {
ShortcutBar_gump::HideGump();
}
gwin->paint();
ShapeID msid(game->get_shape("sprites/map"), 0, SF_SPRITES_VGA);
Paint_map map(&msid, loc);
int xx;
int yy;
Get_click(xx, yy, Mouse::hand, nullptr, false, &map);
gwin->paint();
if (touchui != nullptr) {
Gump_manager* gumpman = gwin->get_gump_man();
if (!gumpman->gump_mode()) {
touchui->showGameControls();
}
}
if (!Face_stats::Visible()) {
Face_stats::ShowGump();
}
if (!ShortcutBar_gump::Visible()) {
ShortcutBar_gump::ShowGump();
}
gwin->paint();
return no_ret;
}
USECODE_INTRINSIC(si_display_map) {
const int mapnum = parms[0].get_int_value();
int shapenum;
switch (mapnum) {
case 0:
return UI_display_map(num_parms, parms);
case 1:
shapenum = 57;
break;
case 2:
shapenum = 58;
break;
case 3:
shapenum = 59;
break;
case 4:
shapenum = 60;
break;
case 5:
shapenum = 52;
break;
default:
return no_ret;
}
// Display map.
// Display map.
if (touchui != nullptr) {
touchui->hideGameControls();
}
if (Face_stats::Visible()) {
Face_stats::HideGump();
}
if (ShortcutBar_gump::Visible()) {
ShortcutBar_gump::HideGump();
}
gwin->paint();
ShapeID msid(shapenum, 0, SF_SPRITES_VGA);
Paint_centered map(&msid);
int xx;
int yy;
Get_click(xx, yy, Mouse::hand, nullptr, false, &map);
gwin->paint();
if (touchui != nullptr) {
Gump_manager* gumpman = gwin->get_gump_man();
if (!gumpman->gump_mode()) {
touchui->showGameControls();
}
}
if (!Face_stats::Visible()) {
Face_stats::ShowGump();
}
if (!ShortcutBar_gump::Visible()) {
ShortcutBar_gump::ShowGump();
}
gwin->paint();
return no_ret;
}
USECODE_INTRINSIC(display_map_ex) {
ignore_unused_variable_warning(num_parms);
const int map_shp = parms[0].get_int_value();
const bool loc = parms[1].get_int_value() != 0;
// Display map.
if (touchui != nullptr) {
touchui->hideGameControls();
}
if (Face_stats::Visible()) {
Face_stats::HideGump();
}
if (ShortcutBar_gump::Visible()) {
ShortcutBar_gump::HideGump();
}
gwin->paint();
ShapeID msid(map_shp, 0, SF_SPRITES_VGA);
Paint_map map(&msid, loc);
int xx;
int yy;
Get_click(xx, yy, Mouse::hand, nullptr, false, &map);
gwin->paint();
if (touchui != nullptr) {
Gump_manager* gumpman = gwin->get_gump_man();
if (!gumpman->gump_mode()) {
touchui->showGameControls();
}
}
if (!Face_stats::Visible()) {
Face_stats::ShowGump();
}
if (!ShortcutBar_gump::Visible()) {
ShortcutBar_gump::ShowGump();
}
gwin->paint();
return no_ret;
}
USECODE_INTRINSIC(kill_npc) {
ignore_unused_variable_warning(num_parms);
// kill_npc(npc).
Game_object* item = get_item(parms[0]);
Actor* npc = as_actor(item);
if (npc) {
npc->die(nullptr);
}
modified_map = true;
return no_ret;
}
USECODE_INTRINSIC(roll_to_win) {
ignore_unused_variable_warning(num_parms);
// roll_to_win(attackpts, defendpts)
const int attack = parms[0].get_int_value();
const int defend = parms[1].get_int_value();
return Usecode_value(static_cast<int>(Actor::roll_to_win(attack, defend)));
}
USECODE_INTRINSIC(set_attack_mode) {
ignore_unused_variable_warning(num_parms);
// set_attack_mode(npc, mode).
Actor* npc = as_actor(get_item(parms[0]));
if (npc) {
npc->set_attack_mode(
static_cast<Actor::Attack_mode>(parms[1].need_int_value()));
}
return no_ret;
}
USECODE_INTRINSIC(get_attack_mode) {
ignore_unused_variable_warning(num_parms);
// get_attack_mode(npc).
Actor* npc = as_actor(get_item(parms[0]));
if (npc) {
return Usecode_value(static_cast<int>(npc->get_attack_mode()));
}
return Usecode_value(0);
}
USECODE_INTRINSIC(set_opponent) {
ignore_unused_variable_warning(num_parms);
// set_opponent(npc, new_opponent).
Actor* npc = as_actor(get_item(parms[0]));
Game_object* opponent = get_item(parms[1]);
if (npc && opponent) {
npc->set_target(opponent);
}
return no_ret;
}
USECODE_INTRINSIC(clone) {
ignore_unused_variable_warning(num_parms);
// clone(npc)
Actor* npc = as_actor(get_item(parms[0]));
if (npc) {
modified_map = true;
const Game_object_shared new_npc = npc->clone();
auto* clonednpc = static_cast<Actor*>(new_npc.get());
clonednpc->set_alignment(Actor::good);
clonednpc->set_schedule_type(Schedule::combat);
return Usecode_value(clonednpc);
}
return Usecode_value(0);
}
USECODE_INTRINSIC(get_oppressor) {
ignore_unused_variable_warning(num_parms);
// get_oppressor(npc) Returns 0-n, NPC # (0=avatar).
Actor* npc = as_actor(get_item(parms[0]));
return Usecode_value(npc ? npc->get_oppressor() : 0);
}
USECODE_INTRINSIC(set_oppressor) {
ignore_unused_variable_warning(num_parms);
// set_oppressor(npc, opp)
Actor* npc = as_actor(get_item(parms[0]));
Actor* opp = as_actor(get_item(parms[1]));
if (npc && opp && npc != opp) { // Just in case.
if (opp == gwin->get_main_actor()) {
npc->set_oppressor(0);
} else {
npc->set_oppressor(opp->get_npc_num());
}
}
return no_ret;
}
USECODE_INTRINSIC(get_weapon) {
ignore_unused_variable_warning(num_parms);
// get_weapon(npc). Returns shape.
Actor* npc = as_actor(get_item(parms[0]));
if (npc) {
int shape;
int points;
Game_object* w;
if (npc->get_weapon(points, shape, w)) {
return Usecode_value(shape);
}
}
return Usecode_value(0);
}
USECODE_INTRINSIC(display_area) {
ignore_unused_variable_warning(num_parms);
// display_area(tilepos) - used for crystal balls.
const int size = parms[0].get_array_size();
if (size >= 3) {
const int tx = parms[0].get_elem(0).get_int_value();
const int ty = parms[0].get_elem(1).get_int_value();
// int unknown = parms[0].get_elem(2).get_int_value();
// Figure in tiles.
const int newmap
= size == 3 ? -1 : parms[0].get_elem(3).get_int_value();
const int oldmap = gwin->get_map()->get_num();
const int tw = gwin->get_game_width() / c_tilesize;
const int th = gwin->get_game_height() / c_tilesize;
if (touchui != nullptr) {
touchui->hideGameControls();
}
if (Face_stats::Visible()) {
Face_stats::HideGump();
}
if (ShortcutBar_gump::Visible()) {
ShortcutBar_gump::HideGump();
}
gwin->clear_screen(); // Fill with black.
if ((newmap != -1) && (newmap != oldmap)) {
gwin->set_map(newmap);
}
Shape_frame* sprite = ShapeID(10, 0, SF_SPRITES_VGA).get_shape();
// Center it.
const int topx = (gwin->get_game_width() - sprite->get_width()) / 2;
const int topy = (gwin->get_game_height() - sprite->get_height()) / 2;
// Get area to show.
int x = 0;
int y = 0;
const int w = gwin->get_game_width();
const int h = gwin->get_game_height();
const int sizex = (w - 320) / 2;
const int sizey = (h - 200) / 2;
// Show only inside the original resolution.
if (w > 320) {
x = sizex;
}
if (h > 200) {
y = sizey;
}
const int save_dungeon = gwin->is_in_dungeon();
// Paint game area.
gwin->set_in_dungeon(0); // Disable dungeon.
gwin->paint_map_at_tile(x, y, 320, 200, tx - tw / 2, ty - th / 2, 4);
// Paint sprite #10
// over it, transparently.
sman->paint_shape(
topx + sprite->get_xleft(), topy + sprite->get_yabove(), sprite,
true);
gwin->set_in_dungeon(save_dungeon);
gwin->show();
// Wait for click.
Get_click(x, y, Mouse::hand, nullptr, false, nullptr);
// BG orrery viewer needs this because it also calls UI_view_tile:
gwin->center_view(gwin->get_main_actor()->get_tile());
if ((newmap != -1) && (newmap != oldmap)) {
gwin->set_map(oldmap);
}
if (touchui != nullptr) {
touchui->showGameControls();
}
if (!Face_stats::Visible()) {
Face_stats::ShowGump();
}
if (!ShortcutBar_gump::Visible()) {
ShortcutBar_gump::ShowGump();
}
gwin->paint(); // Repaint normal area.
}
return no_ret;
}
USECODE_INTRINSIC(wizard_eye) {
ignore_unused_variable_warning(num_parms);
// wizard_eye(#ticks, ??);
extern void Wizard_eye(long);
// Let's give 50% longer.
Wizard_eye(parms[0].get_int_value() * (3 * gwin->get_std_delay()) / 2);
return no_ret;
}
USECODE_INTRINSIC(resurrect) {
ignore_unused_variable_warning(num_parms);
// resurrect(body). Returns actor if successful.
Game_object* body = get_item(parms[0]);
const int npc_num = body ? body->get_live_npc_num() : -1;
if (npc_num < 0) {
return Usecode_value(static_cast<Game_object*>(nullptr));
}
Actor* actor = gwin->get_npc(npc_num);
if (actor) {
// Want to resurrect after returning.
auto* scr = new Usecode_script(body);
(*scr) << Ucscript::resurrect;
scr->start();
modified_map = true;
}
return Usecode_value(actor);
}
USECODE_INTRINSIC(resurrect_npc) {
ignore_unused_variable_warning(num_parms);
// resurrect_npc(npc).
// Behaves like the original does.
Actor* actor = as_actor(get_item(parms[0]));
if (actor) {
// Want to resurrect after returning.
actor->resurrect(nullptr);
modified_map = true;
}
return no_ret;
}
USECODE_INTRINSIC(get_body_npc) {
ignore_unused_variable_warning(num_parms);
// get_body_npc(body). Returns npc # (negative).
Game_object* obj = get_item(parms[0]);
const int num = obj ? obj->get_live_npc_num() : -1;
return Usecode_value(num > 0 ? -num : 0);
}
USECODE_INTRINSIC(add_spell) {
ignore_unused_variable_warning(num_parms);
// add_spell(spell# (0-71), ??, spellbook).
// Returns 0 if book already has that spell.
Game_object* obj = get_item(parms[2]);
auto* book = obj->as_spellbook();
if (!book) {
cout << "Add_spell - Not a spellbook!" << endl;
return Usecode_value(0);
}
return Usecode_value(book->add_spell(parms[0].get_int_value()));
}
USECODE_INTRINSIC(remove_all_spells) {
ignore_unused_variable_warning(num_parms);
// remove_all_spells(spellbook).
// Removes all spells from spellbook.
Game_object* obj = get_item(parms[0]);
auto* book = obj->as_spellbook();
if (!book) {
cout << "remove_all_spells - Not a spellbook!" << endl;
return no_ret;
}
book->clear_spells();
return no_ret;
}
USECODE_INTRINSIC(has_spell) {
ignore_unused_variable_warning(num_parms);
// has_spell(spellbook, spell#).
// Returns true if the spellbook has desired spell, false if not.
Game_object* obj = get_item(parms[0]);
auto* book = obj->as_spellbook();
if (!book) {
cout << "has_spell - Not a spellbook!" << endl;
return Usecode_value(0);
}
return Usecode_value(book->has_spell(parms[1].get_int_value()));
}
USECODE_INTRINSIC(remove_spell) {
ignore_unused_variable_warning(num_parms);
// remove_spell(spellbook, spell#).
// Returns true if the spellbook has desired spell, false if not.
Game_object* obj = get_item(parms[0]);
auto* book = obj->as_spellbook();
if (!book) {
cout << "remove_spell - Not a spellbook!" << endl;
return Usecode_value(0);
}
return Usecode_value(book->remove_spell(parms[1].get_int_value()));
}
USECODE_INTRINSIC(sprite_effect) {
ignore_unused_variable_warning(num_parms);
// Display animation from sprites.vga.
// show_sprite(sprite#, tx, ty, dx, dy, frame, length??);
gwin->get_effects()->add_effect(std::make_unique<Sprites_effect>(
parms[0].get_int_value(),
Tile_coord(parms[1].get_int_value(), parms[2].get_int_value(), 0),
parms[3].get_int_value(), parms[4].get_int_value(), 0,
parms[5].get_int_value(), parms[6].get_int_value()));
return no_ret;
}
USECODE_INTRINSIC(obj_sprite_effect) {
ignore_unused_variable_warning(num_parms);
// obj_sprite_effect(obj, sprite#, -xoff, -yoff, dx, dy,
// frame, length??)
Game_object* obj = get_item(parms[0]);
if (obj) {
gwin->get_effects()->add_effect(std::make_unique<Sprites_effect>(
parms[1].get_int_value(), obj, -parms[2].get_int_value(),
-parms[3].get_int_value(), parms[4].get_int_value(),
parms[5].get_int_value(), parms[6].get_int_value(),
parms[7].get_int_value()));
}
return no_ret;
}
USECODE_INTRINSIC(attack_object) {
ignore_unused_variable_warning(num_parms);
// attack_object(attacker, target, wshape).
Game_object* att = get_item(parms[0]);
Game_object* trg = get_item(parms[1]);
const int wshape = parms[2].get_int_value();
if (!att || !trg) {
return Usecode_value(0);
}
const Tile_coord tile(-1, -1, 0);
return Usecode_value(
Combat_schedule::attack_target(att, trg, tile, wshape));
}
USECODE_INTRINSIC(book_mode) {
ignore_unused_variable_warning(num_parms);
// Display book or scroll.
Text_gump* gump;
Game_object* obj = get_item(parms[0]);
if (!obj) {
return no_ret;
}
// check for avatar read here
const bool do_serp = !gwin->get_main_actor()->get_flag(Obj_flags::read);
const int fnt = do_serp ? 8 : 4;
if (obj->get_shapenum() == 707) { // Serpentine Scroll - Make SI only???
gump = new Scroll_gump(fnt);
} else if (obj->get_shapenum() == 705) { // Serpentine Book - Make SI
// only???
gump = new Book_gump(fnt);
} else if (obj->get_shapenum() == 797) {
gump = new Scroll_gump();
} else {
gump = new Book_gump();
}
set_book(gump);
return no_ret;
}
USECODE_INTRINSIC(book_mode_ex) {
// Display book or scroll.
Text_gump* gump;
const bool is_scroll = parms[0].get_int_value() != 0;
const int fnt = parms[1].get_int_value();
const int gumpshp = num_parms >= 3 ? parms[2].get_int_value() : -1;
if (is_scroll) {
gump = new Scroll_gump(fnt, gumpshp);
} else {
gump = new Book_gump(fnt, gumpshp);
}
set_book(gump);
return no_ret;
}
USECODE_INTRINSIC(stop_time) {
ignore_unused_variable_warning(num_parms);
// stop_time(.25 secs).
const int length = parms[0].get_int_value();
gwin->set_time_stopped(length * 250);
return no_ret;
}
USECODE_INTRINSIC(cause_light) {
ignore_unused_variable_warning(num_parms);
// Cause_light(game_minutes??)
gwin->add_special_light(parms[0].get_int_value());
return no_ret;
}
USECODE_INTRINSIC(get_barge) {
ignore_unused_variable_warning(num_parms);
// get_barge(obj) - returns barge object is part of or lying on.
Game_object* obj = get_item(parms[0]);
if (!obj) {
return Usecode_value(static_cast<Game_object*>(nullptr));
}
return Usecode_value(Get_barge(obj));
}
USECODE_INTRINSIC(earthquake) {
ignore_unused_variable_warning(num_parms);
const int len = parms[0].get_int_value();
gwin->get_tqueue()->add(Game::get_ticks() + 10, new Earthquake(len), this);
return no_ret;
}
USECODE_INTRINSIC(is_pc_female) {
ignore_unused_variable_warning(num_parms, parms);
// Is player female?
Usecode_value u(gwin->get_main_actor()->get_type_flag(Actor::tf_sex));
return u;
}
static inline void Armageddon_death(
Actor* npc, bool barks, const TileRect& screen) {
// Leave a select few alive (like LB, Batlin).
if (npc && !npc->is_dead() && !npc->get_info().survives_armageddon()) {
constexpr static const std::array text{
"Aiiiieee!", "Noooo!", "#!?*#%!"};
const Tile_coord loc = npc->get_tile();
if (barks && screen.has_world_point(loc.tx, loc.ty)) {
npc->say(text[rand() % text.size()]);
}
// Lay down and lie animation.
npc->lay_down(false);
// Originals set health to -10; marking it this way allows
// Actor::is_dying to return true in case it is needed.
npc->set_property(
static_cast<int>(Actor::health),
-npc->get_property(static_cast<int>(Actor::health)) / 3 - 1);
// This makes the NPC stay there unresponsive and immune to damage.
npc->set_flag(Obj_flags::dead);
}
}
USECODE_INTRINSIC(armageddon) {
ignore_unused_variable_warning(num_parms, parms);
const int cnt = gwin->get_num_npcs();
const TileRect screen = gwin->get_win_tile_rect();
for (int i = 1; i < cnt; i++) { // Almost everyone dies.
Armageddon_death(gwin->get_npc(i), true, screen);
}
Actor_vector vec; // Get any monsters nearby.
gwin->get_main_actor()->find_nearby_actors(vec, c_any_shapenum, 40, 0x28);
for (auto* act : vec) {
if (act->is_monster()) {
Armageddon_death(act, false, screen);
}
}
gwin->armageddon = true;
return no_ret;
}
USECODE_INTRINSIC(halt_scheduled) {
ignore_unused_variable_warning(num_parms);
// Halt_scheduled(item)
Game_object* obj = get_item(parms[0]);
if (obj) {
Usecode_script::terminate(obj);
}
return no_ret;
}
USECODE_INTRINSIC(lightning) {
ignore_unused_variable_warning(num_parms, parms);
// 1 sec. is long enough for 1 flash.
gwin->get_effects()->remove_usecode_lightning();
gwin->get_effects()->add_effect(
std::make_unique<Lightning_effect>(1000, 0, true));
return no_ret;
}
USECODE_INTRINSIC(get_array_size) {
ignore_unused_variable_warning(num_parms);
int cnt;
if (parms[0].is_array()) { // An array? We might return 0.
cnt = parms[0].get_array_size();
} else { // Not an array? Usecode wants a 1.
cnt = 1;
}
Usecode_value u(cnt);
return u;
}
USECODE_INTRINSIC(mark_virtue_stone) {
ignore_unused_variable_warning(num_parms);
Game_object* obj = get_item(parms[0]);
auto* vs = obj->as_virtstone();
if (vs) {
vs->set_target_pos(obj->get_outermost()->get_tile());
vs->set_target_map(obj->get_outermost()->get_map_num());
}
return no_ret;
}
USECODE_INTRINSIC(recall_virtue_stone) {
Game_object* obj = get_item(parms[0]);
Game_object_shared keep;
auto* vs = obj->as_virtstone();
if (vs) {
gumpman->close_all_gumps();
// Pick it up if necessary.
if (!obj->get_owner()) {
// Go through whole party.
obj->remove_this(&keep);
Usecode_value party = get_party();
const int cnt = party.get_array_size();
int i;
for (i = 0; i < cnt; i++) {
Game_object* npc = get_item(party.get_elem(i));
if (npc && npc->add(obj)) {
break;
}
}
if (i == cnt) { // Failed? Force it on Avatar.
gwin->get_main_actor()->add(obj, true);
}
}
const Tile_coord t = vs->get_target_pos();
if (t.tx > 0 || t.ty > 0) {
gwin->teleport_party(
t, false, vs->get_target_map(),
num_parms > 1 ? parms[1].get_int_value() : false);
}
}
return no_ret;
}
USECODE_INTRINSIC(apply_damage) {
ignore_unused_variable_warning(num_parms);
// apply_damage(str, hps, type, obj);
Game_object* obj = get_item(parms[3]);
if (!obj) { // No valid target.
return Usecode_value(0);
}
const int base = parms[0].get_int_value();
const int hps = parms[1].get_int_value();
const int type = parms[2].get_int_value();
obj->apply_damage(nullptr, base, hps, type);
return Usecode_value(1);
}
USECODE_INTRINSIC(is_pc_inside) {
ignore_unused_variable_warning(num_parms, parms);
Usecode_value u(gwin->is_main_actor_inside());
return u;
}
USECODE_INTRINSIC(set_orrery) {
ignore_unused_variable_warning(num_parms);
// set_orrery(pos, state(0-9)).
/*
* This code is based on the Planets.txt document written
* by Marzo Sette Torres Junior.
*
* The table below contains the (x,y) offsets for each of the
* 8 planet frames in each possible state.
*/
static const short offsets[10][8][2] = {
/* S0 */ {
{2, -3},
{3, -3},
{1, -6},
{6, -2},
{7, -1},
{8, 1},
{-4, 8},
{9, -2} },
/* S1 */
{ {3, -1},
{4, -1},
{-5, -3},
{3, 6},
{7, 2},
{4, 7},
{-8, 4},
{8, 5} },
/* S2 */
{ {3, 1},
{3, 2},
{-3, 4},
{-5, 4},
{2, 7},
{-2, 8},
{-9, 1},
{2, 9} },
/* S3 */
{ {1, 3},
{1, 4},
{4, 3},
{-5, -3},
{-4, 6},
{-7, 4},
{-9, -1},
{-4, 9} },
/* S4 */
{ {-2, 3},
{-2, 4},
{5, -2},
{5, -4},
{-7, 2},
{-8, 1},
{-8, -4},
{-8, 6} },
/* S5 */
{ {-4, 1},
{-5, 1},
{-5, -3},
{6, 3},
{-7, -2},
{-7, -4},
{-7, -6},
{-10, 1} },
/* S6 */
{ {-4, 9},
{-5, -1},
{-3, 4},
{-3, 6},
{-6, -4},
{-5, -6},
{-7, -6},
{-10, -2}},
/* S7 */
{ {-4, 2},
{-4, -3},
{4, 3},
{-6, 1},
{-5, -5},
{-3, -7},
{-4, -8},
{-8, -6} },
/* S8 */
{{-3, -3},
{-3, -4},
{5, -2},
{-3, -5},
{-1, -7},
{0, -8},
{-1, -9},
{-5, -9} },
/* S9 */
{ {0, -4},
{0, -5},
{1, -6},
{1, -6},
{1, -7},
{1, -8},
{1, -9},
{-1, -10}}
};
const Tile_coord pos(
parms[0].get_elem(0).get_int_value(),
parms[0].get_elem(1).get_int_value(),
parms[0].get_elem(2).get_int_value());
const int state = parms[1].get_int_value();
// Find Planet Britania.
Game_object* brit = Game_object::find_closest(pos, 765, 24);
if (brit && state >= 0 && state <= 9) {
Game_object_vector planets; // Remove existing planets.
brit->find_nearby(planets, 988, 24, 0);
for (auto* p : planets) {
if (p->get_framenum() <= 7) { // Leave the sun.
p->remove_this();
}
}
for (int frame = 0; frame <= 7; ++frame) {
const Game_object_shared p = gmap->create_ireg_object(988, frame);
p->move(pos.tx + offsets[state][frame][0],
pos.ty + offsets[state][frame][1], pos.tz);
}
}
gwin->set_all_dirty();
return no_ret;
}
USECODE_INTRINSIC(get_timer) {
ignore_unused_variable_warning(num_parms);
const int tnum = parms[0].get_int_value();
int ret;
auto it = timers.find(tnum);
if (it != timers.end() && timers[tnum] > 0) {
ret = gclock->get_total_hours() - timers[tnum];
} else {
// Return random amount (up to half a day) if not set.
ret = rand() % 13;
}
return Usecode_value(ret);
}
USECODE_INTRINSIC(set_timer) {
ignore_unused_variable_warning(num_parms);
const int tnum = parms[0].get_int_value();
timers[tnum] = gclock->get_total_hours();
return no_ret;
}
USECODE_INTRINSIC(wearing_fellowship) {
ignore_unused_variable_warning(num_parms, parms);
Game_object* obj = gwin->get_main_actor()->get_readied(amulet);
if (obj && obj->get_shapenum() == 955 && obj->get_framenum() == 1) {
return Usecode_value(1);
} else {
return Usecode_value(0);
}
}
USECODE_INTRINSIC(mouse_exists) {
ignore_unused_variable_warning(num_parms, parms);
Usecode_value u(1);
return u;
}
USECODE_INTRINSIC(get_speech_track) {
ignore_unused_variable_warning(num_parms, parms);
// Get speech track set by 0x74 or 0x8f.
return Usecode_value(speech_track);
}
USECODE_INTRINSIC(flash_mouse) {
ignore_unused_variable_warning(num_parms);
// flash_mouse(code)
Mouse::Mouse_shapes shape;
switch (parms[0].need_int_value()) {
case 2:
shape = Mouse::outofrange;
break;
case 3:
shape = Mouse::outofammo;
break;
case 4:
shape = Mouse::tooheavy;
break;
case 5:
shape = Mouse::wontfit;
break;
case 7:
shape = Mouse::blocked;
break;
case 0:
case 1:
default:
shape = Mouse::redx;
break;
}
Mouse::mouse()->flash_shape(shape);
return no_ret;
}
USECODE_INTRINSIC(get_item_frame_rot) {
ignore_unused_variable_warning(num_parms);
// Same as get_item_frame, but (guessing!) include rotated bit.
Game_object* obj = get_item(parms[0]);
return Usecode_value(obj ? obj->get_framenum() : 0);
}
USECODE_INTRINSIC(set_item_frame_rot) {
ignore_unused_variable_warning(num_parms);
// Set entire frame, including rotated bit.
set_item_frame(get_item(parms[0]), parms[1].get_int_value(), 0, 1);
return no_ret;
}
USECODE_INTRINSIC(on_barge) {
ignore_unused_variable_warning(num_parms, parms);
// Only used once for BG, in usecode for magic-carpet.
// For SI, used for turtle.
// on_barge()
Barge_object* barge = Get_barge(gwin->get_main_actor());
if (barge) {
// See if party is on barge.
const TileRect foot = barge->get_tile_footprint();
Actor* party[9];
const int cnt = gwin->get_party(party, 1);
for (int i = 0; i < cnt; i++) {
Actor* act = party[i];
const Tile_coord t = act->get_tile();
if (!foot.has_world_point(t.tx, t.ty)) {
return Usecode_value(0);
}
}
// Force 'gather()' for turtle.
if (Game::get_game_type() == SERPENT_ISLE) {
barge->done();
}
return Usecode_value(1);
}
return Usecode_value(0);
// return Usecode_value(1);
}
USECODE_INTRINSIC(get_container) {
ignore_unused_variable_warning(num_parms);
// Takes itemref, returns container.
Game_object* obj = get_item(parms[0]);
Usecode_value u(static_cast<Game_object*>(nullptr));
if (obj) {
u = Usecode_value(obj->get_owner());
}
return u;
}
USECODE_INTRINSIC(remove_item) {
ignore_unused_variable_warning(num_parms);
// Think it's 'delete object'.
remove_item(get_item(parms[0]));
modified_map = true;
return no_ret;
}
USECODE_INTRINSIC(reduce_health) {
ignore_unused_variable_warning(num_parms);
// Reduce_health(obj, amount, type).
Game_object* obj = get_item(parms[0]);
const int type = parms[2].get_int_value();
if (obj) { // Dies if health goes too low.
obj->reduce_health(parms[1].get_int_value(), type);
}
return no_ret;
}
USECODE_INTRINSIC(is_readied) {
ignore_unused_variable_warning(num_parms);
// is_readied(npc, where, itemshape, frame (-359=any)).
// Where:
// 0=back,
// 1=weapon hand,
// 2=other hand,
// 3=belt,
// 4=neck,
// 5=torso,
// 6=one finger,
// 7=other finger,
// 8=quiver,
// 9=head,
// 10=legs,
// 11=feet
// 20=???
// Appears to be the same for BG and SI; SI's get_readied
// is far better in any case, and should be used instead.
Actor* npc = as_actor(get_item(parms[0]));
if (!npc) {
return Usecode_value(0);
}
const int where = parms[1].get_int_value();
const int shnum = parms[2].get_int_value();
const int frnum = parms[3].get_int_value();
// Spot defined in Actor class.
const int spot
= GAME_BG ? Ready_spot_from_BG(where) : Ready_spot_from_SI(where);
if (spot >= 0 && spot <= ucont) {
// See if it's the right one.
Game_object* obj = npc->get_readied(spot);
if (obj && obj->get_shapenum() == shnum
&& (frnum == c_any_framenum || obj->get_framenum() == frnum)) {
return Usecode_value(1);
}
} else if (spot < 0) {
cerr << "Readied: invalid spot #: " << spot << endl;
}
return Usecode_value(0);
}
USECODE_INTRINSIC(get_readied) {
ignore_unused_variable_warning(num_parms);
// get_readied(npc, where)
// Where:
// 0=other hand,
// 1=weapon hand,
// 2=cloak,
// 3=neck,
// 4=head,
// 5=gloves,
// 6=usecode container,
// 7=one finger,
// 8=other finger,
// 9=earrings,
// 10=quiver,
// 11=belt,
// 12=torso,
// 13=feet,
// 14=legs,
// 15=backpack,
// 16=back shield,
// 17=back spot
Actor* npc = as_actor(get_item(parms[0]));
if (!npc) {
return Usecode_value(0);
}
const int where = parms[1].get_int_value();
// Spot defined in Actor class.
const int spot
= GAME_BG ? Ready_spot_from_BG(where) : Ready_spot_from_SI(where);
if (spot >= 0 && spot <= ucont) {
return Usecode_value(npc->get_readied(spot));
} else if (spot < 0) {
cerr << "Readied: invalid spot #: " << spot << endl;
}
return Usecode_value(0);
}
USECODE_INTRINSIC(restart_game) {
ignore_unused_variable_warning(num_parms, parms);
// Think it's 'restart game'.
// Happens if you die before leaving trinsic.
Audio::get_ptr()->stop_music();
quitting_time = QUIT_TIME_RESTART; // Quit & restart.
return no_ret;
}
static int get_speech_face(int speech_track) {
// TODO: de-hard-code this.
if (!GAME_SI) {
return -1;
}
if (speech_track < 21) {
// Balance Serpent.
Actor* ava = Game_window::get_instance()->get_main_actor();
// Wearing serpent ring?
Game_object* obj = ava->get_readied(lfinger);
if (obj && obj->get_shapenum() == 0x377 && obj->get_framenum() == 1) {
// Solid.
return 295;
} else if (
(obj = ava->get_readied(rfinger)) != nullptr
&& obj->get_shapenum() == 0x377 && obj->get_framenum() == 1) {
// Solid.
return 295;
}
// Translucent.
return 300;
}
if (speech_track < 23) {
// Guardian.
return 296;
}
if (speech_track < 25) {
// Arcadion.
return 256;
}
if (speech_track == 25) {
// Chaos serpent.
return 293;
}
if (speech_track == 26) {
// Order serpent.
return 294;
}
return -1;
}
USECODE_INTRINSIC(start_speech) {
ignore_unused_variable_warning(num_parms);
// Start_speech(num). Also sets speech_track.
bool okay = false;
speech_track = parms[0].get_int_value();
if (speech_track >= 0) {
okay = Audio::get_ptr()->start_speech(speech_track);
}
if (!okay) {
// Failed? Clear faces. (Fixes SI).
init_conversation();
} else {
// Show guardian, serpent.
const int face = get_speech_face(speech_track);
if (face >= 0) {
Usecode_value sh(face);
Usecode_value fr(0);
show_npc_face(sh, fr);
int x;
int y; // Wait for click.
Get_click(x, y, Mouse::hand);
remove_npc_face(sh);
}
}
return Usecode_value(okay ? 1 : 0);
}
USECODE_INTRINSIC(start_blocking_speech) {
ignore_unused_variable_warning(num_parms);
// Start_speech(num). Also sets speech_track.
bool okay = false;
speech_track = parms[0].get_int_value();
if (speech_track >= 0) {
okay = Audio::get_ptr()->start_speech(speech_track);
}
if (!okay) {
// Failed? Clear faces. (Fixes SI).
init_conversation();
} else {
// Show guardian, serpent.
eman->remove_text_effects();
const int face = get_speech_face(speech_track);
Usecode_value sh(face);
if (face >= 0) {
Usecode_value fr(0);
show_npc_face(sh, fr);
}
const bool os = Mouse::mouse()->is_onscreen();
uint32 last_repaint = 0; // For insuring animation repaints.
do {
Delay(); // Wait a fraction of a second.
Mouse::mouse()->hide(); // Turn off mouse.
Mouse::mouse_update = false;
SDL_Renderer* renderer
= SDL_GetRenderer(gwin->get_win()->get_screen_window());
SDL_Event event;
while (SDL_PollEvent(&event)) {
SDL_ConvertEventToRenderCoordinates(renderer, &event);
if (event.type == SDL_EVENT_MOUSE_MOTION) {
// Mouse scale factor
int mx;
int my;
gwin->get_win()->screen_to_game(
event.motion.x, event.motion.y,
gwin->get_fastmouse(), mx, my);
Mouse::mouse()->move(mx, my);
Mouse::mouse_update = true;
}
}
// Get current time, & animate.
const uint32 ticks = SDL_GetTicks();
Game::set_ticks(ticks);
// Show animation every 1/20 sec.
if (ticks > last_repaint + 50 || gwin->was_painted()) {
gwin->paint_dirty();
while (ticks > last_repaint + 50) {
last_repaint += 50;
}
}
Mouse::mouse()->show(); // Re-display mouse.
// Blit to screen if necessary, or if mouse changed.
if (!gwin->show() && Mouse::mouse_update) {
Mouse::mouse()->blit_dirty();
}
} while (Audio::get_ptr()->is_voice_playing());
if (face >= 0) {
int x;
int y; // Wait for click.
Get_click(x, y, Mouse::hand);
remove_npc_face(sh);
}
if (!os) {
Mouse::mouse()->hide();
}
}
return Usecode_value(okay ? 1 : 0);
}
USECODE_INTRINSIC(is_water) {
ignore_unused_variable_warning(num_parms);
// Is_water(pos).
const size_t size = parms[0].get_array_size();
if (size >= 2 && size <= 4) {
if (size == 4) {
// Exult extention: if this is a [obj, x, y, z], check if the object
// (if any) has the flag water set.
auto* obj = get_item(parms[0].get_elem(0));
if (obj != nullptr) {
return Usecode_value(obj->get_info().is_water());
}
}
const int off = size == 4 ? 1 : 0;
// The original completely ignores the third coordinate.
const int xpos = parms[0].get_elem(0 + off).get_int_value();
const int ypos = parms[0].get_elem(1 + off).get_int_value();
const int x = (xpos - gwin->get_scrolltx()) * c_tilesize;
const int y = (ypos - gwin->get_scrollty()) * c_tilesize;
ShapeID sid = gwin->get_flat(x, y);
if (sid.is_invalid()) {
return Usecode_value(0);
}
const Shape_info& info = sid.get_info();
return Usecode_value(info.is_water());
}
return Usecode_value(0);
}
USECODE_INTRINSIC(run_endgame) {
ignore_unused_variable_warning(num_parms);
Audio::get_ptr()->stop_sound_effects();
game->end_game(parms[0].get_int_value() != 0, true);
// If successful enable menu entry and play credits afterwards
if (parms[0].get_int_value() != 0) {
U7open_out("<SAVEGAME>/endgame.flg");
game->show_credits();
}
quitting_time = QUIT_TIME_YES;
return no_ret;
}
USECODE_INTRINSIC(fire_projectile) {
ignore_unused_variable_warning(num_parms);
// fire_projectile(attacker, dir, missile, attval, wshape, ashape)
Game_object* attacker = get_item(parms[0]);
// Get direction (0-7).
const int dir = parms[1].get_int_value();
const int missile
= parms[2].get_int_value(); // Sprite to use for missile.
const int attval = parms[3].get_int_value(); // Attack value.
const int wshape
= parms[4].get_int_value(); // What to use for weapon info.
const int ashape
= parms[5].get_int_value(); // What to use for ammo info.
const Tile_coord pos = attacker->get_missile_tile(dir);
const Tile_coord adj = pos.get_neighbor(dir % 8);
// Make it go dist tiles.
const int dx = adj.tx - pos.tx;
const int dy = adj.ty - pos.ty;
Tile_coord dest = pos;
const int dist = 31;
dest.tx += dist * dx;
dest.ty += dist * dy;
// Fire missile.
gwin->get_effects()->add_effect(std::make_unique<Projectile_effect>(
attacker, dest, wshape, ashape, missile, attval, 4));
return no_ret;
}
USECODE_INTRINSIC(nap_time) {
ignore_unused_variable_warning(num_parms);
// nap_time(bed)
Game_object* bed = get_item(parms[0]);
if (!bed) {
return no_ret;
}
// See if bed is occupied by an NPC.
if (Sleep_schedule::is_bed_occupied(bed, gwin->get_main_actor())) {
// Show party member's face.
const int party_cnt = partyman->get_count();
const int npcnum
= party_cnt ? partyman->get_member(rand() % party_cnt) : 356;
Usecode_value actval(-npcnum);
Usecode_value frval(0);
show_npc_face(actval, frval);
conv->show_npc_message(
get_text_msg(first_bed_occupied + rand() % num_bed_occupied));
remove_npc_face(actval);
gwin->get_main_actor()->set_schedule_type(Schedule::follow_avatar);
return no_ret;
}
Schedule* sched = gwin->get_main_actor()->get_schedule();
if (sched) { // Tell (sleep) sched. to use bed.
sched->set_bed(bed);
}
return no_ret;
}
USECODE_INTRINSIC(advance_time) {
ignore_unused_variable_warning(num_parms);
// Incr. clock by (parm[0]*.04min.).
gclock->increment(parms[0].get_int_value() / ticks_per_minute);
return no_ret;
}
USECODE_INTRINSIC(in_usecode) {
ignore_unused_variable_warning(num_parms);
// in_usecode(item): Return 1 if executing usecode on parms[0].
Game_object* obj = get_item(parms[0]);
if (!obj) {
return Usecode_value(0);
}
return Usecode_value(Usecode_script::find(obj) != nullptr);
}
USECODE_INTRINSIC(call_guards) {
ignore_unused_variable_warning(num_parms, parms);
// Attack thieving Avatar.
gwin->call_guards();
return no_ret;
}
USECODE_INTRINSIC(stop_arresting) {
ignore_unused_variable_warning(num_parms, parms);
// Seems to be what it does.
gwin->stop_arresting();
return no_ret;
}
USECODE_INTRINSIC(attack_avatar) {
ignore_unused_variable_warning(num_parms, parms);
// Attack thieving Avatar.
gwin->attack_avatar();
return no_ret;
}
USECODE_INTRINSIC(path_run_usecode) {
// exec(loc(x,y,z)?, usecode#, itemref, eventid).
// Think it should have Avatar walk path to loc, return 0
// if he can't get there (and return), 1 if he can.
Usecode_value ava(gwin->get_main_actor());
const bool simode = num_parms > 4 ? parms[4].get_int_value() != 0 : GAME_SI;
return Usecode_value(path_run_usecode(
ava, parms[0], parms[1], parms[2], parms[3],
// SI: Look for free spot. (Guess).
simode, false,
true)); // Bring companions.
}
USECODE_INTRINSIC(close_gump) {
ignore_unused_variable_warning(num_parms);
// close_gump(container)
if (!gwin->is_dragging()) { // NOT while dragging stuff.
Game_object* obj = get_item(parms[0]);
Gump* gump = gumpman->find_gump(obj, c_any_shapenum);
if (gump) {
gumpman->close_gump(gump);
gwin->set_all_dirty();
}
}
return no_ret;
}
USECODE_INTRINSIC(close_gump2) {
ignore_unused_variable_warning(num_parms);
// close_gump(container)
Game_object* obj = get_item(parms[0]);
Gump* gump = gumpman->find_gump(obj, c_any_shapenum);
if (gump) {
gumpman->close_gump(gump);
gwin->set_all_dirty();
}
return no_ret;
}
USECODE_INTRINSIC(close_gumps) {
ignore_unused_variable_warning(num_parms, parms);
if (!gwin->is_dragging()) { // NOT while dragging stuff.
gumpman->close_all_gumps();
}
return no_ret;
}
USECODE_INTRINSIC(close_gumps2) {
ignore_unused_variable_warning(num_parms, parms);
gumpman->close_all_gumps();
return no_ret;
}
USECODE_INTRINSIC(in_gump_mode) {
ignore_unused_variable_warning(num_parms, parms);
// No persistent
return Usecode_value(gumpman->showing_gumps(true));
}
USECODE_INTRINSIC(is_not_blocked) {
ignore_unused_variable_warning(num_parms);
// Is_not_blocked(tile, shape, frame (or -359).
Usecode_value fail(0);
// Parm. 0 should be tile coords.
Usecode_value& pval = parms[0];
if (pval.get_array_size() < 3) {
return fail;
}
const Tile_coord tile(
pval.get_elem(0).get_int_value(), pval.get_elem(1).get_int_value(),
pval.get_elem(2).get_int_value());
const int shapenum = parms[1].get_int_value();
const int framenum = parms[2].get_int_value();
// Find out about given shape.
const Shape_info& info = ShapeID::get_info(shapenum);
const TileRect footprint(
tile.tx - info.get_3d_xtiles(framenum) + 1,
tile.ty - info.get_3d_ytiles(framenum) + 1,
info.get_3d_xtiles(framenum), info.get_3d_ytiles(framenum));
int new_lift;
const bool blocked = Map_chunk::is_blocked(
info.get_3d_height(), tile.tz, footprint.x, footprint.y,
footprint.w, footprint.h, new_lift, MOVE_ALL_TERRAIN, 1);
// Okay?
if (!blocked && new_lift == tile.tz) {
return Usecode_value(1);
} else {
return Usecode_value(0);
}
}
USECODE_INTRINSIC(direction_from) {
ignore_unused_variable_warning(num_parms);
// ?Direction from parm[0] -> parm[1].
// Rets. 0-7, with 0 = North, 1 = Northeast, etc.
// Same as 0x1a??
Usecode_value u = find_direction(parms[0], parms[1]);
return u;
}
/*
* Test for a 'moving barge' flag.
*/
static bool Is_moving_barge_flag(int fnum) {
if (Game::get_game_type() == BLACK_GATE) {
return fnum == static_cast<int>(Obj_flags::on_moving_barge)
|| fnum == static_cast<int>(Obj_flags::active_barge);
} else { // SI.
return fnum == static_cast<int>(Obj_flags::si_on_moving_barge) ||
// Ice raft needs this one:
fnum == static_cast<int>(Obj_flags::on_moving_barge)
|| fnum == static_cast<int>(Obj_flags::active_barge);
}
}
USECODE_INTRINSIC(get_item_flag) {
ignore_unused_variable_warning(num_parms);
// Get npc flag(item, flag#).
Game_object* obj = get_item(parms[0]);
if (!obj) {
return Usecode_value(0);
}
const int fnum = parms[1].get_int_value();
// Special cases:
if (Is_moving_barge_flag(fnum)) {
// Test for moving barge.
Barge_object* barge;
if (!gwin->get_moving_barge() || !(barge = Get_barge(obj))) {
return Usecode_value(0);
}
return Usecode_value(barge == gwin->get_moving_barge());
} else if (fnum == static_cast<int>(Obj_flags::okay_to_land)) {
// Okay to land flying carpet?
Barge_object* barge = Get_barge(obj);
if (!barge) {
return Usecode_value(0);
}
return Usecode_value(barge->okay_to_land());
} else if (fnum == static_cast<int>(Obj_flags::immunities)) {
const Actor* npc = obj->as_actor();
const Monster_info* inf = obj->get_info().get_monster_info();
return Usecode_value(
(inf != nullptr && inf->power_safe())
|| (npc && npc->check_gear_powers(Frame_flags::power_safe)));
} else if (fnum == static_cast<int>(Obj_flags::cant_die)) {
const Actor* npc = obj->as_actor();
const Monster_info* inf = obj->get_info().get_monster_info();
return Usecode_value(
(inf != nullptr && inf->death_safe())
|| (npc && npc->check_gear_powers(Frame_flags::death_safe)));
} else if (fnum == Obj_flags::is_solid) {
// Verified. The previous version worked well because of a bug in both
// BG and SI gang-planck usecode, which checked the flag on the wrong
// object. Also, no non-solid object is in a position where it could
// block the gang-planck.
return Usecode_value(obj->get_info().is_solid());
} else if (fnum == static_cast<int>(Obj_flags::in_dungeon)) {
return Usecode_value(
obj == gwin->get_main_actor() && gwin->is_in_dungeon());
} else if (fnum == Obj_flags::active_sailor) {
// Must be the sailor, as this is used to check for Ferryman.
return Usecode_value(sailor);
}
Usecode_value u(obj->get_flag(fnum));
return u;
}
USECODE_INTRINSIC(set_item_flag) {
ignore_unused_variable_warning(num_parms);
// Set npc flag(item, flag#).
Game_object* obj = get_item(parms[0]);
const int flag = parms[1].get_int_value();
if (!obj) {
return no_ret;
}
switch (flag) {
case Obj_flags::dont_move:
case Obj_flags::bg_dont_move:
obj->set_flag(flag);
// Get out of combat mode.
if (obj == gwin->get_main_actor()) {
if (gwin->in_combat()) {
gwin->toggle_combat();
}
if (touchui != nullptr) {
touchui->hideGameControls();
}
if (Face_stats::Visible()) {
Face_stats::HideGump();
}
if (ShortcutBar_gump::Visible()) {
ShortcutBar_gump::HideGump();
}
}
// Show change in status.
gwin->set_all_dirty();
break;
case Obj_flags::charmed: {
obj->set_flag(flag);
Actor* npc = obj->as_actor();
if (npc) {
npc->set_effective_alignment(Actor::good); // Verified.
}
break;
}
case Obj_flags::invisible:
obj->set_flag(flag);
gwin->add_dirty(obj);
break;
case Obj_flags::active_sailor:
// The sailor (Ferryman or sails).
sailor = obj;
break;
default:
obj->set_flag(flag);
if (Is_moving_barge_flag(flag)) {
// Set barge in motion.
Barge_object* barge = Get_barge(obj);
if (barge) {
gwin->set_moving_barge(barge);
}
}
break;
}
return no_ret;
}
USECODE_INTRINSIC(clear_item_flag) {
ignore_unused_variable_warning(num_parms);
// Clear npc flag(item, flag#).
Game_object* obj = get_item(parms[0]);
const int flag = parms[1].get_int_value();
if (obj) {
Actor* npc = obj->as_actor();
if (flag != Obj_flags::asleep || !npc || !npc->is_knocked_out()) {
obj->clear_flag(flag);
}
if (flag == Obj_flags::dont_move || flag == Obj_flags::bg_dont_move) {
// Show change in status.
show_pending_text(); // Fixes Lydia-tatoo.
if (obj == gwin->get_main_actor()) {
if (touchui != nullptr) {
touchui->showGameControls();
}
if (!Face_stats::Visible()) {
Face_stats::ShowGump();
}
if (!ShortcutBar_gump::Visible()) {
ShortcutBar_gump::ShowGump();
}
}
gwin->set_all_dirty();
} else if (Is_moving_barge_flag(flag)) {
// Stop barge object is on or part of.
Barge_object* barge = Get_barge(obj);
if (barge && barge == gwin->get_moving_barge()) {
gwin->set_moving_barge(nullptr);
}
} else if (flag == Obj_flags::active_sailor) {
// Handles Ferryman and sails
sailor = nullptr;
}
}
return no_ret;
}
USECODE_INTRINSIC(set_path_failure) {
ignore_unused_variable_warning(num_parms);
// set_path_failure(fun, itemref, eventid) for the last NPC in
// a path_run_usecode() call.
const int fun = parms[0].get_int_value();
const int eventid = parms[2].get_int_value();
Game_object* item = get_item(parms[1]);
if (path_npc && item) { // Set in path_run_usecode().
If_else_path_actor_action* action
= path_npc->get_action()
? path_npc->get_action()->as_usecode_path()
: nullptr;
if (action) { // Set in in path action.
action->set_failure(new Usecode_actor_action(fun, item, eventid));
}
}
return no_ret;
}
USECODE_INTRINSIC(fade_palette) {
ignore_unused_variable_warning(num_parms);
// Fade(cycles?, ??(always 1), in_out (0=fade to black, 1=fade in)).
const int cycles = parms[0].get_int_value();
const int inout = parms[2].get_int_value();
if (inout == 0) {
show_pending_text(); // Make sure prev. text was seen.
} else {
gclock->reset_palette();
}
gwin->get_pal()->fade(cycles, inout);
if (inout == 0) {
gwin->toggle_ambient_light(false);
}
return no_ret;
}
USECODE_INTRINSIC(fade_palette_sleep) {
ignore_unused_variable_warning(num_parms);
// Fade(cycles?, ??(always 1), in_out (0=fade to black, 1=fade in)).
const int cycles = parms[0].get_int_value();
const int inout = parms[2].get_int_value();
if (inout == 0) {
show_pending_text(); // Make sure prev. text was seen.
Audio::get_ptr()->start_music(Audio::game_music(33));
} else {
Audio::get_ptr()->start_music(Audio::game_music(31));
gclock->reset_palette();
}
gwin->get_pal()->fade(cycles, inout);
return no_ret;
}
USECODE_INTRINSIC(get_party_list2) {
ignore_unused_variable_warning(num_parms, parms);
// Return party. Same as 0x23
// Probably returns a list of everyone with (or without) some flag
// List of live chars? Dead chars?
Usecode_value u(get_party());
return u;
}
USECODE_INTRINSIC(set_camera) {
ignore_unused_variable_warning(num_parms);
// Set_camera(actor)
gumpman->close_all_gumps();
Actor* actor = as_actor(get_item(parms[0]));
if (actor) {
gwin->set_camera_actor(actor);
activate_cached(actor->get_tile()); // Mar-10-01 - For Test of Love.
} else {
Game_object* obj = get_item(parms[0]);
if (obj) {
const Tile_coord t = obj->get_tile();
gwin->center_view(t);
activate_cached(t); // Mar-10-01 - For Test of Love.
}
}
return no_ret;
}
USECODE_INTRINSIC(in_combat) {
ignore_unused_variable_warning(num_parms, parms);
// Are we in combat mode?
return Usecode_value(gwin->in_combat());
}
USECODE_INTRINSIC(center_view) {
ignore_unused_variable_warning(num_parms);
// Center view around given item.
Game_object* obj = get_item(parms[0]);
if (obj) {
const Tile_coord t = obj->get_tile();
gwin->center_view(t);
activate_cached(t); // Mar-10-01 - For Test of Love.
}
return no_ret;
}
USECODE_INTRINSIC(view_tile) {
ignore_unused_variable_warning(num_parms);
// Center view around given item.
Tile_coord t;
if (!parms[0].is_array() || parms[0].get_array_size() < 2) {
return no_ret;
} else {
t = Tile_coord(
parms[0].get_elem(0).get_int_value(),
parms[0].get_elem(1).get_int_value(), 0);
}
gwin->center_view(t);
return no_ret;
}
USECODE_INTRINSIC(get_dead_party) {
ignore_unused_variable_warning(num_parms);
// Return list of dead companions' bodies.
Game_object* obj = get_item(parms[0]);
if (!obj) {
return no_ret;
}
const int cnt = partyman->get_dead_count();
Usecode_value ret(cnt, nullptr);
for (int i = 0; i < cnt; i++) {
Game_object* body = gwin->get_body(partyman->get_dead_member(i));
// Body within 50 tiles (a guess)?
if (body && body->distance(obj) < 50) {
Usecode_value v(body);
ret.put_elem(i, v);
}
}
return ret;
}
USECODE_INTRINSIC(play_sound_effect) {
if (num_parms < 1) {
return no_ret;
}
// Play music(isongnum).
COUT("Sound effect " << parms[0].get_int_value() << " request in usecode");
Audio::get_ptr()->play_sound_effect(parms[0].get_int_value());
return no_ret;
}
USECODE_INTRINSIC(play_sound_effect2) {
if (num_parms < 2) {
return no_ret;
}
// Play music(songnum, item).
Game_object* obj = get_item(parms[1]);
Object_sfx::Play(obj, parms[0].get_int_value(), 0);
#ifdef DEBUG
cout << "Sound effect(2) " << parms[0].get_int_value()
<< " request in usecode" << endl;
#endif
return no_ret;
}
USECODE_INTRINSIC(play_scene) {
if (num_parms < 1) {
return no_ret;
}
const char* scene_name_str = parms[0].get_str_value();
if (!scene_name_str) {
return no_ret;
}
// Optional fade_out and fade_in parameters (default: true)
bool fade_out = num_parms > 1 ? parms[1].get_int_value() != 0 : true;
bool fade_in = num_parms > 2 ? parms[2].get_int_value() != 0 : true;
std::string scene_name(scene_name_str);
if (scene_available(scene_name)) {
// Pause the queue.
gwin->get_tqueue()->pause(Game::get_ticks());
if (fade_out) {
gwin->get_pal()->fade_out(c_fade_out_time);
}
play_scene(scene_name);
gwin->set_all_dirty();
gwin->paint();
if (fade_in) {
gwin->get_pal()->fade_in(c_fade_in_time);
} else {
gwin->get_pal()->fade_in(0);
}
// Resume the queue.
gwin->get_tqueue()->resume(Game::get_ticks());
}
return no_ret;
}
USECODE_INTRINSIC(get_npc_id) {
ignore_unused_variable_warning(num_parms);
Actor* actor = as_actor(get_item(parms[0]));
if (!actor) {
return Usecode_value(0);
}
return Usecode_value(actor->get_ident());
}
USECODE_INTRINSIC(set_npc_id) {
ignore_unused_variable_warning(num_parms);
Actor* actor = as_actor(get_item(parms[0]));
if (actor) {
actor->set_ident(parms[1].get_int_value());
}
return no_ret;
}
USECODE_INTRINSIC(add_cont_items) {
ignore_unused_variable_warning(num_parms);
// Add items(num, item, ??quality?? (-359), frame (or -359), T/F).
return add_cont_items(
parms[0], parms[1], parms[2], parms[3], parms[4], parms[5]);
}
// Is this SI Only
USECODE_INTRINSIC(remove_cont_items) {
ignore_unused_variable_warning(num_parms);
// Add items(num, item, ??quality?? (-359), frame (or -359), T/F).
return remove_cont_items(
parms[0], parms[1], parms[2], parms[3], parms[4], parms[5]);
}
/*
* SI-specific functions.
*/
USECODE_INTRINSIC(show_npc_face0) {
ignore_unused_variable_warning(num_parms);
// Show_npc_face0(npc, frame). Show in position 0.
show_npc_face(parms[0], parms[1], 0);
return no_ret;
}
USECODE_INTRINSIC(show_npc_face1) {
ignore_unused_variable_warning(num_parms);
// Show_npc_face1(npc, frame). Show in position 1.
show_npc_face(parms[0], parms[1], 1);
return no_ret;
}
USECODE_INTRINSIC(remove_npc_face0) {
ignore_unused_variable_warning(num_parms, parms);
show_pending_text();
conv->remove_slot_face(0);
return no_ret;
}
USECODE_INTRINSIC(remove_npc_face1) {
ignore_unused_variable_warning(num_parms, parms);
show_pending_text();
conv->remove_slot_face(1);
return no_ret;
}
USECODE_INTRINSIC(change_npc_face0) {
ignore_unused_variable_warning(num_parms);
show_pending_text();
conv->change_face_frame(parms[0].get_int_value(), 0);
return no_ret;
}
USECODE_INTRINSIC(change_npc_face1) {
ignore_unused_variable_warning(num_parms);
show_pending_text();
conv->change_face_frame(parms[0].get_int_value(), 1);
return no_ret;
}
USECODE_INTRINSIC(reset_conv_face) {
// Seems to be right.
ignore_unused_variable_warning(num_parms, parms);
show_pending_text();
conv->change_face_frame(0, 0);
return no_ret;
}
USECODE_INTRINSIC(set_conversation_slot) {
ignore_unused_variable_warning(num_parms);
// set_conversation_slot(0 or 1) - Choose which face is talking.
conv->set_slot(parms[0].get_int_value());
return no_ret;
}
USECODE_INTRINSIC(init_conversation) {
ignore_unused_variable_warning(num_parms, parms);
init_conversation();
return no_ret;
}
USECODE_INTRINSIC(end_conversation) {
ignore_unused_variable_warning(num_parms, parms);
show_pending_text(); // Wait for click if needed.
conv->init_faces(); // Removes faces from screen.
gwin->set_all_dirty();
return no_ret;
}
USECODE_INTRINSIC(si_path_run_usecode) {
ignore_unused_variable_warning(num_parms);
// exec(npc, loc(x,y,z), eventid, itemref, usecode#, flag_always).
// Schedule Npc to walk to loc and then execute usecode.
const int always = parms[5].get_int_value();
path_run_usecode(
parms[0], parms[1], parms[4], parms[3], parms[2], true,
always != 0);
return no_ret;
}
USECODE_INTRINSIC(sib_path_run_usecode) {
ignore_unused_variable_warning(num_parms);
// exec(npc, loc(x,y,z), usecode#, itemref, eventid).
// Schedule Npc to walk to loc and then execute usecode.
return Usecode_value(path_run_usecode(
parms[0], parms[1], parms[2], parms[3], parms[4], false, false));
}
USECODE_INTRINSIC(error_message) {
// exec(array)
// Output everything to stdout
for (int i = 0; i < num_parms; i++) {
if (parms[i].is_int()) {
std::cout << parms[i].get_int_value();
} else if (parms[i].is_ptr()) {
std::cout << parms[i].get_ptr_value();
} else if (!parms[i].is_array()) {
std::cout << parms[i].get_str_value();
} else {
for (size_t j = 0; j < parms[i].get_array_size(); j++) {
if (parms[i].get_elem(j).is_int()) {
std::cout << parms[i].get_elem(j).get_int_value();
} else if (parms[i].get_elem(j).is_ptr()) {
std::cout << parms[i].get_elem(j).get_ptr_value();
} else if (!parms[i].get_elem(j).is_array()) {
std::cout << parms[i].get_elem(j).get_str_value();
}
}
}
}
std::cout << std::endl;
return no_ret;
}
USECODE_INTRINSIC(set_polymorph) {
ignore_unused_variable_warning(num_parms);
// exec(npc, shape).
// Npc's shape is change to shape.
Actor* actor = as_actor(get_item(parms[0]));
if (actor) {
actor->set_polymorph(parms[1].get_int_value());
}
return no_ret;
}
USECODE_INTRINSIC(set_new_schedules) {
ignore_unused_variable_warning(num_parms);
// set_new_schedules ( npc, time, activity, [x, y] )
//
// or
//
// set_new_schedules ( npc, [ time1, time2, ...],
// [activity1, activity2, ...],
// [x1,y1, x2, y2, ...] )
//
Actor* actor = as_actor(get_item(parms[0]));
// If no actor return
if (!actor) {
return no_ret;
}
const int count = parms[1].is_array() ? parms[1].get_array_size() : 1;
auto* list = new Schedule_change[count];
if (!parms[1].is_array()) {
const int time = parms[1].get_int_value();
const int sched = parms[2].get_int_value();
const int tx = parms[3].get_elem(0).get_int_value();
const int ty = parms[3].get_elem(1).get_int_value();
list[0].set(tx, ty, 0, sched, time);
} else {
for (int i = 0; i < count; i++) {
const int time = parms[1].get_elem(i).get_int_value();
const int sched = parms[2].get_elem(i).get_int_value();
const int tx = parms[3].get_elem(i * 2).get_int_value();
const int ty = parms[3].get_elem(i * 2 + 1).get_int_value();
list[i].set(tx, ty, 0, sched, time);
}
}
actor->set_schedules(list, count);
return no_ret;
}
USECODE_INTRINSIC(revert_schedule) {
ignore_unused_variable_warning(num_parms);
// revert_schedule(npc)
// Reverts the schedule of the npc to the saved state in
// <STATIC>/schedule.dat
Actor* actor = as_actor(get_item(parms[0]));
if (actor) {
gwin->revert_schedules(actor);
}
return no_ret;
}
USECODE_INTRINSIC(run_schedule) {
ignore_unused_variable_warning(num_parms);
// run_schedule(npc)
// I think this is actually reset activity to current
// scheduled activity - Colourless
Actor* actor = as_actor(get_item(parms[0]));
if (actor) {
actor->update_schedule(gclock->get_hour() / 3);
}
return no_ret;
}
USECODE_INTRINSIC(modify_schedule) {
ignore_unused_variable_warning(num_parms);
// modify_schedule ( npc, time, activity, [x, y] )
Actor* actor = as_actor(get_item(parms[0]));
// If no actor return
if (!actor) {
return no_ret;
}
const int time = parms[1].get_int_value();
const int sched = parms[2].get_int_value();
const int tx = parms[3].get_elem(0).get_int_value();
const int ty = parms[3].get_elem(1).get_int_value();
actor->set_schedule_time_type(time, sched);
actor->set_schedule_time_location(time, tx, ty);
return no_ret;
}
USECODE_INTRINSIC(get_temperature) {
ignore_unused_variable_warning(num_parms);
Actor* npc = as_actor(get_item(parms[0]));
return Usecode_value(npc ? npc->get_temperature() : 0);
}
USECODE_INTRINSIC(set_temperature) {
ignore_unused_variable_warning(num_parms);
// set_temperature(npc, value (0-63)).
Actor* npc = as_actor(get_item(parms[0]));
if (npc) {
npc->set_temperature(parms[1].get_int_value());
}
return no_ret;
}
USECODE_INTRINSIC(get_temperature_zone) {
ignore_unused_variable_warning(num_parms);
// get_temperature_zone(npc).
Actor* npc = as_actor(get_item(parms[0]));
if (npc) {
return Usecode_value(npc->get_temperature_zone());
}
return Usecode_value(0);
}
USECODE_INTRINSIC(get_npc_warmth) {
ignore_unused_variable_warning(num_parms);
// get_npc_warmth(npc).
Actor* npc = as_actor(get_item(parms[0]));
if (npc) {
return Usecode_value(npc->figure_warmth());
}
return Usecode_value(-75);
}
#if 0 /* +++++Not used at the moment. */
USECODE_INTRINSIC(add_removed_npc) {
// move_offscreen(npc, x, y) - I think (seems good) I think
//
// returns false if not moved
// else, moves the object to the closest position off
// Actor we want to move
Actor *actor = as_actor(get_item(parms[0]));
// Need to check superchunk
int cx = actor->get_cx();
int cy = actor->get_cx();
int scx = cx / c_chunks_per_schunk;
int scy = cy / c_chunks_per_schunk;
int scx2 = parms[1].get_int_value() / c_tiles_per_schunk;
int scy2 = parms[2].get_int_value() / c_tiles_per_schunk;
// Are the coords are good
if ((cx == 0xff && scx2) || (cx != 0xff && scx != scx2) ||
(cy == 0xff && scy2) || (cy != 0xff && scy != scy2))
return Usecode_value(false);
// Ok they were good, now move it
// Get the tiles around the edge of the screen
TileRect rect = gwin->get_win_tile_rect();
int sx = rect.x; // Tile coord of x start
int ex = rect.x + rect.w; // Tile coord of x end
int sy = rect.y; // y start
int ey = rect.y + rect.h; // x end
// The height of the Actor we are checking
int height = actor->get_info().get_3d_height();
int i = 0, nlift = 0;
int tx, ty;
// Avatars coords
Tile_coord av = gwin->get_main_actor()->get_tile();;
Tile_coord close; // The tile coords of the closest tile
int dist = -1; // The distance
cy = sy / c_tiles_per_chunk;
ty = sy % c_tiles_per_chunk;
cout << "1" << endl;
for (i = 0; i < rect.w; i++) {
cx = (sx + i) / c_tiles_per_chunk;
tx = (sx + i) % c_tiles_per_chunk;
Map_chunk *clist = gmap->get_chunk_safely(cx, cy);
if (!clist) continue;
clist->setup_cache();
if (!clist->is_blocked(height, 0, tx, ty, nlift, actor->get_type_flags(), 1)) {
Tile_coord cur(tx + cx * c_tiles_per_chunk, ty + cy * c_tiles_per_chunk, nlift);
if (cur.distance(av) < dist || dist == -1) {
dist = cur.distance(av);
cout << "(" << cur.tx << ", " << cur.ty << ") " << dist << endl;
close = cur;
}
}
}
cx = ex / c_tiles_per_chunk;
tx = ex % c_tiles_per_chunk;
cout << "2" << endl;
for (i = 0; i < rect.h; i++) {
cy = (sy + i) / c_tiles_per_chunk;
ty = (sy + i) % c_tiles_per_chunk;
Map_chunk *clist = gmap->get_chunk_safely(cx, cy);
if (!clist) continue;
clist->setup_cache();
if (!clist->is_blocked(height, 0, tx, ty, nlift, actor->get_type_flags(), 1)) {
Tile_coord cur(tx + cx * c_tiles_per_chunk, ty + cy * c_tiles_per_chunk, nlift);
if (cur.distance(av) < dist || dist == -1) {
dist = cur.distance(av);
cout << "(" << cur.tx << ", " << cur.ty << ") " << dist << endl;
close = cur;
}
}
}
cy = ey / c_tiles_per_chunk;
ty = ey % c_tiles_per_chunk;
cout << "3" << endl;
for (i = 0; i < rect.w; i++) {
cx = (ex - i) / c_tiles_per_chunk;
tx = (ex - i) % c_tiles_per_chunk;
Map_chunk *clist = gmap->get_chunk_safely(cx, cy);
if (!clist) continue;
clist->setup_cache();
if (!clist->is_blocked(height, 0, tx, ty, nlift, actor->get_type_flags(), 1)) {
Tile_coord cur(tx + cx * c_tiles_per_chunk, ty + cy * c_tiles_per_chunk, nlift);
if (cur.distance(av) < dist || dist == -1) {
dist = cur.distance(av);
cout << "(" << cur.tx << ", " << cur.ty << ") " << dist << endl;
close = cur;
}
}
}
cx = sx / c_tiles_per_chunk;
tx = sx % c_tiles_per_chunk;
cout << "4" << endl;
for (i = 0; i < rect.h; i++) {
cy = (ey - i) / c_tiles_per_chunk;
ty = (ey - i) % c_tiles_per_chunk;
Map_chunk *clist = gmap->get_chunk_safely(cx, cy);
if (!clist) continue;
clist->setup_cache();
if (!clist->is_blocked(height, 0, tx, ty, nlift, actor->get_type_flags(), 1)) {
Tile_coord cur(tx + cx * c_tiles_per_chunk, ty + cy * c_tiles_per_chunk, nlift);
if (cur.distance(av) < dist || dist == -1) {
dist = cur.distance(av);
cout << "(" << cur.tx << ", " << cur.ty << ") " << dist << endl;
close = cur;
}
}
}
if (dist != -1) {
actor->move(close);
return Usecode_value(true);
}
return Usecode_value(false);
}
#endif
USECODE_INTRINSIC(approach_avatar) {
ignore_unused_variable_warning(num_parms);
// Approach_avatar(npc, ?, ?).
// In the original, this intrinsic seems to create 'npc' off-screen, while
// it approaches the avatar due to si_path_run_usecode or the 'TALK'
// schedule. Need to investigate this further. Actor we want to move
Actor* actor = as_actor(get_item(parms[0]));
if (!actor || actor->is_dead()) {
return Usecode_value(0);
}
// Guessing!! If already close...
if (actor->distance(gwin->get_main_actor()) < 10) {
return Usecode_value(1);
}
// Approach, and wait.
if (!actor->approach_another(gwin->get_main_actor(), true)) {
return Usecode_value(0);
}
return Usecode_value(1);
}
USECODE_INTRINSIC(set_barge_dir) {
ignore_unused_variable_warning(num_parms);
// set_barge_dir(barge, dir (0-7)).
Game_object* obj = get_item(parms[0]);
const int dir = parms[1].get_int_value();
Barge_object* barge = obj ? obj->as_barge() : nullptr;
if (barge) {
barge->face_direction(dir);
}
return no_ret;
}
USECODE_INTRINSIC(telekenesis) {
ignore_unused_variable_warning(num_parms);
// telekenesis(fun#) - Save item for executing Usecode on.
telekenesis_fun = parms[0].get_int_value();
return no_ret;
}
USECODE_INTRINSIC(a_or_an) {
ignore_unused_variable_warning(num_parms);
// a_or_an (word)
// return a/an depending on 'word'
const char* str = parms[0].get_str_value();
if (str && strchr("aeiouyAEIOUY", str[0]) == nullptr) {
return Usecode_value("a");
} else {
return Usecode_value("an");
}
}
USECODE_INTRINSIC(remove_from_area) {
ignore_unused_variable_warning(num_parms);
// Remove_from_area(shapenum, framenum, [x,y]from, [x,y]to).
const int shnum = parms[0].get_int_value();
const int frnum = parms[1].get_int_value();
const int fromx = parms[2].get_elem(0).get_int_value();
const int fromy = parms[2].get_elem(1).get_int_value();
const int tox = parms[3].get_elem(0).get_int_value();
const int toy = parms[3].get_elem(1).get_int_value();
const TileRect area(fromx, fromy, tox - fromx + 1, toy - fromy + 1);
if (area.w <= 0 || area.h <= 0) {
return no_ret;
}
Game_object_vector vec; // Find objects.
Map_chunk::find_in_area(vec, area, shnum, frnum);
// Remove them.
for (auto* obj : vec) {
gwin->add_dirty(obj);
obj->remove_this();
}
return no_ret;
}
USECODE_INTRINSIC(set_light) {
ignore_unused_variable_warning(num_parms);
// set_light(npc, onoff)
Game_object* light = get_item(parms[0]);
if (!light) {
return no_ret;
}
Actor* npc = as_actor(light->get_outermost());
if (npc) {
// This counts the light sources now too. This matches the originals;
// torches and other light sources need it to be done this way, and
// the other "obvious" manners fail.
npc->refigure_gear();
if (!parms[1].get_int_value()) {
npc->remove_light_source(light);
}
}
return no_ret;
}
USECODE_INTRINSIC(set_time_palette) {
ignore_unused_variable_warning(num_parms, parms);
// set_time_palette()
gclock->reset_palette();
return no_ret;
}
USECODE_INTRINSIC(ambient_light) {
ignore_unused_variable_warning(num_parms);
// ambient_light(onoff)
// E.g., the cutscene with Batlin and Cantra.
gwin->toggle_ambient_light(parms[0].get_int_value() == 0);
gclock->set_palette();
return no_ret;
}
USECODE_INTRINSIC(infravision) {
ignore_unused_variable_warning(num_parms);
// infravision(npc, onoff)
Actor* npc = as_actor(get_item(parms[0]));
if (npc && npc->is_in_party()) {
gwin->toggle_infravision(parms[1].get_int_value() != 0);
gclock->set_palette();
}
return no_ret;
}
// parms[0] = quality of key to be added
USECODE_INTRINSIC(add_to_keyring) {
ignore_unused_variable_warning(num_parms);
getKeyring()->addkey(parms[0].get_int_value());
return no_ret;
}
// parms[0] = quality of key to check
// returns true if key is on keyring
USECODE_INTRINSIC(is_on_keyring) {
ignore_unused_variable_warning(num_parms);
if (getKeyring()->checkkey(parms[0].get_int_value())) {
return Usecode_value(true);
} else {
return Usecode_value(false);
}
}
// parms[0] = quality of key to be removed
USECODE_INTRINSIC(remove_from_keyring) {
ignore_unused_variable_warning(num_parms);
const bool ret = getKeyring()->removekey(parms[0].get_int_value());
return Usecode_value(ret);
}
USECODE_INTRINSIC(save_pos) {
ignore_unused_variable_warning(num_parms);
// save_pos(item).
Game_object* item = get_item(parms[0]);
if (item) {
saved_pos = item->get_tile();
saved_map = gwin->get_map()->get_num();
}
return no_ret;
}
USECODE_INTRINSIC(teleport_to_saved_pos) {
// teleport_to_saved_pos(actor). Only supported for Avatar for now.
Actor* npc = as_actor(get_item(parms[0]));
if (npc == gwin->get_main_actor()) {
// Bad value?
if (saved_pos.tx < 0 || saved_pos.tx >= c_num_tiles) {
// Fix old games. Send to Monitor.
saved_pos = Tile_coord(719, 2608, 1);
}
gwin->teleport_party(
saved_pos, false, saved_map,
num_parms > 1 ? parms[1].get_int_value() : false);
}
return no_ret;
}
USECODE_INTRINSIC(get_item_weight) {
ignore_unused_variable_warning(num_parms);
Game_object* obj = get_item(parms[0]);
if (!obj) {
return Usecode_value(0);
} else {
return Usecode_value(obj->get_weight());
}
}
USECODE_INTRINSIC(get_skin_colour) {
ignore_unused_variable_warning(num_parms, parms);
// Gets skin colour of avatar. 0 (wh), 1 (br) or 2 (bl)
Main_actor* av = gwin->get_main_actor();
return Usecode_value(av->get_skin_color());
}
/*
* This is like the C version, but only '%s' is supported, and all the
* parms should be packed into one array.
* Added for Exult.
*/
USECODE_INTRINSIC(printf) {
ignore_unused_variable_warning(num_parms);
Usecode_value ret("");
const char* fmt = parms[0].get_elem0().get_str_value();
int count;
cout << endl; // For now...
if (!fmt || (count = parms[0].get_array_size()) <= 1) {
parms[0].print(cout);
return ret;
}
int i = 1; // Parm. #.
while (*fmt) {
const char* spec = strchr(fmt, '%');
if (!spec) {
spec = fmt + std::strlen(fmt);
}
cout.write(fmt, spec - fmt);
if (*spec == '%') {
if (spec[1] == 's') {
const Usecode_value p
= i < count ? parms[0][i] : Usecode_value(0);
if (p.get_type() == Usecode_value::int_type) {
cout << p.get_int_value();
} else {
p.print(cout);
}
spec += 2;
i++;
} else {
cout << '%';
spec++;
}
}
fmt = spec;
}
return ret;
}
USECODE_INTRINSIC(begin_casting_mode) {
Actor* npc = as_actor(get_item(parms[0]));
if (npc) {
// Have custom casting frames been specified?
// TODO: Need to de-hard-code.
const int cframes = num_parms > 1 ? parms[1].need_int_value() : 859;
npc->begin_casting(cframes);
}
return no_ret;
}
USECODE_INTRINSIC(get_usecode_fun) {
ignore_unused_variable_warning(num_parms);
Game_object* obj = get_item(parms[0]);
if (!obj) {
return Usecode_value(0);
}
return Usecode_value(obj->get_usecode());
}
USECODE_INTRINSIC(set_usecode_fun) {
ignore_unused_variable_warning(num_parms);
Game_object* obj = get_item(parms[0]);
if (!obj) {
return no_ret;
}
const int usefun = parms[1].get_int_value();
Usecode_symbol* ucsym = symtbl ? (*symtbl)[usefun] : nullptr;
obj->set_usecode(usefun, ucsym ? ucsym->get_name() : nullptr);
return no_ret;
}
USECODE_INTRINSIC(get_map_num) {
ignore_unused_variable_warning(num_parms);
Game_object* obj = get_item(parms[0]);
if (!obj) {
return Usecode_value(-1);
}
return Usecode_value(obj->get_map_num());
}
USECODE_INTRINSIC(is_dest_reachable) {
ignore_unused_variable_warning(num_parms);
Usecode_value ret(0);
Actor* npc = as_actor(get_item(parms[0]));
if (!npc || parms[1].get_array_size() < 2) {
return ret;
}
const Tile_coord dest = Tile_coord(
parms[1].get_elem(0).get_int_value(),
parms[1].get_elem(1).get_int_value(),
parms[1].get_array_size() == 2
? 0
: parms[1].get_elem(2).get_int_value());
ret = Usecode_value(is_dest_reachable(npc, dest));
return ret;
}
USECODE_INTRINSIC(sib_is_dest_reachable) {
// Note: this function did not work in SI Beta. This implementation is
// based on what usecode expects.
ignore_unused_variable_warning(num_parms);
Usecode_value ret(0);
Actor* npc = as_actor(get_item(parms[1]));
if (!npc || parms[0].get_array_size() < 2) {
return ret;
}
const Tile_coord dest = Tile_coord(
parms[0].get_elem(0).get_int_value(),
parms[0].get_elem(1).get_int_value(),
parms[0].get_array_size() == 2
? 0
: parms[0].get_elem(2).get_int_value());
ret = Usecode_value(is_dest_reachable(npc, dest));
return ret;
}
USECODE_INTRINSIC(can_avatar_reach_pos) {
ignore_unused_variable_warning(num_parms);
Usecode_value ret(0);
if (parms[0].get_array_size() < 2) {
return ret;
}
const Tile_coord dest = Tile_coord(
parms[0].get_elem(0).get_int_value(),
parms[0].get_elem(1).get_int_value(),
parms[0].get_array_size() == 2
? 0
: parms[0].get_elem(2).get_int_value());
ret = Usecode_value(is_dest_reachable(gwin->get_main_actor(), dest));
return ret;
}
USECODE_INTRINSIC(create_barge_object) {
// create_barge_object (width, height, dir(0-7)). Stores it in
// 'last_created'.
if (num_parms < 2) {
return Usecode_value(0);
}
auto b = std::make_shared<Barge_object>(
961, 0, 0, 0, 0, parms[0].get_int_value(), parms[1].get_int_value(),
num_parms >= 3 ? ((parms[2].get_int_value() >> 1) & 3) : 0);
b->set_invalid(); // Not in world yet.
b->set_flag(Obj_flags::okay_to_take);
last_created.push_back(b);
Usecode_value u(b);
return u;
}
USECODE_INTRINSIC(in_usecode_path) {
ignore_unused_variable_warning(num_parms);
// in_usecode_path (npc). Returns true if actor is in a usecode path.
Actor* npc = as_actor(get_item(parms[0]));
if (!npc) {
return Usecode_value(0);
}
if (npc->get_action() && npc->get_action()->as_usecode_path()) {
return Usecode_value(1);
}
return Usecode_value(0);
}
| 412 | 0.950889 | 1 | 0.950889 | game-dev | MEDIA | 0.695514 | game-dev | 0.89336 | 1 | 0.89336 |
PotRooms/AzurPromiliaData | 2,006 | Lua/lang/kr/lang_pet_egg.lua | local pet_egg = {}
local key_to_index_map = {}
local index_to_key_map = {}
for k, v in pairs(key_to_index_map) do
index_to_key_map[v] = k
end
local value_to_index_map = {}
local index_to_value_map = {}
for k, v in pairs(value_to_index_map) do
index_to_value_map[v] = k
end
local function SetReadonlyTable(t)
for k, v in pairs(t) do
if type(v) == "table" then
t[k] = SetReadonlyTable(v)
end
end
local mt = {
__data = t,
__index_to_key_map = index_to_key_map,
__key_to_index_map = key_to_index_map,
__index_to_value_map = index_to_value_map,
__index = function(t, k)
local tmt = getmetatable(t)
local data = tmt.__data
local value_index
if tmt.__key_to_index_map[k] ~= nil then
value_index = data[tmt.__key_to_index_map[k]]
else
value_index = data[k]
end
if type(value_index) == "table" then
return value_index
else
return tmt.__index_to_value_map[value_index]
end
end,
__newindex = function(t, k, v)
errorf("attempt to modify a read-only talbe!", 2)
end,
__pairs = function(t, k)
return function(t, k)
local tmt = getmetatable(t)
local data = tmt.__data
local nk, nv
if tmt.__key_to_index_map[k] ~= nil then
local iter_key = tmt.__key_to_index_map[k]
nk, nv = next(data, iter_key)
else
nk, nv = next(data, k)
end
local key, value
if tmt.__index_to_key_map[nk] ~= nil then
key = tmt.__index_to_key_map[nk]
else
key = nk
end
if type(nv) == "table" then
value = nv
else
value = tmt.__index_to_value_map[nv]
end
return key, value
end, t, nil
end,
__len = function(t)
local tmt = getmetatable(t)
local data = tmt.__data
return #data
end
}
t = setmetatable({}, mt)
return t
end
pet_egg = SetReadonlyTable(pet_egg)
return pet_egg
| 412 | 0.644778 | 1 | 0.644778 | game-dev | MEDIA | 0.475414 | game-dev | 0.790776 | 1 | 0.790776 |
IJEMIN/Unity-Programming-Essence | 2,703 | 19/Done/Zombie Multiplayer/Assets/Scripts/ItemSpawner.cs | using System.Collections;
using Photon.Pun;
using UnityEngine;
using UnityEngine.AI; // 내비메쉬 관련 코드
// 주기적으로 아이템을 플레이어 근처에 생성하는 스크립트
public class ItemSpawner : MonoBehaviourPun {
public GameObject[] items; // 생성할 아이템들
public float maxDistance = 5f; // 플레이어 위치로부터 아이템이 배치될 최대 반경
public float timeBetSpawnMax = 7f; // 최대 시간 간격
public float timeBetSpawnMin = 2f; // 최소 시간 간격
private float timeBetSpawn; // 생성 간격
private float lastSpawnTime; // 마지막 생성 시점
private void Start() {
// 생성 간격과 마지막 생성 시점 초기화
timeBetSpawn = Random.Range(timeBetSpawnMin, timeBetSpawnMax);
lastSpawnTime = 0;
}
// 주기적으로 아이템 생성 처리 실행
private void Update() {
// 호스트에서만 아이템 직접 생성 가능
if (!PhotonNetwork.IsMasterClient)
{
return;
}
if (Time.time >= lastSpawnTime + timeBetSpawn)
{
// 마지막 생성 시간 갱신
lastSpawnTime = Time.time;
// 생성 주기를 랜덤으로 변경
timeBetSpawn = Random.Range(timeBetSpawnMin, timeBetSpawnMax);
// 실제 아이템 생성
Spawn();
}
}
// 실제 아이템 생성 처리
private void Spawn() {
// (0,0,0)을 기준으로 maxDistance 안에서 내비메시위의 랜덤 위치 지정
Vector3 spawnPosition = GetRandomPointOnNavMesh(Vector3.zero, maxDistance);
// 바닥에서 0.5만큼 위로 올리기
spawnPosition += Vector3.up * 0.5f;
// 생성할 아이템을 무작위로 하나 선택
GameObject itemToCreate = items[Random.Range(0, items.Length)];
// 네트워크의 모든 클라이언트에서 해당 아이템 생성
GameObject item =
PhotonNetwork.Instantiate(itemToCreate.name, spawnPosition,
Quaternion.identity);
// 생성한 아이템을 5초 뒤에 파괴
StartCoroutine(DestroyAfter(item, 5f));
}
// 포톤의 PhotonNetwork.Destroy()를 지연 실행하는 코루틴
IEnumerator DestroyAfter(GameObject target, float delay) {
// delay 만큼 대기
yield return new WaitForSeconds(delay);
// target이 파괴되지 않았으면 파괴 실행
if (target != null)
{
PhotonNetwork.Destroy(target);
}
}
// 네브 메시 위의 랜덤한 위치를 반환하는 메서드
// center를 중심으로 distance 반경 안에서 랜덤한 위치를 찾는다.
private Vector3 GetRandomPointOnNavMesh(Vector3 center, float distance) {
// center를 중심으로 반지름이 maxDinstance인 구 안에서의 랜덤한 위치 하나를 저장
// Random.insideUnitSphere는 반지름이 1인 구 안에서의 랜덤한 한 점을 반환하는 프로퍼티
Vector3 randomPos = Random.insideUnitSphere * distance + center;
// 네브 메시 샘플링의 결과 정보를 저장하는 변수
NavMeshHit hit;
// randomPos를 기준으로 maxDistance 반경 안에서, randomPos에 가장 가까운 네브 메시 위의 한 점을 찾음
NavMesh.SamplePosition(randomPos, out hit, distance, NavMesh.AllAreas);
// 찾은 점 반환
return hit.position;
}
} | 412 | 0.699067 | 1 | 0.699067 | game-dev | MEDIA | 0.939644 | game-dev | 0.856387 | 1 | 0.856387 |
godotengine/godot | 7,423 | scene/3d/physics/area_3d.h | /**************************************************************************/
/* area_3d.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/**************************************************************************/
#pragma once
#include "core/templates/vset.h"
#include "scene/3d/physics/collision_object_3d.h"
class Area3D : public CollisionObject3D {
GDCLASS(Area3D, CollisionObject3D);
public:
enum SpaceOverride {
SPACE_OVERRIDE_DISABLED,
SPACE_OVERRIDE_COMBINE,
SPACE_OVERRIDE_COMBINE_REPLACE,
SPACE_OVERRIDE_REPLACE,
SPACE_OVERRIDE_REPLACE_COMBINE
};
private:
SpaceOverride gravity_space_override = SPACE_OVERRIDE_DISABLED;
Vector3 gravity_vec;
real_t gravity = 0.0;
bool gravity_is_point = false;
real_t gravity_point_unit_distance = 0.0;
SpaceOverride linear_damp_space_override = SPACE_OVERRIDE_DISABLED;
SpaceOverride angular_damp_space_override = SPACE_OVERRIDE_DISABLED;
real_t angular_damp = 0.1;
real_t linear_damp = 0.1;
int priority = 0;
real_t wind_force_magnitude = 0.0;
real_t wind_attenuation_factor = 0.0;
NodePath wind_source_path;
bool monitoring = false;
bool monitorable = false;
bool locked = false;
void _body_inout(int p_status, const RID &p_body, ObjectID p_instance, int p_body_shape, int p_area_shape);
void _body_enter_tree(ObjectID p_id);
void _body_exit_tree(ObjectID p_id);
struct ShapePair {
int body_shape = 0;
int area_shape = 0;
bool operator<(const ShapePair &p_sp) const {
if (body_shape == p_sp.body_shape) {
return area_shape < p_sp.area_shape;
} else {
return body_shape < p_sp.body_shape;
}
}
ShapePair() {}
ShapePair(int p_bs, int p_as) {
body_shape = p_bs;
area_shape = p_as;
}
};
struct BodyState {
RID rid;
int rc = 0;
bool in_tree = false;
VSet<ShapePair> shapes;
};
HashMap<ObjectID, BodyState> body_map;
void _area_inout(int p_status, const RID &p_area, ObjectID p_instance, int p_area_shape, int p_self_shape);
void _area_enter_tree(ObjectID p_id);
void _area_exit_tree(ObjectID p_id);
struct AreaShapePair {
int area_shape = 0;
int self_shape = 0;
bool operator<(const AreaShapePair &p_sp) const {
if (area_shape == p_sp.area_shape) {
return self_shape < p_sp.self_shape;
} else {
return area_shape < p_sp.area_shape;
}
}
AreaShapePair() {}
AreaShapePair(int p_bs, int p_as) {
area_shape = p_bs;
self_shape = p_as;
}
};
struct AreaState {
RID rid;
int rc = 0;
bool in_tree = false;
VSet<AreaShapePair> shapes;
};
HashMap<ObjectID, AreaState> area_map;
void _clear_monitoring();
bool audio_bus_override = false;
StringName audio_bus;
bool use_reverb_bus = false;
StringName reverb_bus;
float reverb_amount = 0.0;
float reverb_uniformity = 0.0;
void _initialize_wind();
protected:
void _notification(int p_what);
static void _bind_methods();
void _validate_property(PropertyInfo &p_property) const;
virtual void _space_changed(const RID &p_new_space) override;
public:
void set_gravity_space_override_mode(SpaceOverride p_mode);
SpaceOverride get_gravity_space_override_mode() const;
void set_gravity_is_point(bool p_enabled);
bool is_gravity_a_point() const;
void set_gravity_point_unit_distance(real_t p_scale);
real_t get_gravity_point_unit_distance() const;
void set_gravity_point_center(const Vector3 &p_center);
const Vector3 &get_gravity_point_center() const;
void set_gravity_direction(const Vector3 &p_direction);
const Vector3 &get_gravity_direction() const;
void set_gravity(real_t p_gravity);
real_t get_gravity() const;
void set_linear_damp_space_override_mode(SpaceOverride p_mode);
SpaceOverride get_linear_damp_space_override_mode() const;
void set_angular_damp_space_override_mode(SpaceOverride p_mode);
SpaceOverride get_angular_damp_space_override_mode() const;
void set_angular_damp(real_t p_angular_damp);
real_t get_angular_damp() const;
void set_linear_damp(real_t p_linear_damp);
real_t get_linear_damp() const;
void set_priority(int p_priority);
int get_priority() const;
void set_wind_force_magnitude(real_t p_wind_force_magnitude);
real_t get_wind_force_magnitude() const;
void set_wind_attenuation_factor(real_t p_wind_attenuation_factor);
real_t get_wind_attenuation_factor() const;
void set_wind_source_path(const NodePath &p_wind_source_path);
const NodePath &get_wind_source_path() const;
void set_monitoring(bool p_enable);
bool is_monitoring() const;
void set_monitorable(bool p_enable);
bool is_monitorable() const;
TypedArray<Node3D> get_overlapping_bodies() const;
TypedArray<Area3D> get_overlapping_areas() const; //function for script
bool has_overlapping_bodies() const;
bool has_overlapping_areas() const;
bool overlaps_area(Node *p_area) const;
bool overlaps_body(Node *p_body) const;
void set_audio_bus_override(bool p_override);
bool is_overriding_audio_bus() const;
void set_audio_bus_name(const StringName &p_audio_bus);
StringName get_audio_bus_name() const;
void set_use_reverb_bus(bool p_enable);
bool is_using_reverb_bus() const;
void set_reverb_bus_name(const StringName &p_audio_bus);
StringName get_reverb_bus_name() const;
void set_reverb_amount(float p_amount);
float get_reverb_amount() const;
void set_reverb_uniformity(float p_uniformity);
float get_reverb_uniformity() const;
Area3D();
~Area3D();
};
VARIANT_ENUM_CAST(Area3D::SpaceOverride);
| 412 | 0.855572 | 1 | 0.855572 | game-dev | MEDIA | 0.784214 | game-dev | 0.525447 | 1 | 0.525447 |
alexkulya/pandaria_5.4.8 | 47,242 | src/server/scripts/EasternKingdoms/Scholomance/scholomance.cpp | /*
* This file is part of the Pandaria 5.4.8 Project. See THANKS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "scholomance.h"
enum ScholoEvents
{
// Neophyte
EVENT_CAST_REND_FLESH = 100,
EVENT_CAST_SHADOW_INCINERATION = 101,
// acolyte
EVENT_CAST_SPIRIT_BARRAGE = 102,
EVENT_CAST_UNBOUND = 103,
EVENT_CAST_SHADOW_BOLT = 104,
EVENT_CAST_SHATTER_SOUL = 105,
// Risen Guard
EVENT_IMPALE = 106,
EVENT_UNHOLY_WEAPON = 107,
// Candleflickring mages
EVENT_FLICKERING_FLAME = 108,
EVENT_SKIN_LIKE_WAX = 109,
// Bored Student
EVENT_FIRE_BREATH = 110,
EVENT_SHADOW_NOVA = 111,
// Professor Slate
EVENT_TOXIC_POTION = 112,
EVENT_POTION_BRUTE_FORCE = 113,
EVENT_BRUTISH_FORCE = 114,
// BoneWeaver
EVENT_BONE_SHARDS = 115,
EVENT_SUMMON_WOVEN_BONEGUARD = 116,
// Lilian and Gandling
EVENT_TALK_1 = 117,
EVENT_TALK_2 = 118,
EVENT_TALK_3 = 119,
EVENT_TALK_4 = 120,
EVENT_TALK_5 = 121,
EVENT_TALK_6 = 122,
EVENT_TALK_7 = 123,
EVENT_TALK_8 = 124,
EVENT_TALK_9 = 125,
EVENT_SPECIAL = 126,
EVENT_CHECK_BONEWEAVER = 127,
EVENT_ESCORT = 128,
EVENT_FINALY_FORM = 129,
};
enum Yells
{
TALK_1 = 0,
TALK_2 = 1,
TALK_3 = 2,
TALK_4 = 3,
TALK_5 = 4,
TALK_6 = 5,
TALK_7 = 6,
TALK_8 = 7,
TALK_9 = 8,
TALK_10 = 9,
TALK_11 = 10,
TALK_12 = 11,
};
enum Spells
{
SPELL_SHADOW_FORM_VISUAL = 51126,
SPELL_VISUAL_STRANGULATE_EMOTE = 78037,
SPELL_UNHOLY_WEAPON = 111801,
SPELL_FLICKERING_FLAME = 114474,
SPELL_SKIN_LIKE_WAX = 114479,
SPELL_TWILING_CHANNEL = 78198,
SPELL_CANDLE_EURPTION_VISUAL = 39180,
SPELL_SHADOW_BOLT_BORED_STUDENT = 114859,
SPELL_SHADOW_NOVA_BORED_STUDENT = 114864,
SPELL_FIRE_BREATH_POTION_BORED_STUDENT = 114872,
SPELL_POTION_OF_BRUTISH_FORCE = 114874,
SPELL_TOXIC_POTION = 114873,
SPELL_SUMMON_BLACK_CANDLE = 114473,
SPELL_BLACK_CANDLE_SPELL = 114400,
SPELL_SPIRIT_BARRAGE = 111774,
SPELL_SHADOW_BOLT = 111599,
SPELL_SHATTER_SOUL = 111594,
SPELL_SHATTER_SOUL_SUMMON = 111596,
SPELL_IMPALE = 111813,
SPELL_BOLIDING_BLOODTHIRST = 114141,
SPELL_BOILING_BLOODTHIRST = 114155,
SPELL_BOILING_BLOODTHIRST_AURA = 114141,
SPELL_REND_FLESH_LOW_LEVEL = 120787,
SPELL_REND_FLESH_HIGH_LEVEL = 111762,
SPELL_SHADOW_INCINERATION = 111752,
SPELL_DRINK_VIAL = 114800,
SPELL_DRINK_VIAL_PROFESSOR_MORPH = 124934,
SPELL_CHAIN = 83487,
SPELL_CLOTTING = 114176,
SPELL_KRASTINOV_ACHIEVEMENT_SPELL = 115427,
};
// Neophyte
#define REND_FLESH_INTERVAL urand(10000, 16000)
#define SHADOW_INCINERATION_INTERVAL 6500
// Acolyte
//#define UNBOUND_INTERVAL
#define SHADOW_BOLT_INTERVAL 6000
#define SHATTER_SOUL_INTERVAL urand(14000, 20000)
#define EVENT_UNHOLY_WEAPON_INTERVAL urand(20000, 26000)
#define EVENT_IMPALE_INTERVAL urand(6000, 14000)
#define EVENT_FLICKERING_FLAME_INTERVAL urand(6000, 14000)
#define EVENT_SKIN_LIKE_WAX_INTERVAL 10000
#define firebreathinterval urand(8000, 30000)
#define toxicinterval urand(5000, 20000)
#define brutishforceinterval 25000
#define shadowbreathinterval urand(5000, 25000)
uint32 GetWovenGuardCount(WorldObject* owner)
{
std::list <Creature*> WovenBoneguards;
GetCreatureListWithEntryInGrid(WovenBoneguards, owner, NPC_WOVEN_BONEGUARD, 80.0f);
if (WovenBoneguards.empty())
return 0;
return WovenBoneguards.size();
}
// Chillheart intro door 211259
class go_chillheart_iron_door : public GameObjectScript
{
public:
go_chillheart_iron_door() : GameObjectScript("go_chillheart_iron_door") { }
bool OnGossipHello(Player* player, GameObject* go) override
{
if (Creature* Chillheart = GetClosestCreatureWithEntry(go, NPC_INSTRUCTOR_CHILLHEART, 150.0f, true))
Chillheart->AI()->DoAction(ACTION_INTRO);
if (Creature* TalkingSkull = GetClosestCreatureWithEntry(go, NPC_TALKING_SKULL, 150.0f, true))
TalkingSkull->AI()->DoAction(ACTION_INTRO);
go->UseDoorOrButton();
return true;
}
};
// Polyformic acid potion 211669
class go_polyformic_acid_potion : public GameObjectScript
{
public:
go_polyformic_acid_potion() : GameObjectScript("go_alchemy_bottle_white") { }
bool OnGossipHello(Player* player, GameObject* go) override
{
if (player)
player->CastSpell(player, SPELL_DRINK_VIAL, false);
if (go)
go->SetFlag(GAMEOBJECT_FIELD_FLAGS, GO_FLAG_INTERACT_COND);
return true;
}
};
// Boneweaver 59193
class npc_boneweaver : public CreatureScript
{
public:
npc_boneweaver() : CreatureScript("npc_boneweaver") { }
struct npc_boneweaverAI : public ScriptedAI
{
npc_boneweaverAI(Creature* creature) : ScriptedAI(creature), _instance(creature->GetInstanceScript()) { }
EventMap events, nonCombatEvents;
float PosY;
void IsSummonedBy(Unit* summoner) override { }
void Reset() override
{
me->SetReactState(REACT_PASSIVE);
me->CastSpell(me, SPELL_BONEWEAVING, false);
nonCombatEvents.ScheduleEvent(EVENT_SUMMON_WOVEN_BONEGUARD, 3000);
}
void InitializeAI() override
{
me->SetReactState(REACT_PASSIVE);
me->CastSpell(me, SPELL_BONEWEAVING, false);
nonCombatEvents.ScheduleEvent(EVENT_SUMMON_WOVEN_BONEGUARD, 3000);
}
void JustSummoned(Creature* summon) override
{
if (Creature* Lilian = GetClosestCreatureWithEntry(me, NPC_LILIAN_VOSS, 60.0f, true))
summon->GetMotionMaster()->MoveChase(Lilian);
}
void DoAction(int32 actionId) override { }
void DamageTaken(Unit* attacker, uint32& damage) override { }
void EnterCombat(Unit* who) override
{
events.ScheduleEvent(EVENT_BONE_SHARDS, 3000);
events.ScheduleEvent(EVENT_SUMMON_WOVEN_BONEGUARD, urand(8000, 9000));
}
void UpdateAI(uint32 diff) override
{
events.Update(diff);
nonCombatEvents.Update(diff);
if (uint32 eventId = nonCombatEvents.ExecuteEvent())
if (eventId == EVENT_SUMMON_WOVEN_BONEGUARD)
{
if (GetWovenGuardCount(me) > 6)
return;
me->SummonCreature(NPC_WOVEN_BONEGUARD, me->GetPositionX() + frand(-5.0f, 5.0f), me->GetPositionY() + frand(-6.0f, 6.0f), me->GetPositionZ(), TEMPSUMMON_MANUAL_DESPAWN);
}
if (!UpdateVictim())
return;
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_BONE_SHARDS:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 50.0f, true))
me->CastSpell(target, SPELL_BONE_SHARDS, false);
events.ScheduleEvent(EVENT_BONE_SHARDS, urand(3000, 4000));
break;
case EVENT_SUMMON_WOVEN_BONEGUARD:
me->SummonCreature(NPC_WOVEN_BONEGUARD, me->GetPositionX() + frand(-5.0f, 5.0f), me->GetPositionY() + frand(-6.0f, 6.0f), me->GetPositionZ(), TEMPSUMMON_MANUAL_DESPAWN);
events.ScheduleEvent(EVENT_SUMMON_WOVEN_BONEGUARD, urand(8000, 16000));
break;
}
}
}
private:
InstanceScript* _instance;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_boneweaverAI(creature);
}
};
// Acolyte 58757
class npc_scholomance_acolyte : public CreatureScript
{
public:
npc_scholomance_acolyte() : CreatureScript("npc_scholomance_acolyte") { }
struct npc_scholomance_acolyteAI : public ScriptedAI
{
npc_scholomance_acolyteAI(Creature* creature) : ScriptedAI(creature) { }
EventMap events;
void Reset() override
{
me->AddAura(SPELL_SHADOW_FORM_VISUAL, me);
me->SetReactState(REACT_DEFENSIVE);
}
void EnterCombat(Unit* /*who*/) override
{
if (me->HasAura(SPELL_VISUAL_STRANGULATE_EMOTE))
me->RemoveAura(SPELL_VISUAL_STRANGULATE_EMOTE);
events.ScheduleEvent(EVENT_CAST_SHADOW_BOLT, SHADOW_BOLT_INTERVAL);
events.ScheduleEvent(EVENT_CAST_SHATTER_SOUL, SHATTER_SOUL_INTERVAL);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
if (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_CAST_SHADOW_BOLT:
if (Unit* target = me->GetVictim())
me->CastSpell(target, SPELL_SHADOW_BOLT);
events.ScheduleEvent(EVENT_CAST_SHADOW_BOLT, SHADOW_BOLT_INTERVAL);
break;
case EVENT_CAST_SHATTER_SOUL:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 50.0F, true))
me->CastSpell(target, SPELL_SHATTER_SOUL);
events.ScheduleEvent(EVENT_CAST_SHATTER_SOUL, SHATTER_SOUL_INTERVAL);
break;
}
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_scholomance_acolyteAI(creature);
}
};
// Neophyte 58823
class npc_scholomance_neophyte : public CreatureScript
{
public:
npc_scholomance_neophyte() : CreatureScript("npc_scholomance_neophyte") { }
struct npc_scholomance_neophyteAI : public ScriptedAI
{
npc_scholomance_neophyteAI(Creature* creature) : ScriptedAI(creature) { }
EventMap events;
void EnterCombat(Unit* /*who*/) override
{
if (me->HasAura(SPELL_VISUAL_STRANGULATE_EMOTE))
me->RemoveAura(SPELL_VISUAL_STRANGULATE_EMOTE);
if (me->HasAura(SPELL_SHADOW_FORM_VISUAL))
me->RemoveAura(SPELL_SHADOW_FORM_VISUAL);
me->SetReactState(REACT_DEFENSIVE);
events.ScheduleEvent(EVENT_CAST_REND_FLESH, REND_FLESH_INTERVAL);
events.ScheduleEvent(EVENT_CAST_SHADOW_INCINERATION, SHADOW_INCINERATION_INTERVAL);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
if (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_CAST_REND_FLESH:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 50.0F, true))
me->CastSpell(target, SPELL_REND_FLESH_HIGH_LEVEL);
events.ScheduleEvent(EVENT_CAST_REND_FLESH, REND_FLESH_INTERVAL);
break;
case EVENT_CAST_SHADOW_INCINERATION:
if (Unit* target = me->GetVictim())
me->CastSpell(target, SPELL_SHADOW_INCINERATION);
events.ScheduleEvent(EVENT_CAST_SHADOW_INCINERATION, SHADOW_INCINERATION_INTERVAL);
break;
}
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_scholomance_neophyteAI(creature);
}
};
// Risen Guard 58822
class npc_scholomance_risen_guard : public CreatureScript
{
public:
npc_scholomance_risen_guard() : CreatureScript("npc_scholomance_risen_guard") { }
struct npc_scholomance_risen_guardAI : public ScriptedAI
{
npc_scholomance_risen_guardAI(Creature* creature) : ScriptedAI(creature) { }
EventMap events;
void Reset() override
{
SetEquipmentSlots(false, RisenGuardSword, 0, EQUIP_NO_CHANGE);
}
void InitializeAI() override
{
SetEquipmentSlots(false, RisenGuardSword, 0, EQUIP_NO_CHANGE);
}
void EnterCombat(Unit* /*who*/) override
{
events.ScheduleEvent(EVENT_IMPALE, EVENT_IMPALE_INTERVAL);
events.ScheduleEvent(EVENT_UNHOLY_WEAPON, EVENT_UNHOLY_WEAPON_INTERVAL);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
if (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_IMPALE:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 50.0F, true))
me->CastSpell(target, SPELL_IMPALE);
events.ScheduleEvent(EVENT_IMPALE, EVENT_IMPALE_INTERVAL);
break;
case EVENT_UNHOLY_WEAPON:
if (Unit* target = me->GetVictim())
me->CastSpell(target, SPELL_UNHOLY_WEAPON);
events.ScheduleEvent(EVENT_UNHOLY_WEAPON, EVENT_UNHOLY_WEAPON_INTERVAL);
break;
}
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_scholomance_risen_guardAI(creature);
}
};
// Shatter soul fragment 58758
class npc_shatter_soul_fragment : public CreatureScript
{
public:
npc_shatter_soul_fragment() : CreatureScript("npc_shatter_soul_fragment") { }
struct npc_shatter_soul_fragmentAI : public ScriptedAI
{
npc_shatter_soul_fragmentAI(Creature* creature) : ScriptedAI(creature) { }
void Reset() override
{
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->SetFaction(16);
me->DespawnOrUnsummon(8000);
}
void IsSummonedBy(Unit* summoner) override
{
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->SetFaction(16);
me->DespawnOrUnsummon(8000);
}
void EnterCombat(Unit* /*who*/) override
{
if (Unit* target = me->GetVictim())
me->CastSpell(target, SPELL_SPIRIT_BARRAGE);
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_shatter_soul_fragmentAI(creature);
}
};
// World trigger candle 59481
struct npc_scholomance_dark_candle : public ScriptedAI
{
npc_scholomance_dark_candle(Creature* creature) : ScriptedAI(creature) {}
uint32 candleCount;
void InitializeAI() override
{
SetCombatMovement(false);
switch (me->GetMapId())
{
case 1007: // Scholomance
candleCount = 0;
me->CastSpell(me, SPELL_SUMMON_BLACK_CANDLE);
me->CastSpell(me, SPELL_BLACK_CANDLE_SPELL);
break;
case 1009: // Heart of Fear
DoCast(me, 125270);
break;
}
}
void DoAction(int32 actionId) override
{
if (actionId == ACTION_CANDLESTICK_DEATH)
{
candleCount++;
if (candleCount >= 2)
{
me->RemoveAurasDueToSpell(SPELL_SUMMON_BLACK_CANDLE);
me->RemoveAurasDueToSpell(SPELL_BLACK_CANDLE_SPELL);
}
}
}
void UpdateAI(uint32 /*diff*/) override { }
};
// Candlestick mage 59467
class npc_scholomance_candlestick_mage : public CreatureScript
{
public:
npc_scholomance_candlestick_mage() : CreatureScript("npc_scholomance_candlestick_mage") { }
enum iEvents
{
EVENT_INIT = 1,
};
struct npc_scholomance_candlestick_mageAI : public ScriptedAI
{
npc_scholomance_candlestick_mageAI(Creature* creature) : ScriptedAI(creature) { }
EventMap events, nonCombatEvents;
uint64 CandleGUID;
void InitializeAI() override
{
CandleGUID = 0;
nonCombatEvents.ScheduleEvent(EVENT_INIT, 2 * IN_MILLISECONDS);
Reset();
}
void Reset() override
{
events.Reset();
}
void EnterCombat(Unit* /*who*/) override
{
events.ScheduleEvent(EVENT_FLICKERING_FLAME, EVENT_FLICKERING_FLAME_INTERVAL);
events.ScheduleEvent(EVENT_SKIN_LIKE_WAX, EVENT_SKIN_LIKE_WAX_INTERVAL);
}
void JustDied(Unit* /*killer*/) override
{
if (Creature* candle = ObjectAccessor::GetCreature(*me, CandleGUID))
candle->AI()->DoAction(ACTION_CANDLESTICK_DEATH);
}
void UpdateAI(uint32 diff) override
{
nonCombatEvents.Update(diff);
while (uint32 eventId = nonCombatEvents.ExecuteEvent())
{
if (eventId == EVENT_INIT)
{
if (Creature* candle = me->FindNearestCreature(NPC_CANDLE, 10.0f, true))
{
CandleGUID = candle->GetGUID();
me->SetFacingToObject(candle);
me->CastSpell(me, SPELL_TWILING_CHANNEL);
}
}
break;
}
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_FLICKERING_FLAME:
me->CastSpell(me->GetVictim(), SPELL_FLICKERING_FLAME);
events.ScheduleEvent(EVENT_FLICKERING_FLAME, EVENT_FLICKERING_FLAME_INTERVAL);
break;
case EVENT_SKIN_LIKE_WAX:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 50.0F, true))
me->CastSpell(target, SPELL_SKIN_LIKE_WAX);
events.ScheduleEvent(EVENT_SKIN_LIKE_WAX, EVENT_SKIN_LIKE_WAX_INTERVAL);
break;
}
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_scholomance_candlestick_mageAI(creature);
}
};
enum KrastTexts
{
TALK_KRAST_AGGRO = 0,
TALK_KRAST_DEAD,
};
// Krastinoc carvers 59368
class npc_scholomance_krastinoc_carvers : public CreatureScript
{
public:
npc_scholomance_krastinoc_carvers() : CreatureScript("npc_scholomance_krastinoc_carvers") { }
struct npc_scholomance_krastinoc_carversAI : public ScriptedAI
{
npc_scholomance_krastinoc_carversAI(Creature* creature) : ScriptedAI(creature) { }
EventMap events;
void Reset() override
{
switch (urand(0, 5))
{
case 0:
me->CastSpell(me, 124064); // book
break;
}
me->CastSpell(me, SPELL_BOLIDING_BLOODTHIRST);
}
void EnterCombat(Unit* /*who*/) override
{
Talk(TALK_KRAST_AGGRO);
}
void JustDied(Unit* /*killer*/) override
{
Talk(TALK_KRAST_DEAD);
DoCast(me, SPELL_BOILING_BLOODTHIRST);
if (Aura* BloodAura = me->GetAura(SPELL_BOILING_BLOODTHIRST_AURA))
if (BloodAura->GetStackAmount() >= 99)
DoCast(me, SPELL_KRASTINOV_ACHIEVEMENT_SPELL);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_scholomance_krastinoc_carversAI(creature);
}
};
// Flesh horror 59359
class npc_scholomance_flesh_horror : public CreatureScript
{
public:
npc_scholomance_flesh_horror() : CreatureScript("npc_scholomance_flesh_horror") { }
struct npc_scholomance_flesh_horrorAI : public ScriptedAI
{
npc_scholomance_flesh_horrorAI(Creature* creature) : ScriptedAI(creature) { }
EventMap events;
std::list<uint64> meat;
uint32 VehPos;
void Reset() override
{
RemoveCraftMeat();
VehPos = 0;
}
void InitializeAI() override
{
VehPos = 0;
}
void RemoveCraftMeat()
{
for (auto&& itr : meat)
if (Creature* CraftMeat = ObjectAccessor::GetCreature(*me, itr))
CraftMeat->DespawnOrUnsummon();
meat.clear();
}
bool HasGraftsDeath()
{
for (auto&& itr : meat)
if (Creature* graft = ObjectAccessor::GetCreature(*me, itr))
if (graft->IsAlive()) // we need check once
return false;
return true;
}
void EnterCombat(Unit* /*who*/) override
{
Position pos;
me->GetRandomNearPosition(pos, 8.0f);
for (uint8 i = 0; i < 4; i++)
{
if (Creature* graft = me->SummonCreature(NPC_MEAT_GRAFT, pos, TEMPSUMMON_MANUAL_DESPAWN))
{
if (!IsHeroic())
{
me->SetMaxHealth(9800);
me->SetHealth(9800);
graft->SetLevel(39);
}
graft->EnterVehicle(me, VehPos);
graft->SetReactState(REACT_PASSIVE);
graft->AddUnitState(UNIT_STATE_CANNOT_AUTOATTACK);
meat.push_back(graft->GetGUID());
VehPos++;
}
}
}
void JustDied(Unit* /*killer*/) override
{
RemoveCraftMeat();
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->GetHealthPct() < 95 && !HasGraftsDeath())
me->CastSpell(me, SPELL_CLOTTING, false);
if (HasGraftsDeath())
{
me->Kill(me);
me->DespawnOrUnsummon(10000);
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_scholomance_flesh_horrorAI(creature);
}
};
// Bored student 59614
class npc_scholomance_bored_student : public CreatureScript
{
public:
npc_scholomance_bored_student() : CreatureScript("npc_scholomance_bored_student") { }
struct npc_scholomance_bored_studentAI : public ScriptedAI
{
npc_scholomance_bored_studentAI(Creature* creature) : ScriptedAI(creature) { }
EventMap events;
void Reset() override { }
void EnterCombat(Unit* /*who*/) override
{
events.ScheduleEvent(EVENT_SHADOW_NOVA, firebreathinterval);
events.ScheduleEvent(EVENT_FIRE_BREATH, shadowbreathinterval);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SHADOW_NOVA:
me->CastSpell(me->GetVictim(), SPELL_SHADOW_NOVA_BORED_STUDENT);
events.ScheduleEvent(EVENT_SHADOW_NOVA, shadowbreathinterval);
break;
case EVENT_FIRE_BREATH:
me->CastSpell(me->GetVictim(), SPELL_FIRE_BREATH_POTION_BORED_STUDENT);
events.ScheduleEvent(EVENT_FIRE_BREATH, firebreathinterval);
break;
}
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_scholomance_bored_studentAI(creature);
}
};
// Professor Slait 59613
class npc_scholomance_professor : public CreatureScript
{
public:
npc_scholomance_professor() : CreatureScript("npc_scholomance_professor") { }
struct npc_scholomance_professorAI : public ScriptedAI
{
npc_scholomance_professorAI(Creature* creature) : ScriptedAI(creature) { }
EventMap events;
void Reset() override { }
void EnterCombat(Unit* /*who*/) override
{
events.ScheduleEvent(EVENT_BRUTISH_FORCE, brutishforceinterval);
events.ScheduleEvent(EVENT_TOXIC_POTION, toxicinterval);
events.ScheduleEvent(EVENT_FIRE_BREATH, firebreathinterval);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
{
switch (urand(0, 20))
{
case 0:
me->CastSpell(me, 79506); // emote talk
break;
}
}
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_FIRE_BREATH:
me->CastSpell(me->GetVictim(), SPELL_FIRE_BREATH_POTION_BORED_STUDENT);
events.ScheduleEvent(EVENT_FIRE_BREATH, firebreathinterval);
break;
case EVENT_TOXIC_POTION:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 50.0f, true))
me->CastSpell(target, SPELL_TOXIC_POTION);
events.ScheduleEvent(EVENT_FIRE_BREATH, toxicinterval);
break;
case EVENT_BRUTISH_FORCE:
me->CastSpell(me, SPELL_POTION_OF_BRUTISH_FORCE);
events.ScheduleEvent(EVENT_BRUTISH_FORCE, brutishforceinterval);
break;
}
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_scholomance_professorAI(creature);
}
};
// Gandling at Rattlegore/lilian 58875
class npc_gandling_at_rattlegore : public CreatureScript
{
public:
npc_gandling_at_rattlegore() : CreatureScript("npc_gandling_at_rattlegore") { }
struct npc_gandling_at_rattlegoreAI : public ScriptedAI
{
npc_gandling_at_rattlegoreAI(Creature* creature) : ScriptedAI(creature), _instance(creature->GetInstanceScript()) { }
EventMap nonCombatEvents;
float PosY;
bool AtRattlegore, _introDone;
void IsSummonedBy(Unit* summoner) override { }
void Reset() override
{
me->AddAura(SPELL_BONE_ARMOR_VISUAL, me);
me->SetReactState(REACT_PASSIVE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
SetEquipmentSlots(false, GandlingStaff, 0, EQUIP_NO_CHANGE);
}
void InitializeAI() override
{
me->AddAura(SPELL_BONE_ARMOR_VISUAL, me);
me->SetReactState(REACT_PASSIVE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
SetEquipmentSlots(false, GandlingStaff, 0, EQUIP_NO_CHANGE);
AtRattlegore = false;
_introDone = false;
}
void JustSummoned(Creature* summon) override { }
void DoAction(int32 actionId) override
{
switch (actionId)
{
case ACTION_INTRO:
Talk(TALK_1);
if (Creature* Lilian = GetClosestCreatureWithEntry(me, NPC_LILIAN_VOSS, 50.0f, true))
Lilian->AI()->DoAction(ACTION_INTRO);
nonCombatEvents.ScheduleEvent(EVENT_TALK_1, 6000);
break;
case ACTION_DIFF_INTRO:
Talk(TALK_10);
break;
case ACTION_REMOVE_LILIAN_SOUL:
Talk(TALK_11);
nonCombatEvents.ScheduleEvent(EVENT_TALK_9, 4500);
break;
}
}
void DamageTaken(Unit* attacker, uint32& damage) override { }
void EnterCombat(Unit* who) override { }
void MovementInform(uint32 type, uint32 pointId) override
{
if (type != POINT_MOTION_TYPE)
return;
switch (pointId)
{
case 0:
Talk(TALK_7);
me->CastSpell(me, SPELL_TELEPORT_VISUAL, false);
me->SetAnimationTier(UnitAnimationTier::Fly);
me->OverrideInhabitType(INHABIT_AIR);
me->UpdateMovementFlags();
me->CastSpell(me, SPELL_SOUL_RIP_VISUAL, false);
me->NearTeleportTo(me->GetPositionX(), me->GetPositionY() + 10.0f, me->GetPositionZ(), me->GetOrientation());
nonCombatEvents.ScheduleEvent(EVENT_SPECIAL, 1500);
break;
case 1:
me->CastSpell(me, SPELL_TELEPORT_VISUAL, false);
me->DespawnOrUnsummon();
break;
}
}
void UpdateAI(uint32 diff) override
{
nonCombatEvents.Update(diff);
if (!me->HasAura(SPELL_BONE_ARMOR_VISUAL) && !AtRattlegore)
me->AddAura(SPELL_BONE_ARMOR_VISUAL, me);
if (AtRattlegore && me->FindNearestPlayer(25.0f) && me->FindNearestPlayer(25.0f)->GetPositionZ() <= 109.0f)
{
AtRattlegore = false;
Talk(TALK_8);
nonCombatEvents.ScheduleEvent(EVENT_TALK_8, 8000);
if (Creature* Lilian = GetClosestCreatureWithEntry(me, NPC_LILIAN_VOSS, 50.0f, true))
Lilian->AI()->DoAction(ACTION_DIFF_INTRO);
if (Creature* Skull = GetClosestCreatureWithEntry(me, NPC_TALKING_SKULL, 80.0f, true))
Skull->AI()->DoAction(ACTION_COUNTINUE_MOVE);
}
while (uint32 eventId = nonCombatEvents.ExecuteEvent())
{
switch (eventId)
{
case EVENT_TALK_1:
Talk(TALK_2);
nonCombatEvents.ScheduleEvent(EVENT_TALK_2, 10000);
break;
case EVENT_TALK_2:
Talk(TALK_3);
nonCombatEvents.ScheduleEvent(EVENT_TALK_3, 10000);
break;
case EVENT_TALK_3:
Talk(TALK_4);
nonCombatEvents.ScheduleEvent(EVENT_TALK_4, 10000);
break;
case EVENT_TALK_4:
Talk(TALK_5);
nonCombatEvents.ScheduleEvent(EVENT_TALK_5, 10000);
break;
case EVENT_TALK_5:
Talk(TALK_6);
nonCombatEvents.ScheduleEvent(EVENT_TALK_6, 6000);
break;
case EVENT_TALK_6:
me->SetAnimationTier(UnitAnimationTier::Ground);
me->OverrideInhabitType(INHABIT_GROUND);
me->UpdateMovementFlags();
me->RemoveAurasDueToSpell(SPELL_SOUL_RIP_VISUAL);
me->GetMotionMaster()->MovePoint(0, GandlinglilianDoorPoint);
break;
case EVENT_TALK_8:
Talk(TALK_9);
break;
case EVENT_TALK_9:
Talk(TALK_12);
if (Unit* TalkingSkull = ObjectAccessor::GetUnit(*me, _instance->GetData64(NPC_TALKING_SKULL)))
TalkingSkull->ToCreature()->AI()->Talk(TALK_GANDLING_LEAVE);
me->SetAnimationTier(UnitAnimationTier::Ground);
me->OverrideInhabitType(INHABIT_GROUND);
me->UpdateMovementFlags();
me->RemoveAurasDueToSpell(SPELL_SOUL_RIP_VISUAL);
me->GetMotionMaster()->MovePoint(1, GandlingLeavePoint);
break;
case EVENT_SPECIAL:
me->NearTeleportTo(GandlingTeleportPos.GetPositionX(), GandlingTeleportPos.GetPositionY(), GandlingTeleportPos.GetPositionZ(), GandlingTeleportPos.GetOrientation());
me->SetHomePosition(GandlingTeleportPos.GetPositionX(), GandlingTeleportPos.GetPositionY(), GandlingTeleportPos.GetPositionZ(), GandlingTeleportPos.GetOrientation());
AtRattlegore = true;
me->CastSpell(me, SPELL_GANDLING_INTRO_CHANNEL, false);
break;
}
}
}
private:
InstanceScript* _instance;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_gandling_at_rattlegoreAI(creature);
}
};
// Talking Skull 64562
class npc_talking_skull : public CreatureScript
{
public:
npc_talking_skull() : CreatureScript("npc_talking_skull") { }
struct npc_talking_skullAI : public ScriptedAI
{
npc_talking_skullAI(Creature* creature) : ScriptedAI(creature) { }
EventMap nonCombatEvents;
uint32 wp;
bool AtGandling;
void Reset() override { }
void InitializeAI() override
{
wp = 0;
AtGandling = false;
me->SetWalk(true);
me->SetSpeed(MOVE_WALK, 2.3f);
}
void DoAction(int32 actionId) override
{
switch (actionId)
{
case ACTION_COUNTINUE_MOVE:
case ACTION_INTRO:
if (!AtGandling)
nonCombatEvents.ScheduleEvent(EVENT_ESCORT, urand(1000, 2000));
break;
case ACTION_ALEXEI:
//Talk(...)
nonCombatEvents.ScheduleEvent(EVENT_FINALY_FORM, urand(3000, 5000));
break;
}
}
void MovementInform(uint32 type, uint32 pointId) override
{
if (type != POINT_MOTION_TYPE)
return;
wp++;
switch (pointId)
{
case 0:
Talk(TALK_CHILLHEART_ENTRANCE);
Talk(TALK_CHILLHEART);
me->GetMotionMaster()->Clear();
break;
case 9:
Talk(TALK_JANDICE_ENTRANCE);
me->GetMotionMaster()->Clear();
nonCombatEvents.ScheduleEvent(EVENT_ESCORT, 4000);
break;
case 10:
me->GetMotionMaster()->Clear();
break;
case 11:
Talk(TALK_RATTLEGORE_ENTRANCE);
me->GetMotionMaster()->Clear();
break;
case 14:
me->GetMotionMaster()->Clear();
break;
case 16:
Talk(TALK_LILIAN_ENTRANCE);
me->GetMotionMaster()->Clear();
break;
case 29:
Talk(TALK_GANDLING_ENTRANCE);
AtGandling = true;
me->GetMotionMaster()->Clear();
break;
default:
nonCombatEvents.ScheduleEvent(EVENT_ESCORT, urand(100, 200));
break;
}
}
void DamageTaken(Unit* /*attacker*/, uint32& damage) override { }
void UpdateAI(uint32 diff) override
{
nonCombatEvents.Update(diff);
while (uint32 eventId = nonCombatEvents.ExecuteEvent())
{
switch (eventId)
{
case EVENT_ESCORT:
me->GetMotionMaster()->MovePoint(wp, SkullPath[wp]);
break;
case EVENT_FINALY_FORM:
if (Creature* Alexi = me->SummonCreature(NPC_ALEXIY_BAROV, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), me->GetOrientation(), TEMPSUMMON_MANUAL_DESPAWN))
me->DespawnOrUnsummon();
break;
}
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_talking_skullAI(creature);
}
};
// Polymorfic acid 114800
class spell_polymorfic_acid_potion : public SpellScriptLoader
{
public:
spell_polymorfic_acid_potion() : SpellScriptLoader("spell_polymorfic_acid_potion") { }
class spell_polymorfic_acid_potion_AuraScript : public AuraScript
{
PrepareAuraScript(spell_polymorfic_acid_potion_AuraScript);
void OnApply(AuraEffect const* aurEff, AuraEffectHandleModes mode)
{
if (Unit* owner = GetOwner()->ToUnit())
owner->CastSpell(owner, SPELL_DRINK_VIAL_PROFESSOR_MORPH, false);
}
void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/)
{
if (Unit* owner = GetOwner()->ToUnit())
if (owner->HasAura(SPELL_DRINK_VIAL_PROFESSOR_MORPH))
owner->RemoveAura(SPELL_DRINK_VIAL_PROFESSOR_MORPH);
}
void Register() override
{
OnEffectApply += AuraEffectApplyFn(spell_polymorfic_acid_potion_AuraScript::OnApply, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL, AURA_EFFECT_HANDLE_REAL);
OnEffectRemove += AuraEffectRemoveFn(spell_polymorfic_acid_potion_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL, AURA_EFFECT_HANDLE_REAL);
}
};
AuraScript* GetAuraScript() const override
{
return new spell_polymorfic_acid_potion_AuraScript();
}
};
// Boiling Bloodthirst 114155
class spell_boiling_bloodthirst : public SpellScriptLoader
{
public:
spell_boiling_bloodthirst() : SpellScriptLoader("spell_boiling_bloodthirst") { }
class spell_boiling_bloodthirst_SpellScript : public SpellScript
{
PrepareSpellScript(spell_boiling_bloodthirst_SpellScript);
void CheckTargets(std::list<WorldObject*>& targets)
{
targets.remove_if([=](WorldObject* target) { return target->GetEntry() != NPC_KRASTINOV_CARVER; });
}
void HandleOnHitEffect(SpellEffIndex /*effIndex*/)
{
if (Unit* caster = GetCaster())
if (Unit* target = GetHitUnit())
if (Aura* CasterBloodAura = caster->GetAura(SPELL_BOILING_BLOODTHIRST_AURA))
if (Aura* TargetBloodAura = target->GetAura(SPELL_BOILING_BLOODTHIRST_AURA))
TargetBloodAura->SetStackAmount(TargetBloodAura->GetStackAmount() + CasterBloodAura->GetStackAmount() - 1);
}
void Register() override
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_boiling_bloodthirst_SpellScript::CheckTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENTRY);
OnEffectHitTarget += SpellEffectFn(spell_boiling_bloodthirst_SpellScript::HandleOnHitEffect, EFFECT_0, SPELL_EFFECT_FORCE_CAST);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_boiling_bloodthirst_SpellScript();
}
};
void AddSC_scholomance()
{
new go_chillheart_iron_door();
new go_polyformic_acid_potion();
new npc_boneweaver();
new npc_scholomance_acolyte();
new npc_scholomance_neophyte();
new npc_scholomance_risen_guard();
new npc_shatter_soul_fragment();
new creature_script<npc_scholomance_dark_candle>("npc_scholomance_dark_candle");
new npc_scholomance_candlestick_mage();
new npc_scholomance_krastinoc_carvers();
new npc_scholomance_flesh_horror();
new npc_scholomance_bored_student();
new npc_scholomance_professor();
new npc_gandling_at_rattlegore();
new npc_talking_skull();
new spell_polymorfic_acid_potion();
new spell_boiling_bloodthirst();
}
| 412 | 0.925783 | 1 | 0.925783 | game-dev | MEDIA | 0.997429 | game-dev | 0.898411 | 1 | 0.898411 |
berezaa/vesteria | 6,478 | src/ReplicatedStorage/modules/levels.lua |
local runService = game:GetService("RunService")
local replicatedStorage = game:GetService("ReplicatedStorage")
local modules = require(replicatedStorage.modules)
local network = modules.load("network")
local module = {}
-- returns the total exp needed to reach this level
function module.getEXPForLevel(level)
return 7 + 5*(level - 2) + 4*(level - 2)^2
end
function module.getTotalAP(playerData)
return playerData.level - 1
end
-- returns the exp granted from a quest at a specific level
function module.getQuestGoldFromLevel(questLevel)
return 100 + math.floor(questLevel ^ 1.18 * 300)
end
-- returns the exp needed to gain the level above the given
function module.getEXPToNextLevel(currentLevel)
return module.getEXPForLevel(currentLevel + 1)
end
-- returns the exp granted from a quest at a specific level
function module.getQuestEXPFromLevel(questLevel)
return 10 + (module.getEXPToNextLevel(questLevel) * (1/1.5) * questLevel^(-1/6))
end
function module.getMonsterEXPFromLevel(questLevel)
local killsToLevel = 7 * (1 + questLevel^1.21 - questLevel^1.1)
return module.getEXPToNextLevel(questLevel) * killsToLevel^-1
end
-- let andrew decide whatever
function module.getBaseStatInfoForMonster(monsterLevel)
monsterLevel = 0--monsterLevel or 1
return {
str = monsterLevel * 1;
int = monsterLevel * 1;
dex = monsterLevel * 1;
vit = monsterLevel * 1;
}
end
-- returns main stat and cost of equipment based on the itemBaseData
function module.getEquipmentInfo(itemBaseData)
if itemBaseData then
local level = itemBaseData.level or itemBaseData.minLevel
if level then
local stat = getStatForLevel(level)
-- local stat = 0.009*level^2 + 3*level + 12
-- me: can we get good cost algorithm
-- mom: we have good cost algorithm at home
-- cost algorithm at home:
local function sig(x)
local e = 2.7182818284590452353602874713527
return 15 / (1 + e^(-1 * (0.25 * x - 9)))
end
local cost = 1.35 * module.getQuestGoldFromLevel(level) * level^(1/3) * math.max(sig(level), 1)
local rarity = itemBaseData.rarity or "Common"
if rarity == "Legendary" then
cost = cost * 2
elseif rarity == "Rare" then
cost = cost * 1.5
end
local modifierData
if itemBaseData.equipmentSlot then
if itemBaseData.equipmentSlot == 1 then
-- weapons
local damage = stat
cost = cost * 0.7
if rarity == "Legendary" then
damage = damage + 10
elseif rarity == "Rare" then
damage = damage + 5
end
return {damage = math.ceil(damage); cost = math.floor(cost); }
elseif itemBaseData.equipmentSlot == 11 then
return {cost = math.floor(cost * 0.6)}
else
local statUpgrade
-- armor
local defense
if itemBaseData.equipmentSlot == 8 then
-- body
defense = stat
if rarity == "Legendary" then
defense = defense + 10
elseif rarity == "Rare" then
defense = defense + 5
end
cost = cost * 1
defense = defense * (itemBaseData.defenseModifier or 1)
elseif itemBaseData.equipmentSlot == 9 then
-- lower
defense = 0
cost = cost * 0.35
elseif itemBaseData.equipmentSlot == 2 then
-- hat
defense = 0
cost = cost * 0.5
local value = stat/5
local distribution = itemBaseData.statDistribution
if itemBaseData.minimumClass == "hunter" then
distribution = distribution or {
str = 0;
dex = 1;
int = 0;
vit = 0;
}
statUpgrade = {
str = 0;
dex = 1;
int = 0;
vit = 0;
}
elseif itemBaseData.minimumClass == "warrior" then
distribution = distribution or {
str = 1;
dex = 0;
int = 0;
vit = 0;
}
statUpgrade = {
str = 1;
dex = 0;
int = 0;
vit = 0;
}
elseif itemBaseData.minimumClass == "mage" then
distribution = distribution or {
str = 0;
dex = 0;
int = 1;
vit = 0;
}
statUpgrade = {
str = 0;
dex = 0;
int = 1;
vit = 0;
}
end
if distribution then
modifierData = {}
for stat, coefficient in pairs(distribution) do
modifierData[stat] = math.floor(value * coefficient)
end
end
-- modifierData = {int = math.floor(value)}
end
if defense then
return {defense = math.ceil(defense); cost = math.floor(cost); modifierData = modifierData; statUpgrade = statUpgrade}
end
return false
end
end
end
end
return false
end
function module.getPlayerTickHealing(player)
if player and player.Character and player:FindFirstChild("level") and player.Character.PrimaryPart then
local level = player.level.Value
local vit = player.vit.Value
return (0.24 * level) + (0.1 * vit)
end
return 0
end
-- warning: this is just base crit chance. Doesn't include bonus crit chance from equipment
function module.calculateCritChance(dex, playerLevel)
return 0 --math.clamp(0.4 * (dex / (3 * playerLevel)), 0, 1)
end
function module.getPlayerCritChance(player)
if runService:IsServer() then
local playerData = network:invoke("getPlayerData", player)
if playerData then
return module.calculateCritChance(
playerData.nonSerializeData.statistics_final.dex,
playerData.level
) + (playerData.nonSerializeData.statistics_final.criticalStrikeChance or 0)
end
else
warn("attempt to call getPlayerCritChance on client")
end
return 0
end
function module.getAttackSpeed(dex)
return dex * 0.5 / 2
end
function module.getMonsterGoldForLevel(level)
return 10 + (3 * (level - 1))
end
function module.getStatPointsForLevel(level)
return 3 * (level-1)
end
-- returns the level associated with the exp
function module.getLevelForEXP(exp)
return math.floor((5 * exp / 10) ^ (1 / 3))
end
-- returns how much exp you are past the exp required to earn your current level
function module.getEXPPastCurrentLevel(currentEXP)
return currentEXP
--return currentEXP - module.getEXPForLevel(math.floor(module.getLevelForEXP(currentEXP)))
end
-- returns fraction of how close you are until next level
function module.getFractionForNextLevel(currentEXP)
return module.getEXPPastCurrentLevel(currentEXP) / module.getEXPToNextLevel(math.floor(module.getLevelForEXP(currentEXP)))
end
return module | 412 | 0.79872 | 1 | 0.79872 | game-dev | MEDIA | 0.948839 | game-dev | 0.912386 | 1 | 0.912386 |
EternityX/DEADCELL-CSGO | 1,448 | csgo/hooking/hooks/FrameStageNotify.cpp | #include "../../inc.h"
#include "../../features/misc/misc.h"
#include "../../features/anti-aim/antiaim.h"
#include "../../features/animations/anim.h"
#include "../../features/resolver/resolver.h"
#include "../../features/visuals/visuals.h"
#include "../../features/backtrack/backtrack.h"
#include "../../features/entity listener/ent_listener.h"
void __fastcall hook::FrameStageNotify( uintptr_t ecx, uintptr_t edx, client_frame_stage_t curstage ) {
g_misc.no_smoke( curstage );
if ( g_cl.m_should_update_materials ) {
g_misc.transparent_props( );
}
switch ( curstage ) {
case FRAME_RENDER_START: {
const auto in_thirdperson = g_csgo.m_input->m_camera_in_thirdperson;
if ( in_thirdperson && g_vars.antiaim.enabled ) {
g_csgo.m_prediction->set_local_viewangles( g_antiaim.m_real );
}
g_misc.flashlight( );
}
case FRAME_NET_UPDATE_POSTDATAUPDATE_START: {
g_resolver.frame_stage_notify( );
}
}
g_hooks.m_client.get_old_method< fn::FrameStageNotify_t >( hook::idx::FRAME_STAGE_NOTIFY )( ecx, curstage );
switch ( curstage ) {
case FRAME_NET_UPDATE_POSTDATAUPDATE_START: {
auto local = c_csplayer::get_local( );
if ( local )
local->flash_alpha( ) = g_vars.visuals.misc.no_flash ? 0.f : 255.f;
}
case FRAME_NET_UPDATE_END: {
if ( g_vars.rage.enabled ) {
if ( g_cl.m_local && g_cl.m_local->alive( ) ) {
g_backtrack.log( );
}
else {
g_backtrack.reset( );
}
}
}
}
}
| 412 | 0.94301 | 1 | 0.94301 | game-dev | MEDIA | 0.458112 | game-dev | 0.863 | 1 | 0.863 |
cataclysmbnteam/Cataclysm-BN | 61,414 | src/martialarts.cpp | #include "martialarts.h"
#include <algorithm>
#include <cstdlib>
#include <iterator>
#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include "avatar.h"
#include "character.h"
#include "character_martial_arts.h"
#include "color.h"
#include "cursesdef.h"
#include "damage.h"
#include "debug.h"
#include "effect.h"
#include "enums.h"
#include "generic_factory.h"
#include "generic_readers.h"
#include "input.h"
#include "item.h"
#include "item_factory.h"
#include "itype.h"
#include "json.h"
#include "map.h"
#include "messages.h"
#include "mutation.h"
#include "output.h"
#include "pimpl.h"
#include "player.h"
#include "pldata.h"
#include "point.h"
#include "skill.h"
#include "string_formatter.h"
#include "string_id.h"
#include "string_utils.h"
#include "translations.h"
#include "ui_manager.h"
#include "value_ptr.h"
static const skill_id skill_unarmed( "unarmed" );
static const bionic_id bio_armor_arms( "bio_armor_arms" );
static const bionic_id bio_armor_legs( "bio_armor_legs" );
static const bionic_id bio_cqb( "bio_cqb" );
static const flag_id json_flag_UNARMED_WEAPON( "UNARMED_WEAPON" );
namespace
{
generic_factory<weapon_category> weapon_category_factory( "weapon category" );
generic_factory<ma_technique> ma_techniques( "martial art technique" );
generic_factory<martialart> martialarts( "martial art style" );
generic_factory<ma_buff> ma_buffs( "martial art buff" );
} // namespace
template<>
const weapon_category &weapon_category_id::obj() const
{
return weapon_category_factory.obj( *this );
}
/** @relates string_id */
template<>
bool weapon_category_id::is_valid() const
{
return weapon_category_factory.is_valid( *this );
}
void weapon_category::load_weapon_categories( const JsonObject &jo, const std::string &src )
{
weapon_category_factory.load( jo, src );
}
void weapon_category::reset()
{
weapon_category_factory.reset();
}
void weapon_category::load( const JsonObject &jo, const std::string & )
{
mandatory( jo, was_loaded, "name", name_ );
}
const std::vector<weapon_category> &weapon_category::get_all()
{
return weapon_category_factory.get_all();
}
matype_id martial_art_learned_from( const itype &type )
{
if( !type.can_use( "MA_MANUAL" ) ) {
return {};
}
if( !type.book || type.book->martial_art.is_null() ) {
debugmsg( "Item '%s' which claims to teach a martial art is missing martial_art",
type.get_id().str() );
return {};
}
return type.book->martial_art;
}
void load_technique( const JsonObject &jo, const std::string &src )
{
ma_techniques.load( jo, src );
}
// To avoid adding empty entries
template <typename Container>
void add_if_exists( const JsonObject &jo, Container &cont, bool was_loaded,
const std::string &json_key, const typename Container::key_type &id )
{
if( jo.has_member( json_key ) ) {
mandatory( jo, was_loaded, json_key, cont[id] );
}
}
class ma_skill_reader : public generic_typed_reader<ma_skill_reader>
{
public:
std::pair<skill_id, int> get_next( JsonIn &jin ) const {
JsonObject jo = jin.get_object();
return std::pair<skill_id, int>( skill_id( jo.get_string( "name" ) ), jo.get_int( "level" ) );
}
template<typename C>
void erase_next( JsonIn &jin, C &container ) const {
const skill_id id = skill_id( jin.get_string() );
reader_detail::handler<C>().erase_if( container, [&id]( const std::pair<skill_id, int> &e ) {
return e.first == id;
} );
}
};
class ma_weapon_damage_reader : public generic_typed_reader<ma_weapon_damage_reader>
{
public:
std::map<std::string, damage_type> dt_map = get_dt_map();
std::pair<damage_type, int> get_next( JsonIn &jin ) const {
JsonObject jo = jin.get_object();
std::string type = jo.get_string( "type" );
const auto iter = get_dt_map().find( type );
if( iter == get_dt_map().end() ) {
jo.throw_error( "Invalid damage type" );
}
const damage_type dt = iter->second;
return std::pair<damage_type, int>( dt, jo.get_int( "min" ) );
}
template<typename C>
void erase_next( JsonIn &jin, C &container ) const {
JsonObject jo = jin.get_object();
std::string type = jo.get_string( "type" );
const auto iter = get_dt_map().find( type );
if( iter == get_dt_map().end() ) {
jo.throw_error( "Invalid damage type" );
}
damage_type id = iter->second;
reader_detail::handler<C>().erase_if( container, [&id]( const std::pair<damage_type, int> &e ) {
return e.first == id;
} );
}
};
void ma_requirements::load( const JsonObject &jo, const std::string & )
{
optional( jo, was_loaded, "unarmed_allowed", unarmed_allowed, false );
optional( jo, was_loaded, "melee_allowed", melee_allowed, false );
optional( jo, was_loaded, "unarmed_weapons_allowed", unarmed_weapons_allowed, true );
optional( jo, was_loaded, "strictly_unarmed", strictly_unarmed, false );
optional( jo, was_loaded, "wall_adjacent", wall_adjacent, false );
optional( jo, was_loaded, "req_buffs", req_buffs, auto_flags_reader<mabuff_id> {} );
optional( jo, was_loaded, "req_flags", req_flags, auto_flags_reader<flag_id> {} );
optional( jo, was_loaded, "skill_requirements", min_skill, ma_skill_reader {} );
optional( jo, was_loaded, "weapon_damage_requirements", min_damage, ma_weapon_damage_reader {} );
optional( jo, was_loaded, "weapon_categories_allowed", weapon_categories_allowed,
auto_flags_reader<weapon_category_id> {} );
optional( jo, was_loaded, "mutations_required", mutations_required, auto_flags_reader<trait_id> {} );
}
void ma_technique::load( const JsonObject &jo, const std::string &src )
{
mandatory( jo, was_loaded, "name", name );
optional( jo, was_loaded, "description", description, "" );
if( jo.has_member( "messages" ) ) {
JsonArray jsarr = jo.get_array( "messages" );
avatar_message = jsarr.get_string( 0 );
npc_message = jsarr.get_string( 1 );
}
optional( jo, was_loaded, "crit_tec", crit_tec, false );
optional( jo, was_loaded, "crit_ok", crit_ok, false );
optional( jo, was_loaded, "downed_target", downed_target, false );
optional( jo, was_loaded, "stunned_target", stunned_target, false );
optional( jo, was_loaded, "wall_adjacent", wall_adjacent, false );
optional( jo, was_loaded, "human_target", human_target, false );
optional( jo, was_loaded, "defensive", defensive, false );
optional( jo, was_loaded, "disarms", disarms, false );
optional( jo, was_loaded, "take_weapon", take_weapon, false );
optional( jo, was_loaded, "side_switch", side_switch, false );
optional( jo, was_loaded, "dummy", dummy, false );
optional( jo, was_loaded, "dodge_counter", dodge_counter, false );
optional( jo, was_loaded, "block_counter", block_counter, false );
optional( jo, was_loaded, "miss_recovery", miss_recovery, false );
optional( jo, was_loaded, "grab_break", grab_break, false );
optional( jo, was_loaded, "weighting", weighting, 1 );
optional( jo, was_loaded, "down_dur", down_dur, 0 );
optional( jo, was_loaded, "stun_dur", stun_dur, 0 );
optional( jo, was_loaded, "knockback_dist", knockback_dist, 0 );
optional( jo, was_loaded, "knockback_spread", knockback_spread, 0 );
optional( jo, was_loaded, "powerful_knockback", powerful_knockback, false );
optional( jo, was_loaded, "knockback_follow", knockback_follow, false );
optional( jo, was_loaded, "aoe", aoe, "" );
optional( jo, was_loaded, "flags", flags, auto_flags_reader<> {} );
reqs.load( jo, src );
bonuses.load( jo );
}
// Not implemented on purpose (martialart objects have no integer id)
// int_id<T> string_id<mabuff>::id() const;
/** @relates string_id */
template<>
const ma_technique &string_id<ma_technique>::obj() const
{
return ma_techniques.obj( *this );
}
/** @relates string_id */
template<>
bool string_id<ma_technique>::is_valid() const
{
return ma_techniques.is_valid( *this );
}
void ma_buff::load( const JsonObject &jo, const std::string &src )
{
mandatory( jo, was_loaded, "name", name );
mandatory( jo, was_loaded, "description", description );
optional( jo, was_loaded, "buff_duration", buff_duration, 2_turns );
optional( jo, was_loaded, "max_stacks", max_stacks, 1 );
optional( jo, was_loaded, "bonus_dodges", dodges_bonus, 0 );
optional( jo, was_loaded, "bonus_blocks", blocks_bonus, 0 );
optional( jo, was_loaded, "quiet", quiet, false );
optional( jo, was_loaded, "throw_immune", throw_immune, false );
optional( jo, was_loaded, "stealthy", stealthy, false );
reqs.load( jo, src );
bonuses.load( jo );
}
// Not implemented on purpose (martialart objects have no integer id)
// int_id<T> string_id<mabuff>::id() const;
/** @relates string_id */
template<>
const ma_buff &string_id<ma_buff>::obj() const
{
return ma_buffs.obj( *this );
}
/** @relates string_id */
template<>
bool string_id<ma_buff>::is_valid() const
{
return ma_buffs.is_valid( *this );
}
void load_martial_art( const JsonObject &jo, const std::string &src )
{
martialarts.load( jo, src );
}
class ma_buff_reader : public generic_typed_reader<ma_buff_reader>
{
public:
mabuff_id get_next( JsonIn &jin ) const {
if( jin.test_string() ) {
return mabuff_id( jin.get_string() );
}
JsonObject jsobj = jin.get_object();
ma_buffs.load( jsobj, "" );
return mabuff_id( jsobj.get_string( "id" ) );
}
};
void martialart::load( const JsonObject &jo, const std::string & )
{
mandatory( jo, was_loaded, "name", name );
mandatory( jo, was_loaded, "description", description );
mandatory( jo, was_loaded, "initiate", initiate );
for( JsonArray skillArray : jo.get_array( "autolearn" ) ) {
std::string skill_name = skillArray.get_string( 0 );
int skill_level = 0;
std::string skill_level_string = skillArray.get_string( 1 );
skill_level = stoi( skill_level_string );
autolearn_skills.emplace_back( skill_name, skill_level );
}
optional( jo, was_loaded, "primary_skill", primary_skill, skill_id( "unarmed" ) );
optional( jo, was_loaded, "learn_difficulty", learn_difficulty );
optional( jo, was_loaded, "static_buffs", static_buffs, ma_buff_reader{} );
optional( jo, was_loaded, "onmove_buffs", onmove_buffs, ma_buff_reader{} );
optional( jo, was_loaded, "onpause_buffs", onpause_buffs, ma_buff_reader{} );
optional( jo, was_loaded, "onhit_buffs", onhit_buffs, ma_buff_reader{} );
optional( jo, was_loaded, "onattack_buffs", onattack_buffs, ma_buff_reader{} );
optional( jo, was_loaded, "ondodge_buffs", ondodge_buffs, ma_buff_reader{} );
optional( jo, was_loaded, "onblock_buffs", onblock_buffs, ma_buff_reader{} );
optional( jo, was_loaded, "ongethit_buffs", ongethit_buffs, ma_buff_reader{} );
optional( jo, was_loaded, "onmiss_buffs", onmiss_buffs, ma_buff_reader{} );
optional( jo, was_loaded, "oncrit_buffs", oncrit_buffs, ma_buff_reader{} );
optional( jo, was_loaded, "onkill_buffs", onkill_buffs, ma_buff_reader{} );
optional( jo, was_loaded, "techniques", techniques, auto_flags_reader<matec_id> {} );
optional( jo, was_loaded, "weapons", weapons, auto_flags_reader<itype_id> {} );
optional( jo, was_loaded, "weapon_category", weapon_category, auto_flags_reader<weapon_category_id> {} );
optional( jo, was_loaded, "mutation", mutation, auto_flags_reader<trait_id> {} );
optional( jo, was_loaded, "strictly_melee", strictly_melee, false );
optional( jo, was_loaded, "strictly_unarmed", strictly_unarmed, false );
optional( jo, was_loaded, "allow_melee", allow_melee, false );
optional( jo, was_loaded, "force_unarmed", force_unarmed, false );
optional( jo, was_loaded, "leg_block", leg_block, 99 );
optional( jo, was_loaded, "arm_block", arm_block, 99 );
optional( jo, was_loaded, "arm_block_with_bio_armor_arms", arm_block_with_bio_armor_arms, false );
optional( jo, was_loaded, "leg_block_with_bio_armor_legs", leg_block_with_bio_armor_legs, false );
}
// Not implemented on purpose (martialart objects have no integer id)
// int_id<T> string_id<martialart>::id() const;
/** @relates string_id */
template<>
const martialart &string_id<martialart>::obj() const
{
return martialarts.obj( *this );
}
/** @relates string_id */
template<>
bool string_id<martialart>::is_valid() const
{
return martialarts.is_valid( *this );
}
std::vector<matype_id> all_martialart_types()
{
std::vector<matype_id> result;
for( const auto &ma : martialarts.get_all() ) {
result.push_back( ma.id );
}
return result;
}
std::vector<matype_id> autolearn_martialart_types()
{
std::vector<matype_id> result;
for( const auto &ma : martialarts.get_all() ) {
if( ma.autolearn_skills.empty() ) {
continue;
}
result.push_back( ma.id );
}
return result;
}
static void check( const ma_requirements &req, const std::string &display_text )
{
for( auto &r : req.req_buffs ) {
if( !r.is_valid() ) {
debugmsg( "ma buff %s of %s does not exist", r.c_str(), display_text );
}
}
}
void check_martialarts()
{
for( const auto &ma : martialarts.get_all() ) {
for( auto technique = ma.techniques.cbegin();
technique != ma.techniques.cend(); ++technique ) {
if( !technique->is_valid() ) {
debugmsg( "Technique with id %s in style %s doesn't exist.",
technique->c_str(), ma.name );
}
}
for( const itype_id &weapon : ma.weapons ) {
if( !weapon.is_valid() ) {
debugmsg( "Weapon %s in style %s doesn't exist.", weapon, ma.name );
}
}
for( const weapon_category_id &weap_cat : ma.weapon_category ) {
if( !weap_cat.is_valid() ) {
debugmsg( "Weapon category %s in style %s is invalid.", weap_cat.c_str(), ma.name );
}
}
for( const trait_id &mut : ma.mutation ) {
if( !mut.is_valid() ) {
debugmsg( "Mutation %s in style %s is invalid.", mut.c_str(), ma.name );
}
}
}
for( const auto &t : ma_techniques.get_all() ) {
::check( t.reqs, string_format( "technique %s", t.id.c_str() ) );
}
for( const auto &b : ma_buffs.get_all() ) {
::check( b.reqs, string_format( "buff %s", b.id.c_str() ) );
}
}
/**
* This is a wrapper class to get access to the protected members of effect_type, it creates
* the @ref effect_type that is used to store a @ref ma_buff in the creatures effect map.
* Note: this class must not contain any new members, it will be converted to a plain
* effect_type later and that would slice the new members of.
*/
class ma_buff_effect_type : public effect_type
{
public:
ma_buff_effect_type( const ma_buff &buff ) {
id = buff.get_effect_id();
max_intensity = buff.max_stacks;
// add_effect add the duration to an existing effect, but it must never be
// above buff_duration, this keeps the old ma_buff behavior
max_duration = buff.buff_duration;
dur_add_perc = 100;
// each add_effect call increases the intensity by 1
int_add_val = 1;
// effect intensity increases by -1 each turn.
int_decay_step = -1;
int_decay_tick = 1;
int_dur_factor = 0_turns;
name.push_back( to_translation( buff.name ) );
desc.push_back( buff.description );
rating = e_good;
}
};
void finialize_martial_arts()
{
// This adds an effect type for each ma_buff, so we can later refer to it and don't need a
// redundant definition of those effects in json.
for( const auto &buff : ma_buffs.get_all() ) {
const ma_buff_effect_type new_eff( buff );
// Note the slicing here: new_eff is converted to a plain effect_type, but this doesn't
// bother us because ma_buff_effect_type does not have any members that can be sliced.
effect_type::register_ma_buff_effect( new_eff );
}
}
std::string martialart_difficulty( const matype_id &mstyle )
{
std::string diff;
if( mstyle->learn_difficulty <= 2 ) {
diff = _( "easy" );
} else if( mstyle->learn_difficulty <= 4 ) {
diff = _( "moderately hard" );
} else if( mstyle->learn_difficulty <= 6 ) {
diff = _( "hard" );
} else if( mstyle->learn_difficulty <= 8 ) {
diff = _( "very hard" );
} else {
diff = _( "extremely hard" );
}
return diff;
}
void clear_techniques_and_martial_arts()
{
martialarts.reset();
ma_buffs.reset();
ma_techniques.reset();
}
bool ma_requirements::is_valid_character( const Character &u ) const
{
for( const mabuff_id &buff_id : req_buffs ) {
if( !u.has_mabuff( buff_id ) ) {
return false;
}
}
//A technique is valid if it applies to unarmed strikes, if it applies generally
//to all weapons (such as Ninjutsu sneak attacks or innate weapon techniques like RAPID)
//or if the weapon is flagged as being compatible with the style. Some techniques have
//further restrictions on required weapon properties (is_valid_weapon).
bool cqb = u.has_active_bionic( bio_cqb );
// There are 4 different cases of "armedness":
// Truly unarmed, unarmed weapon, style-allowed weapon, generic weapon
bool melee_style = u.martial_arts_data->selected_strictly_melee();
bool is_armed = u.is_armed();
bool unarmed_weapon = is_armed && u.primary_weapon().has_flag( json_flag_UNARMED_WEAPON );
bool forced_unarmed = u.martial_arts_data->selected_force_unarmed();
bool weapon_ok = is_valid_weapon( u.primary_weapon() );
bool style_weapon = u.martial_arts_data->selected_has_weapon( u.primary_weapon().typeId() );
bool all_weapons = u.martial_arts_data->selected_allow_melee();
std::set<trait_id> style_muts = u.martial_arts_data->selected_mutations();
bool unarmed_ok = !is_armed || ( unarmed_weapon && unarmed_weapons_allowed );
bool melee_ok = melee_allowed && weapon_ok && ( style_weapon || all_weapons );
bool valid_unarmed = !melee_style && unarmed_allowed && unarmed_ok;
bool valid_melee = !strictly_unarmed && ( forced_unarmed || melee_ok );
if( !valid_unarmed && !valid_melee ) {
return false;
}
if( !style_muts.empty() ) {
bool valid_mut = false;
for( const trait_id &mut : style_muts ) {
if( u.has_trait( mut ) ) {
valid_mut = true;
}
}
if( !valid_mut ) {
return false;
}
}
if( wall_adjacent && !get_map().is_wall_adjacent( u.pos() ) ) {
return false;
}
for( const auto &pr : min_skill ) {
if( ( cqb ? 5 : u.get_skill_level( pr.first ) ) < pr.second ) {
return false;
}
}
if( !weapon_categories_allowed.empty() && is_armed ) {
bool valid_weap_cat = false;
for( const weapon_category_id &w_cat : weapon_categories_allowed ) {
if( u.used_weapon().typeId()->weapon_category.contains( w_cat ) ) {
valid_weap_cat = true;
}
}
if( !valid_weap_cat ) {
return false;
}
}
if( !mutations_required.empty() ) {
bool valid_mut = false;
for( const trait_id &mut : mutations_required ) {
if( u.has_trait( mut ) ) {
valid_mut = true;
}
}
if( !valid_mut ) {
return false;
}
}
return true;
}
bool ma_requirements::is_valid_weapon( const item &i ) const
{
for( const flag_id &flag : req_flags ) {
if( !i.has_flag( flag ) ) {
return false;
}
}
for( const auto &pr : min_damage ) {
if( i.damage_melee( pr.first ) < pr.second ) {
return false;
}
}
return true;
}
std::string ma_requirements::get_description( bool buff ) const
{
std::string dump;
if( std::any_of( min_skill.begin(), min_skill.end(), []( const std::pair<skill_id, int> &pr ) {
return pr.second > 0;
} ) ) {
dump += string_format( _( "<bold>%s required: </bold>" ),
vgettext( "Skill", "Skills", min_skill.size() ) );
dump += enumerate_as_string( min_skill.begin(),
min_skill.end(), []( const std::pair<skill_id, int> &pr ) {
int player_skill = get_player_character().get_skill_level( skill_id( pr.first ) );
if( get_player_character().has_active_bionic( bio_cqb ) ) {
player_skill = BIO_CQB_LEVEL;
}
return string_format( "%s: <stat>%d</stat>/<stat>%d</stat>", pr.first->name(), player_skill,
pr.second );
}, enumeration_conjunction::none ) + "\n";
}
if( std::any_of( min_damage.begin(),
min_damage.end(), []( const std::pair<damage_type, int> &pr ) {
return pr.second > 0;
} ) ) {
dump += vgettext( "<bold>Damage type required: </bold>",
"<bold>Damage types required: </bold>", min_damage.size() );
dump += enumerate_as_string( min_damage.begin(),
min_damage.end(), []( const std::pair<damage_type, int> &pr ) {
return string_format( _( "%s: <stat>%d</stat>" ), name_by_dt( pr.first ), pr.second );
}, enumeration_conjunction::none ) + "\n";
}
if( !weapon_categories_allowed.empty() ) {
dump += vgettext( "<bold>Weapon category required: </bold>",
"<bold>Weapon categories required: </bold>", weapon_categories_allowed.size() );
dump += enumerate_as_string( weapon_categories_allowed.begin(),
weapon_categories_allowed.end(), []( const weapon_category_id & w_cat ) {
if( !w_cat.is_valid() ) {
return w_cat.str();
}
return w_cat->name().translated();
} ) + "\n";
}
if( !mutations_required.empty() ) {
dump += vgettext( "<bold>Mutation required: </bold>",
"<bold>Mutations required: </bold>", mutations_required.size() );
dump += enumerate_as_string( mutations_required.begin(),
mutations_required.end(), []( const trait_id & mut ) {
if( !mut.is_valid() ) {
return mut.str();
}
return mut->name();
} ) + "\n";
}
if( !req_buffs.empty() ) {
dump += _( "<bold>Requires:</bold> " );
dump += enumerate_as_string( req_buffs.begin(), req_buffs.end(), []( const mabuff_id & bid ) {
return _( bid->name );
}, enumeration_conjunction::none ) + "\n";
}
const std::string type = buff ? _( "activate" ) : _( "be used" );
if( unarmed_allowed && melee_allowed ) {
dump += string_format( _( "* Can %s while <info>armed</info> or <info>unarmed</info>" ),
type ) + "\n";
if( unarmed_weapons_allowed ) {
dump += string_format( _( "* Can %s while using <info>any unarmed weapon</info>" ),
type ) + "\n";
}
} else if( unarmed_allowed ) {
dump += string_format( _( "* Can <info>only</info> %s while <info>unarmed</info>" ),
type ) + "\n";
if( unarmed_weapons_allowed ) {
dump += string_format( _( "* Can %s while using <info>any unarmed weapon</info>" ),
type ) + "\n";
}
} else if( melee_allowed ) {
dump += string_format( _( "* Can <info>only</info> %s while <info>armed</info>" ),
type ) + "\n";
}
if( wall_adjacent ) {
dump += string_format( _( "* Can %s while <info>near</info> to a <info>wall</info>" ),
type ) + "\n";
}
return dump;
}
ma_technique::ma_technique()
{
crit_tec = false;
crit_ok = false;
defensive = false;
side_switch = false; // moves the target behind user
dummy = false;
down_dur = 0;
stun_dur = 0;
knockback_dist = 0;
knockback_spread = 0; // adding randomness to knockback, like tec_throw
powerful_knockback = false;
knockback_follow = false; // player follows the knocked-back party into their former tile
// offensive
disarms = false; // like tec_disarm
take_weapon = false; // disarms and equips weapon if hands are free
dodge_counter = false; // like tec_grab
block_counter = false; // like tec_counter
// conditional
downed_target = false; // only works on downed enemies
stunned_target = false; // only works on stunned enemies
wall_adjacent = false; // only works near a wall
human_target = false; // only works on humanoid enemies
miss_recovery = false; // allows free recovery from misses, like tec_feint
grab_break = false; // allows grab_breaks, like tec_break
}
bool ma_technique::is_valid_character( const Character &u ) const
{
return reqs.is_valid_character( u );
}
ma_buff::ma_buff()
: buff_duration( 1_turns )
{
max_stacks = 1; // total number of stacks this buff can have
dodges_bonus = 0; // extra dodges, like karate
blocks_bonus = 0; // extra blocks, like karate
throw_immune = false;
}
efftype_id ma_buff::get_effect_id() const
{
return efftype_id( std::string( "mabuff:" ) + id.str() );
}
const ma_buff *ma_buff::from_effect( const effect &eff )
{
const std::string &id = eff.get_effect_type()->id.str();
// Same as in get_effect_id!
if( !id.starts_with( "mabuff:" ) ) {
return nullptr;
}
return &mabuff_id( id.substr( 7 ) ).obj();
}
void ma_buff::apply_buff( Character &u ) const
{
u.add_effect( get_effect_id(), time_duration::from_turns( buff_duration ) );
}
bool ma_buff::is_valid_character( const Character &u ) const
{
return reqs.is_valid_character( u );
}
void ma_buff::apply_character( Character &u ) const
{
u.mod_num_dodges_bonus( dodges_bonus );
u.set_num_blocks_bonus( u.get_num_blocks_bonus() + blocks_bonus );
}
int ma_buff::hit_bonus( const Character &u ) const
{
return bonuses.get_flat( u, affected_stat::HIT );
}
int ma_buff::dodge_bonus( const Character &u ) const
{
return bonuses.get_flat( u, affected_stat::DODGE );
}
int ma_buff::block_bonus( const Character &u ) const
{
return bonuses.get_flat( u, affected_stat::BLOCK );
}
int ma_buff::arpen_bonus( const Character &u, damage_type dt ) const
{
return bonuses.get_flat( u, affected_stat::ARMOR_PENETRATION, dt );
}
int ma_buff::speed_bonus( const Character &u ) const
{
return bonuses.get_flat( u, affected_stat::SPEED );
}
int ma_buff::armor_bonus( const Character &guy, damage_type dt ) const
{
return bonuses.get_flat( guy, affected_stat::ARMOR, dt );
}
float ma_buff::damage_bonus( const Character &u, damage_type dt ) const
{
return bonuses.get_flat( u, affected_stat::DAMAGE, dt );
}
float ma_buff::damage_mult( const Character &u, damage_type dt ) const
{
return bonuses.get_mult( u, affected_stat::DAMAGE, dt );
}
float ma_buff::tg_armor_mult( const Character &u, damage_type dt ) const
{
return bonuses.get_mult( u, affected_stat::TARGET_ARMOR_MULTIPLIER, dt );
}
bool ma_buff::is_throw_immune() const
{
return throw_immune;
}
bool ma_buff::is_quiet() const
{
return quiet;
}
bool ma_buff::is_stealthy() const
{
return stealthy;
}
std::string ma_buff::get_description( bool passive ) const
{
std::string dump;
dump += string_format( _( "<bold>Buff technique:</bold> %s" ), _( name ) ) + "\n";
std::string temp = bonuses.get_description();
if( !temp.empty() ) {
dump += string_format( _( "<bold>%s:</bold> " ),
vgettext( "Bonus", "Bonus/stack", max_stacks ) ) + "\n" + temp;
}
dump += reqs.get_description( true );
if( max_stacks > 1 ) {
dump += string_format( _( "* Will <info>stack</info> up to <stat>%d</stat> times" ),
max_stacks ) + "\n";
}
const int turns = to_turns<int>( buff_duration );
if( !passive && turns ) {
dump += string_format( _( "* Will <info>last</info> for <stat>%d %s</stat>" ),
turns, vgettext( "turn", "turns", turns ) ) + "\n";
}
if( dodges_bonus > 0 ) {
dump += string_format( _( "* Will give a <good>+%s</good> bonus to <info>dodge</info>%s" ),
dodges_bonus, vgettext( " for the stack", " per stack", max_stacks ) ) + "\n";
} else if( dodges_bonus < 0 ) {
dump += string_format( _( "* Will give a <bad>%s</bad> penalty to <info>dodge</info>%s" ),
dodges_bonus, vgettext( " for the stack", " per stack", max_stacks ) ) + "\n";
}
if( blocks_bonus > 0 ) {
dump += string_format( _( "* Will give a <good>+%s</good> bonus to <info>block</info>%s" ),
blocks_bonus, vgettext( " for the stack", " per stack", max_stacks ) ) + "\n";
} else if( blocks_bonus < 0 ) {
dump += string_format( _( "* Will give a <bad>%s</bad> penalty to <info>block</info>%s" ),
blocks_bonus, vgettext( " for the stack", " per stack", max_stacks ) ) + "\n";
}
if( quiet ) {
dump += _( "* Attacks will be completely <info>silent</info>" ) + std::string( "\n" );
}
if( stealthy ) {
dump += _( "* Movement will make <info>less noise</info>" ) + std::string( "\n" );
}
return dump;
}
martialart::martialart()
{
leg_block = -1;
arm_block = -1;
}
// simultaneously check and add all buffs. this is so that buffs that have
// buff dependencies added by the same event trigger correctly
static void simultaneous_add( Character &u, const std::vector<mabuff_id> &buffs )
{
std::vector<const ma_buff *> buffer; // hey get it because it's for buffs????
for( const mabuff_id &buffid : buffs ) {
const ma_buff &buff = buffid.obj();
if( buff.is_valid_character( u ) ) {
buffer.push_back( &buff );
}
}
for( auto &elem : buffer ) {
elem->apply_buff( u );
}
}
void martialart::apply_static_buffs( Character &u ) const
{
simultaneous_add( u, static_buffs );
}
void martialart::apply_onmove_buffs( Character &u ) const
{
simultaneous_add( u, onmove_buffs );
}
void martialart::apply_onpause_buffs( Character &u ) const
{
simultaneous_add( u, onpause_buffs );
}
void martialart::apply_onhit_buffs( Character &u ) const
{
simultaneous_add( u, onhit_buffs );
}
void martialart::apply_onattack_buffs( Character &u ) const
{
simultaneous_add( u, onattack_buffs );
}
void martialart::apply_ondodge_buffs( Character &u ) const
{
simultaneous_add( u, ondodge_buffs );
}
void martialart::apply_onblock_buffs( Character &u ) const
{
simultaneous_add( u, onblock_buffs );
}
void martialart::apply_ongethit_buffs( Character &u ) const
{
simultaneous_add( u, ongethit_buffs );
}
void martialart::apply_onmiss_buffs( Character &u ) const
{
simultaneous_add( u, onmiss_buffs );
}
void martialart::apply_oncrit_buffs( Character &u ) const
{
simultaneous_add( u, oncrit_buffs );
}
void martialart::apply_onkill_buffs( Character &u ) const
{
simultaneous_add( u, onkill_buffs );
}
bool martialart::has_technique( const Character &u, const matec_id &tec_id ) const
{
for( const matec_id &elem : techniques ) {
const ma_technique &tec = elem.obj();
if( tec.is_valid_character( u ) && tec.id == tec_id ) {
return true;
}
}
return false;
}
bool martialart::has_weapon( const itype_id &itt ) const
{
return weapons.contains( itt ) ||
std::any_of( itt->weapon_category.begin(), itt->weapon_category.end(),
[&]( const weapon_category_id & weap ) {
return weapon_category.contains( weap );
} );
}
bool martialart::weapon_valid( const item &it ) const
{
if( allow_melee ) {
return true;
}
if( it.is_null() && !strictly_melee ) {
return true;
}
if( has_weapon( it.typeId() ) ) {
return true;
}
if( !strictly_unarmed && !strictly_melee && !it.is_null() &&
it.has_flag( json_flag_UNARMED_WEAPON ) ) {
return true;
}
return false;
}
std::string martialart::get_initiate_avatar_message() const
{
return initiate[0];
}
std::string martialart::get_initiate_npc_message() const
{
return initiate[1];
}
// Player stuff
// technique
std::vector<matec_id> character_martial_arts::get_all_techniques( const item &weap ) const
{
std::vector<matec_id> tecs;
// Grab individual item techniques
const auto &weapon_techs = weap.get_techniques();
tecs.insert( tecs.end(), weapon_techs.begin(), weapon_techs.end() );
// and martial art techniques
const auto &style = style_selected.obj();
tecs.insert( tecs.end(), style.techniques.begin(), style.techniques.end() );
return tecs;
}
// defensive technique-related
bool character_martial_arts::has_miss_recovery_tec( const item &weap ) const
{
for( const matec_id &technique : get_all_techniques( weap ) ) {
if( technique->miss_recovery ) {
return true;
}
}
return false;
}
ma_technique character_martial_arts::get_miss_recovery_tec( const item &weap ) const
{
ma_technique tech;
for( const matec_id &technique : get_all_techniques( weap ) ) {
if( technique->miss_recovery ) {
tech = technique.obj();
break;
}
}
return tech;
}
// This one isn't used with a weapon
bool character_martial_arts::has_grab_break_tec() const
{
for( const matec_id &technique : get_all_techniques( null_item_reference() ) ) {
if( technique->grab_break ) {
return true;
}
}
return false;
}
ma_technique character_martial_arts::get_grab_break_tec( const item &weap ) const
{
ma_technique tec;
for( const matec_id &technique : get_all_techniques( weap ) ) {
if( technique->grab_break ) {
tec = technique.obj();
break;
}
}
return tec;
}
bool Character::can_use_grab_break_tec( const item &weap ) const
{
if( !has_grab_break_tec() ) {
return false;
}
ma_technique tec = martial_arts_data->get_grab_break_tec( weap );
return tec.is_valid_character( *this );
}
bool Character::can_miss_recovery( const item &weap ) const
{
if( !martial_arts_data->has_miss_recovery_tec( weap ) ) {
return false;
}
ma_technique tec = martial_arts_data->get_miss_recovery_tec( weap );
return tec.is_valid_character( *this );
}
bool character_martial_arts::can_leg_block( const Character &owner ) const
{
const martialart &ma = style_selected.obj();
///\EFFECT_UNARMED increases ability to perform leg block
int unarmed_skill = owner.has_active_bionic( bio_cqb ) ? 5 : owner.get_skill_level(
skill_unarmed );
// Success conditions.
if( owner.get_working_leg_count() >= 1 ) {
if( unarmed_skill >= ma.leg_block ) {
return true;
} else if( ma.leg_block_with_bio_armor_legs && owner.has_bionic( bio_armor_legs ) ) {
return true;
}
}
// if not above, can't block.
return false;
}
bool character_martial_arts::can_arm_block( const Character &owner ) const
{
const martialart &ma = style_selected.obj();
///\EFFECT_UNARMED increases ability to perform arm block
int unarmed_skill = owner.has_active_bionic( bio_cqb ) ? 5 : owner.get_skill_level(
skill_unarmed );
// Success conditions.
if( !owner.is_limb_broken( bodypart_id( "arm_l" ) ) ||
!owner.is_limb_broken( bodypart_id( "arm_r" ) ) ) {
if( unarmed_skill >= ma.arm_block ) {
return true;
} else if( ma.arm_block_with_bio_armor_arms && owner.has_bionic( bio_armor_arms ) ) {
return true;
}
}
// if not above, can't block.
return false;
}
bool character_martial_arts::can_limb_block( const Character &owner ) const
{
return can_arm_block( owner ) || can_leg_block( owner );
}
bool character_martial_arts::is_force_unarmed() const
{
return style_selected->force_unarmed;
}
// event handlers
void character_martial_arts::ma_static_effects( Character &owner )
{
style_selected->apply_static_buffs( owner );
}
void character_martial_arts::ma_onmove_effects( Character &owner )
{
style_selected->apply_onmove_buffs( owner );
}
void character_martial_arts::ma_onpause_effects( Character &owner )
{
style_selected->apply_onpause_buffs( owner );
}
void character_martial_arts::ma_onhit_effects( Character &owner )
{
style_selected->apply_onhit_buffs( owner );
}
void character_martial_arts::ma_onattack_effects( Character &owner )
{
style_selected->apply_onattack_buffs( owner );
}
void character_martial_arts::ma_ondodge_effects( Character &owner )
{
style_selected->apply_ondodge_buffs( owner );
}
void character_martial_arts::ma_onblock_effects( Character &owner )
{
style_selected->apply_onblock_buffs( owner );
}
void character_martial_arts::ma_ongethit_effects( Character &owner )
{
style_selected->apply_ongethit_buffs( owner );
}
void character_martial_arts::ma_onmiss_effects( Character &owner )
{
style_selected->apply_onmiss_buffs( owner );
}
void character_martial_arts::ma_oncrit_effects( Character &owner )
{
style_selected->apply_oncrit_buffs( owner );
}
void character_martial_arts::ma_onkill_effects( Character &owner )
{
style_selected->apply_onkill_buffs( owner );
}
template<typename C, typename F>
static void accumulate_ma_buff_effects( const C &container, F f )
{
for( auto &elem : container ) {
for( auto &eff : elem.second ) {
const effect &e = eff.second;
if( e.is_removed() ) {
continue;
}
if( auto buff = ma_buff::from_effect( e ) ) {
f( *buff, e );
}
}
}
}
template<typename C, typename F>
static bool search_ma_buff_effect( const C &container, F f )
{
for( auto &elem : container ) {
for( auto &eff : elem.second ) {
const effect &e = eff.second;
if( e.is_removed() ) {
continue;
}
if( auto buff = ma_buff::from_effect( e ) ) {
if( f( *buff, e ) ) {
return true;
}
}
}
}
return false;
}
// bonuses
float Character::mabuff_tohit_bonus() const
{
float ret = 0;
accumulate_ma_buff_effects( *effects, [&ret, this]( const ma_buff & b, const effect & ) {
ret += b.hit_bonus( *this );
} );
return ret;
}
float Character::mabuff_dodge_bonus() const
{
float ret = 0;
accumulate_ma_buff_effects( *effects, [&ret, this]( const ma_buff & b, const effect & d ) {
ret += d.get_intensity() * b.dodge_bonus( *this );
} );
return ret;
}
int Character::mabuff_block_bonus() const
{
int ret = 0;
accumulate_ma_buff_effects( *effects, [&ret, this]( const ma_buff & b, const effect & d ) {
ret += d.get_intensity() * b.block_bonus( *this );
} );
return ret;
}
int Character::mabuff_speed_bonus() const
{
int ret = 0;
accumulate_ma_buff_effects( *effects, [&ret, this]( const ma_buff & b, const effect & d ) {
ret += d.get_intensity() * b.speed_bonus( *this );
} );
return ret;
}
int Character::mabuff_arpen_bonus( damage_type type ) const
{
int ret = 0;
accumulate_ma_buff_effects( *effects, [&ret, type, this]( const ma_buff & b, const effect & d ) {
ret += d.get_intensity() * b.arpen_bonus( *this, type );
} );
return ret;
}
float Character::mabuff_tg_armor_mult( damage_type type ) const
{
float ret = 1.f;
accumulate_ma_buff_effects( *effects, [&ret, type, this]( const ma_buff & b, const effect & d ) {
// This is correct, so that a 20% buff (1.2) plus a 20% buff (1.2)
// becomes 1.4 instead of 2.4 (which would be a 240% buff)
ret *= d.get_intensity() * ( b.tg_armor_mult( *this, type ) - 1 ) + 1;
} );
return ret;
}
int Character::mabuff_armor_bonus( damage_type type ) const
{
int ret = 0;
accumulate_ma_buff_effects( *effects, [&ret, type, this]( const ma_buff & b, const effect & d ) {
ret += d.get_intensity() * b.armor_bonus( *this, type );
} );
return ret;
}
float Character::mabuff_damage_mult( damage_type type ) const
{
float ret = 1.f;
accumulate_ma_buff_effects( *effects, [&ret, type, this]( const ma_buff & b, const effect & d ) {
// This is correct, so that a 20% buff (1.2) plus a 20% buff (1.2)
// becomes 1.4 instead of 2.4 (which would be a 240% buff)
ret *= d.get_intensity() * ( b.damage_mult( *this, type ) - 1 ) + 1;
} );
return ret;
}
int Character::mabuff_damage_bonus( damage_type type ) const
{
int ret = 0;
accumulate_ma_buff_effects( *effects, [&ret, type, this]( const ma_buff & b, const effect & d ) {
ret += d.get_intensity() * b.damage_bonus( *this, type );
} );
return ret;
}
int Character::mabuff_attack_cost_penalty() const
{
int ret = 0;
accumulate_ma_buff_effects( *effects, [&ret, this]( const ma_buff & b, const effect & d ) {
ret += d.get_intensity() * b.bonuses.get_flat( *this, affected_stat::MOVE_COST );
} );
return ret;
}
float Character::mabuff_attack_cost_mult() const
{
float ret = 1.0f;
accumulate_ma_buff_effects( *effects, [&ret, this]( const ma_buff & b, const effect & d ) {
// This is correct, so that a 20% buff (1.2) plus a 20% buff (1.2)
// becomes 1.4 instead of 2.4 (which would be a 240% buff)
ret *= d.get_intensity() * ( b.bonuses.get_mult( *this,
affected_stat::MOVE_COST ) - 1 ) + 1;
} );
return ret;
}
bool Character::is_throw_immune() const
{
return search_ma_buff_effect( *effects, []( const ma_buff & b, const effect & ) {
return b.is_throw_immune();
} );
}
bool Character::is_quiet() const
{
return search_ma_buff_effect( *effects, []( const ma_buff & b, const effect & ) {
return b.is_quiet();
} );
}
bool Character::is_stealthy() const
{
return search_ma_buff_effect( *effects, []( const ma_buff & b, const effect & ) {
return b.is_stealthy();
} );
}
bool Character::has_mabuff( const mabuff_id &id ) const
{
return search_ma_buff_effect( *effects, [&id]( const ma_buff & b, const effect & ) {
return b.id == id;
} );
}
bool Character::has_grab_break_tec() const
{
return martial_arts_data->has_grab_break_tec();
}
bool character_martial_arts::has_martialart( const matype_id &ma ) const
{
return std::find( ma_styles.begin(), ma_styles.end(), ma ) != ma_styles.end();
}
void character_martial_arts::add_martialart( const matype_id &ma_id )
{
if( has_martialart( ma_id ) ) {
return;
}
ma_styles.emplace_back( ma_id );
}
bool can_autolearn_martial_art( const Character &who, const matype_id &ma_id )
{
if( ma_id.obj().autolearn_skills.empty() ) {
return false;
}
for( const std::pair<std::string, int> &elem : ma_id.obj().autolearn_skills ) {
const skill_id skill_req( elem.first );
const int required_level = elem.second;
if( required_level > who.get_skill_level( skill_req ) ) {
return false;
}
}
return true;
}
void character_martial_arts::martialart_use_message( const Character &owner ) const
{
martialart ma = style_selected.obj();
if( ma.force_unarmed || ma.weapon_valid( owner.primary_weapon() ) ) {
owner.add_msg_if_player( m_info, _( ma.get_initiate_avatar_message() ) );
} else if( ma.strictly_melee && !owner.is_armed() ) {
owner.add_msg_if_player( m_bad, _( "%s cannot be used unarmed." ), ma.name );
} else if( ma.strictly_unarmed && owner.is_armed() ) {
owner.add_msg_if_player( m_bad, _( "%s cannot be used with weapons." ), ma.name );
} else {
owner.add_msg_if_player( m_bad, _( "The %1$s is not a valid %2$s weapon." ), owner.primary_weapon()
.tname( 1, false ), ma.name );
}
}
float ma_technique::damage_bonus( const Character &u, damage_type type ) const
{
return bonuses.get_flat( u, affected_stat::DAMAGE, type );
}
float ma_technique::damage_multiplier( const Character &u, damage_type type ) const
{
return bonuses.get_mult( u, affected_stat::DAMAGE, type );
}
float ma_technique::move_cost_multiplier( const Character &u ) const
{
return bonuses.get_mult( u, affected_stat::MOVE_COST );
}
float ma_technique::move_cost_penalty( const Character &u ) const
{
return bonuses.get_flat( u, affected_stat::MOVE_COST );
}
float ma_technique::armor_penetration( const Character &u, damage_type type ) const
{
return bonuses.get_flat( u, affected_stat::ARMOR_PENETRATION, type );
}
std::string ma_technique::get_description() const
{
std::string dump;
std::string type;
if( block_counter ) {
type = _( "Block Counter" );
} else if( dodge_counter ) {
type = _( "Dodge Counter" );
} else if( miss_recovery ) {
type = _( "Miss Recovery" );
} else if( grab_break ) {
type = _( "Grab Break" );
} else if( defensive ) {
type = _( "Defensive" );
} else {
type = _( "Offensive" );
}
dump += string_format( _( "<bold>Type:</bold> %s" ), type ) + "\n";
std::string temp = bonuses.get_description();
if( !temp.empty() ) {
dump += _( "<bold>Bonus:</bold> " ) + std::string( "\n" ) + temp;
}
dump += reqs.get_description();
if( weighting > 1 ) {
dump += string_format( _( "* <info>Greater chance</info> to activate: <stat>+%s%%</stat>" ),
( 100 * ( weighting - 1 ) ) ) + "\n";
} else if( weighting < -1 ) {
dump += string_format( _( "* <info>Lower chance</info> to activate: <stat>1/%s</stat>" ),
std::abs( weighting ) ) + "\n";
}
if( crit_ok ) {
dump += _( "* Can activate on a <info>normal</info> or a <info>crit</info> hit" ) +
std::string( "\n" );
} else if( crit_tec ) {
dump += _( "* Will only activate on a <info>crit</info>" ) + std::string( "\n" );
}
if( side_switch ) {
dump += _( "* Moves target <info>behind</info> you" ) + std::string( "\n" );
}
if( wall_adjacent ) {
dump += _( "* Will only activate while <info>near</info> to a <info>wall</info>" ) +
std::string( "\n" );
}
if( downed_target ) {
dump += _( "* Only works on a <info>downed</info> target" ) + std::string( "\n" );
}
if( stunned_target ) {
dump += _( "* Only works on a <info>stunned</info> target" ) + std::string( "\n" );
}
if( human_target ) {
dump += _( "* Only works on a <info>humanoid</info> target" ) + std::string( "\n" );
}
if( powerful_knockback ) {
dump += _( "* Causes extra damage on <info>knockback collision</info>." ) + std::string( "\n" );
}
if( dodge_counter ) {
dump += _( "* Will <info>counterattack</info> when you <info>dodge</info>" ) + std::string( "\n" );
}
if( block_counter ) {
dump += _( "* Will <info>counterattack</info> when you <info>block</info>" ) + std::string( "\n" );
}
if( miss_recovery ) {
dump += _( "* Will grant <info>free recovery</info> from a <info>miss</info>" ) +
std::string( "\n" );
}
if( grab_break ) {
dump += _( "* Will <info>break</info> a <info>grab</info>" ) + std::string( "\n" );
}
if( aoe == "wide" ) {
dump += _( "* Will attack in a <info>wide arc</info> in front of you" ) + std::string( "\n" );
} else if( aoe == "spin" ) {
dump += _( "* Will attack <info>adjacent</info> enemies around you" ) + std::string( "\n" );
} else if( aoe == "impale" ) {
dump += _( "* Will <info>attack</info> your target and another <info>one behind</info> it" ) +
std::string( "\n" );
}
if( knockback_dist ) {
dump += string_format( _( "* Will <info>knock back</info> enemies <stat>%d %s</stat>" ),
knockback_dist, vgettext( "tile", "tiles", knockback_dist ) ) + "\n";
}
if( knockback_follow ) {
dump += _( "* Will <info>follow</info> enemies after knockback." ) + std::string( "\n" );
}
if( down_dur ) {
dump += string_format( _( "* Will <info>down</info> enemies for <stat>%d %s</stat>" ),
down_dur, vgettext( "turn", "turns", down_dur ) ) + "\n";
}
if( stun_dur ) {
dump += string_format( _( "* Will <info>stun</info> target for <stat>%d %s</stat>" ),
stun_dur, vgettext( "turn", "turns", stun_dur ) ) + "\n";
}
if( disarms ) {
dump += _( "* Will <info>disarm</info> the target" ) + std::string( "\n" );
}
if( take_weapon ) {
dump += _( "* Will <info>disarm</info> the target and <info>take their weapon</info>" ) +
std::string( "\n" );
}
return dump;
}
struct cat_order {
bool operator()( const weapon_category_id &lhs, const weapon_category_id &rhs ) const {
return localized_compare( lhs->name().translated(), rhs->name().translated() );
}
};
bool ma_style_callback::key( const input_context &ctxt, const input_event &event, int entnum,
uilist * )
{
const std::string &action = ctxt.input_to_action( event );
if( action != "SHOW_DESCRIPTION" ) {
return false;
}
matype_id style_selected;
const size_t index = entnum;
if( index >= offset && index - offset < styles.size() ) {
style_selected = styles[index - offset];
}
if( !style_selected.str().empty() ) {
const martialart &ma = style_selected.obj();
std::string buffer;
if( ma.force_unarmed ) {
buffer += _( "<bold>This style forces you to use unarmed strikes, even if wielding a weapon.</bold>" );
buffer += "\n";
} else if( ma.allow_melee ) {
buffer += _( "<bold>This style can be used with all weapons.</bold>" );
buffer += "\n";
} else if( ma.strictly_melee ) {
buffer += _( "<bold>This is an armed combat style.</bold>" );
buffer += "\n";
}
buffer += "--\n";
if( ma.arm_block_with_bio_armor_arms || ma.arm_block != 99 ||
ma.leg_block_with_bio_armor_legs || ma.leg_block != 99 ) {
int unarmed_skill = get_player_character().get_skill_level( skill_unarmed );
if( get_player_character().has_active_bionic( bio_cqb ) ) {
unarmed_skill = BIO_CQB_LEVEL;
}
if( ma.arm_block_with_bio_armor_arms ) {
buffer += _( "You can <info>arm block</info> by installing the <info>Arms Alloy Plating CBM</info>" );
buffer += "\n";
} else if( ma.arm_block != 99 ) {
buffer += string_format(
_( "You can <info>arm block</info> at <info>unarmed combat:</info> <stat>%s</stat>/<stat>%s</stat>" ),
unarmed_skill, ma.arm_block ) + "\n";
}
if( ma.leg_block_with_bio_armor_legs ) {
buffer += _( "You can <info>leg block</info> by installing the <info>Legs Alloy Plating CBM</info>" );
buffer += "\n";
} else if( ma.leg_block != 99 ) {
buffer += string_format(
_( "You can <info>leg block</info> at <info>unarmed combat:</info> <stat>%s</stat>/<stat>%s</stat>" ),
unarmed_skill, ma.leg_block );
buffer += "\n";
}
buffer += "--\n";
}
auto buff_desc = [&]( const std::string & title, const std::vector<mabuff_id> &buffs,
bool passive = false ) {
if( !buffs.empty() ) {
buffer += string_format( _( "<header>%s buffs:</header>" ), title );
for( const auto &buff : buffs ) {
buffer += "\n" + buff->get_description( passive );
}
buffer += "--\n";
}
};
buff_desc( _( "Passive" ), ma.static_buffs, true );
buff_desc( _( "Move" ), ma.onmove_buffs );
buff_desc( _( "Pause" ), ma.onpause_buffs );
buff_desc( _( "Hit" ), ma.onhit_buffs );
buff_desc( _( "Miss" ), ma.onmiss_buffs );
buff_desc( _( "Attack" ), ma.onattack_buffs );
buff_desc( _( "Crit" ), ma.oncrit_buffs );
buff_desc( _( "Kill" ), ma.onkill_buffs );
buff_desc( _( "Dodge" ), ma.ondodge_buffs );
buff_desc( _( "Block" ), ma.onblock_buffs );
buff_desc( _( "Get hit" ), ma.ongethit_buffs );
for( const auto &tech : ma.techniques ) {
buffer += string_format( _( "<header>Technique:</header> <bold>%s</bold> " ),
_( tech.obj().name ) ) + "\n";
buffer += tech.obj().get_description() + "--\n";
}
if( !( ma.weapons.empty() && ma.weapon_category.empty() ) ) {
Character &player = get_player_character();
std::map< weapon_category_id, std::vector<std::string>, cat_order > weapons_by_category;
// Iterate over every item in the game.
for( const itype *itp : item_controller->all() ) {
const itype_id &weap_id = itp->get_id();
bool wielded = player.primary_weapon().typeId() == weap_id;
bool carried = player.has_item_with( [weap_id]( const item & it ) {
return it.typeId() == weap_id;
} );
// Check if the item has any one of the weapon categories listed in the MA.
for( const weapon_category_id &cat : ma.weapon_category ) {
auto cat_check = [cat]( const weapon_category_id & category ) {
return category == cat;
};
if( std::any_of( itp->weapon_category.begin(),
itp->weapon_category.end(), cat_check ) ) {
// If so, add it to the categories it applies to.
std::string weaponname = wielded ? colorize( item::nname( weap_id ) + _( " [wielded]" ),
c_light_cyan ) :
carried ? colorize( item::nname( weap_id ), c_yellow ) : item::nname( weap_id );
weapons_by_category[cat].push_back( weaponname );
}
}
}
buffer += _( "<bold>Weapons:</bold>" ) + std::string( "\n" );
for( std::pair< const weapon_category_id, std::vector<std::string> > &list : weapons_by_category ) {
// This removes duplicate names (e.g. a real weapon and a replica sharing the same name) from the weapon list.
list.second.erase( std::unique( list.second.begin(), list.second.end() ), list.second.end() );
// then sort weapons within alphabetically.
std::sort( list.second.begin(), list.second.end(), localized_compare );
// If item factory somehow manages to crap out and it has no translation/name, use the ID.
std::string cat_name = list.first.is_valid() ? list.first->name().translated()
: colorize( "ID: " + std::string( list.first ), c_red );
buffer += std::string( "<header>" ) + cat_name + ": " +
std::string( "</header>" );
buffer += enumerate_as_string( list.second ) + std::string( "\n" );
}
if( !ma.weapons.empty() ) {
std::vector<std::string> weapons;
for( const itype_id &wid : ma.weapons ) {
const itype_id &weap_id = wid->get_id();
bool wielded = player.primary_weapon().typeId() == weap_id;
bool carried = player.has_item_with( [weap_id]( const item & it ) {
return it.typeId() == weap_id;
} );
std::string weaponname = wielded ? colorize( item::nname( wid ) + _( " [wielded]" ),
c_light_cyan ) :
carried ? colorize( item::nname( wid ), c_yellow ) : item::nname( wid );
weapons.push_back( weaponname );
}
// Sorting alphabetically makes it easier to find a specific weapon
std::sort( weapons.begin(), weapons.end(), localized_compare );
// This removes duplicate names (e.g. a real weapon and a replica sharing the same name) from the weapon list.
auto last = std::unique( weapons.begin(), weapons.end() );
weapons.erase( last, weapons.end() );
buffer += _( "<header>Special: </header>" );
buffer += enumerate_as_string( weapons );
}
}
if( !ma.mutation.empty() ) {
Character &player = get_player_character();
buffer += _( "<bold>Mutations:</bold>" ) + std::string( "\n" );
std::vector<std::string> mutations;
for( const trait_id &mut : ma.mutation ) {
std::string mutname = player.has_trait( mut ) ? colorize( mut->name() + _( " [have]" ),
c_light_cyan ) : mut->name();
mutations.push_back( mutname );
}
std::sort( mutations.begin(), mutations.end(), localized_compare );
buffer += enumerate_as_string( mutations );
}
catacurses::window w;
const std::string text = replace_colors( buffer );
int width = 0;
int height = 0;
int iLines = 0;
int selected = 0;
ui_adaptor ui;
ui.on_screen_resize( [&]( ui_adaptor & ui ) {
w = catacurses::newwin( FULL_SCREEN_HEIGHT, FULL_SCREEN_WIDTH,
point( TERMX > FULL_SCREEN_WIDTH ? ( TERMX - FULL_SCREEN_WIDTH ) / 2 : 0,
TERMY > FULL_SCREEN_HEIGHT ? ( TERMY - FULL_SCREEN_HEIGHT ) / 2 : 0 ) );
width = FULL_SCREEN_WIDTH - 4;
height = FULL_SCREEN_HEIGHT - 2;
const auto vFolded = foldstring( text, width );
iLines = vFolded.size();
if( iLines < height ) {
selected = 0;
} else if( selected >= iLines - height ) {
selected = iLines - height;
}
ui.position_from_window( w );
} );
ui.mark_resize();
input_context ict;
ict.register_action( "UP" );
ict.register_action( "DOWN" );
ict.register_action( "PAGE_UP" );
ict.register_action( "PAGE_DOWN" );
ict.register_action( "QUIT" );
ict.register_action( "HELP_KEYBINDINGS" );
ui.on_redraw( [&]( const ui_adaptor & ) {
werase( w );
fold_and_print_from( w, point( 2, 1 ), width, selected, c_light_gray, text );
draw_border( w, BORDER_COLOR, string_format( _( " Style: %s " ), ma.name ) );
draw_scrollbar( w, selected, height, iLines, point_south, BORDER_COLOR, true );
wnoutrefresh( w );
} );
do {
if( selected < 0 ) {
selected = 0;
} else if( iLines < height ) {
selected = 0;
} else if( selected >= iLines - height ) {
selected = iLines - height;
}
ui_manager::redraw();
const int scroll_lines = catacurses::getmaxy( w ) - 4;
std::string action = ict.handle_input();
if( action == "QUIT" ) {
break;
} else if( action == "DOWN" ) {
selected++;
} else if( action == "UP" ) {
selected--;
} else if( action == "PAGE_DOWN" ) {
selected += scroll_lines;
} else if( action == "PAGE_UP" ) {
selected -= scroll_lines;
}
} while( true );
}
return true;
}
| 412 | 0.974777 | 1 | 0.974777 | game-dev | MEDIA | 0.643861 | game-dev | 0.959115 | 1 | 0.959115 |
cleolibrary/GTALCS.GTAVCS.PSP.CLEO | 7,290 | external/pspsdk/usr/local/pspdev/psp/include/SDL2/SDL_timer.h | /*
Simple DirectMedia Layer
Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_timer_h_
#define SDL_timer_h_
/**
* \file SDL_timer.h
*
* Header for the SDL time management routines.
*/
#include "SDL_stdinc.h"
#include "SDL_error.h"
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/**
* Get the number of milliseconds since SDL library initialization.
*
* This value wraps if the program runs for more than ~49 days.
*
* This function is not recommended as of SDL 2.0.18; use SDL_GetTicks64()
* instead, where the value doesn't wrap every ~49 days. There are places in
* SDL where we provide a 32-bit timestamp that can not change without
* breaking binary compatibility, though, so this function isn't officially
* deprecated.
*
* \returns an unsigned 32-bit value representing the number of milliseconds
* since the SDL library initialized.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_TICKS_PASSED
*/
extern DECLSPEC Uint32 SDLCALL SDL_GetTicks(void);
/**
* Get the number of milliseconds since SDL library initialization.
*
* Note that you should not use the SDL_TICKS_PASSED macro with values
* returned by this function, as that macro does clever math to compensate for
* the 32-bit overflow every ~49 days that SDL_GetTicks() suffers from. 64-bit
* values from this function can be safely compared directly.
*
* For example, if you want to wait 100 ms, you could do this:
*
* ```c
* const Uint64 timeout = SDL_GetTicks64() + 100;
* while (SDL_GetTicks64() < timeout) {
* // ... do work until timeout has elapsed
* }
* ```
*
* \returns an unsigned 64-bit value representing the number of milliseconds
* since the SDL library initialized.
*
* \since This function is available since SDL 2.0.18.
*/
extern DECLSPEC Uint64 SDLCALL SDL_GetTicks64(void);
/**
* Compare 32-bit SDL ticks values, and return true if `A` has passed `B`.
*
* This should be used with results from SDL_GetTicks(), as this macro
* attempts to deal with the 32-bit counter wrapping back to zero every ~49
* days, but should _not_ be used with SDL_GetTicks64(), which does not have
* that problem.
*
* For example, with SDL_GetTicks(), if you want to wait 100 ms, you could
* do this:
*
* ```c
* const Uint32 timeout = SDL_GetTicks() + 100;
* while (!SDL_TICKS_PASSED(SDL_GetTicks(), timeout)) {
* // ... do work until timeout has elapsed
* }
* ```
*
* Note that this does not handle tick differences greater
* than 2^31 so take care when using the above kind of code
* with large timeout delays (tens of days).
*/
#define SDL_TICKS_PASSED(A, B) ((Sint32)((B) - (A)) <= 0)
/**
* Get the current value of the high resolution counter.
*
* This function is typically used for profiling.
*
* The counter values are only meaningful relative to each other. Differences
* between values can be converted to times by using
* SDL_GetPerformanceFrequency().
*
* \returns the current counter value.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetPerformanceFrequency
*/
extern DECLSPEC Uint64 SDLCALL SDL_GetPerformanceCounter(void);
/**
* Get the count per second of the high resolution counter.
*
* \returns a platform-specific count per second.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_GetPerformanceCounter
*/
extern DECLSPEC Uint64 SDLCALL SDL_GetPerformanceFrequency(void);
/**
* Wait a specified number of milliseconds before returning.
*
* This function waits a specified number of milliseconds before returning. It
* waits at least the specified time, but possibly longer due to OS
* scheduling.
*
* \param ms the number of milliseconds to delay
*
* \since This function is available since SDL 2.0.0.
*/
extern DECLSPEC void SDLCALL SDL_Delay(Uint32 ms);
/**
* Function prototype for the timer callback function.
*
* The callback function is passed the current timer interval and returns
* the next timer interval. If the returned value is the same as the one
* passed in, the periodic alarm continues, otherwise a new alarm is
* scheduled. If the callback returns 0, the periodic alarm is cancelled.
*/
typedef Uint32 (SDLCALL * SDL_TimerCallback) (Uint32 interval, void *param);
/**
* Definition of the timer ID type.
*/
typedef int SDL_TimerID;
/**
* Call a callback function at a future time.
*
* If you use this function, you must pass `SDL_INIT_TIMER` to SDL_Init().
*
* The callback function is passed the current timer interval and the user
* supplied parameter from the SDL_AddTimer() call and should return the next
* timer interval. If the value returned from the callback is 0, the timer is
* canceled.
*
* The callback is run on a separate thread.
*
* Timers take into account the amount of time it took to execute the
* callback. For example, if the callback took 250 ms to execute and returned
* 1000 (ms), the timer would only wait another 750 ms before its next
* iteration.
*
* Timing may be inexact due to OS scheduling. Be sure to note the current
* time with SDL_GetTicks() or SDL_GetPerformanceCounter() in case your
* callback needs to adjust for variances.
*
* \param interval the timer delay, in milliseconds, passed to `callback`
* \param callback the SDL_TimerCallback function to call when the specified
* `interval` elapses
* \param param a pointer that is passed to `callback`
* \returns a timer ID or 0 if an error occurs; call SDL_GetError() for more
* information.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_RemoveTimer
*/
extern DECLSPEC SDL_TimerID SDLCALL SDL_AddTimer(Uint32 interval,
SDL_TimerCallback callback,
void *param);
/**
* Remove a timer created with SDL_AddTimer().
*
* \param id the ID of the timer to remove
* \returns SDL_TRUE if the timer is removed or SDL_FALSE if the timer wasn't
* found.
*
* \since This function is available since SDL 2.0.0.
*
* \sa SDL_AddTimer
*/
extern DECLSPEC SDL_bool SDLCALL SDL_RemoveTimer(SDL_TimerID id);
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* SDL_timer_h_ */
/* vi: set ts=4 sw=4 expandtab: */
| 412 | 0.768702 | 1 | 0.768702 | game-dev | MEDIA | 0.410076 | game-dev | 0.692481 | 1 | 0.692481 |
PolarisSS13/Polaris | 3,990 | code/game/machinery/supplybeacon.dm | // Used to deploy the bacon.
/obj/item/supply_beacon
name = "inactive supply beacon"
icon = 'icons/obj/supplybeacon.dmi'
desc = "An inactive, hacked supply beacon stamped with the local system's Rapid Fabrication logo. Good for one (1) ballistic supply pod shipment."
icon_state = "beacon"
var/deploy_path = /obj/machinery/power/supply_beacon
var/deploy_time = 30
/obj/item/supply_beacon/supermatter
name = "inactive supermatter supply beacon"
deploy_path = /obj/machinery/power/supply_beacon/supermatter
/obj/item/supply_beacon/attack_self(var/mob/user)
user.visible_message("<span class='notice'>\The [user] begins setting up \the [src].</span>")
if(!do_after(user, deploy_time))
return
var/obj/S = new deploy_path(get_turf(user))
user.visible_message("<span class='notice'>\The [user] deploys \the [S].</span>")
user.unEquip(src)
qdel(src)
/obj/machinery/power/supply_beacon
name = "supply beacon"
desc = "A bulky moonshot supply beacon. Someone has been messing with the wiring."
icon = 'icons/obj/supplybeacon.dmi'
icon_state = "beacon"
anchored = 0
density = 1
layer = MOB_LAYER - 0.1
stat = 0
var/target_drop_time
var/drop_delay = 450
var/expended
var/drop_type
/obj/machinery/power/supply_beacon/Initialize()
. = ..()
if(!drop_type) drop_type = pick(supply_drop_random_loot_types())
/obj/machinery/power/supply_beacon/supermatter
name = "supermatter supply beacon"
drop_type = "supermatter"
/obj/machinery/power/supply_beacon/attackby(var/obj/item/W, var/mob/user)
if(!use_power && W.is_wrench())
if(!anchored && !connect_to_network())
to_chat(user, "<span class='warning'>This device must be placed over an exposed cable.</span>")
return
anchored = !anchored
user.visible_message("<span class='notice'>\The [user] [anchored ? "secures" : "unsecures"] \the [src].</span>")
playsound(src, W.usesound, 50, 1)
return
return ..()
/obj/machinery/power/supply_beacon/attack_hand(var/mob/user)
if(expended)
update_use_power(USE_POWER_OFF)
to_chat (user, "<span class='warning'>\The [src] has used up its charge.</span>")
return
if(anchored)
return use_power ? deactivate(user) : activate(user)
else
to_chat(user, "<span class='warning'>You need to secure the beacon with a wrench first!</span>")
return
/obj/machinery/power/supply_beacon/attack_ai(var/mob/user)
if(user.Adjacent(src))
attack_hand(user)
/obj/machinery/power/supply_beacon/proc/activate(var/mob/user)
if(expended)
return
if(surplus() < 500)
if(user) to_chat(user, "<span class='notice'>The connected wire doesn't have enough current.</span>")
return
set_light(3, 3, "#00CCAA")
icon_state = "beacon_active"
update_use_power(USE_POWER_IDLE)
if(user) to_chat(user, "<span class='notice'>You activate the beacon. The supply drop will be dispatched soon.</span>")
/obj/machinery/power/supply_beacon/proc/deactivate(var/mob/user, var/permanent)
if(permanent)
expended = 1
icon_state = "beacon_depleted"
else
icon_state = "beacon"
set_light(0)
update_use_power(USE_POWER_OFF)
target_drop_time = null
if(user) to_chat(user, "<span class='notice'>You deactivate the beacon.</span>")
/obj/machinery/power/supply_beacon/Destroy()
if(use_power)
deactivate()
..()
/obj/machinery/power/supply_beacon/process()
if(expended)
return PROCESS_KILL
if(!use_power)
return
if(draw_power(500) < 500)
deactivate()
return
if(!target_drop_time)
target_drop_time = world.time + drop_delay
else if(world.time >= target_drop_time)
deactivate(permanent = 1)
var/drop_x = src.x - 2
var/drop_y = src.y - 2
var/drop_z = src.z
command_announcement.Announce("[using_map.starsys_name] Rapid Fabrication priority supply request #[rand(1000,9999)]-[rand(100,999)] received. Shipment dispatched via ballistic supply pod for immediate delivery. Have a nice day.", "Thank You For Your Patronage")
spawn(rand(100, 300))
new /datum/random_map/droppod/supply(null, drop_x, drop_y, drop_z, supplied_drop = drop_type) // Splat.
| 412 | 0.957924 | 1 | 0.957924 | game-dev | MEDIA | 0.620165 | game-dev | 0.921662 | 1 | 0.921662 |
focus-creative-games/luban_examples | 4,739 | Projects/Csharp_Unity_Editor_json/Assets/Gen/ai/MoveToRandomLocation.cs |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Collections.Generic;
using SimpleJSON;
using Luban;
namespace cfg.ai
{
public sealed class MoveToRandomLocation : ai.Task
{
public MoveToRandomLocation()
{
originPositionKey = "";
}
public override void LoadJson(SimpleJSON.JSONObject _json)
{
{
var _fieldJson = _json["id"];
if (_fieldJson != null)
{
if(!_fieldJson.IsNumber) { throw new SerializationException(); } id = _fieldJson;
}
}
{
var _fieldJson = _json["node_name"];
if (_fieldJson != null)
{
if(!_fieldJson.IsString) { throw new SerializationException(); } nodeName = _fieldJson;
}
}
{
var _fieldJson = _json["decorators"];
if (_fieldJson != null)
{
if(!_fieldJson.IsArray) { throw new SerializationException(); } decorators = new System.Collections.Generic.List<ai.Decorator>(); foreach(JSONNode __e0 in _fieldJson.Children) { ai.Decorator __v0; if(!__e0.IsObject) { throw new SerializationException(); } __v0 = ai.Decorator.LoadJsonDecorator(__e0); decorators.Add(__v0); }
}
}
{
var _fieldJson = _json["services"];
if (_fieldJson != null)
{
if(!_fieldJson.IsArray) { throw new SerializationException(); } services = new System.Collections.Generic.List<ai.Service>(); foreach(JSONNode __e0 in _fieldJson.Children) { ai.Service __v0; if(!__e0.IsObject) { throw new SerializationException(); } __v0 = ai.Service.LoadJsonService(__e0); services.Add(__v0); }
}
}
{
var _fieldJson = _json["ignore_restart_self"];
if (_fieldJson != null)
{
if(!_fieldJson.IsBoolean) { throw new SerializationException(); } ignoreRestartSelf = _fieldJson;
}
}
{
var _fieldJson = _json["origin_position_key"];
if (_fieldJson != null)
{
if(!_fieldJson.IsString) { throw new SerializationException(); } originPositionKey = _fieldJson;
}
}
{
var _fieldJson = _json["radius"];
if (_fieldJson != null)
{
if(!_fieldJson.IsNumber) { throw new SerializationException(); } radius = _fieldJson;
}
}
}
public override void SaveJson(SimpleJSON.JSONObject _json)
{
{
_json["id"] = new JSONNumber(id);
}
{
if (nodeName == null) { throw new System.ArgumentNullException(); }
_json["node_name"] = new JSONString(nodeName);
}
{
if (decorators == null) { throw new System.ArgumentNullException(); }
{ var __cjson0 = new JSONArray(); _json["decorators"] = __cjson0; foreach(var _e0 in decorators) { JSONNode __v0; { var __bjson1 = new JSONObject(); __v0 = __bjson1; ai.Decorator.SaveJsonDecorator(_e0, __bjson1); } __cjson0.Add(__v0); } }
}
{
if (services == null) { throw new System.ArgumentNullException(); }
{ var __cjson0 = new JSONArray(); _json["services"] = __cjson0; foreach(var _e0 in services) { JSONNode __v0; { var __bjson1 = new JSONObject(); __v0 = __bjson1; ai.Service.SaveJsonService(_e0, __bjson1); } __cjson0.Add(__v0); } }
}
{
_json["ignore_restart_self"] = new JSONBool(ignoreRestartSelf);
}
{
if (originPositionKey == null) { throw new System.ArgumentNullException(); }
_json["origin_position_key"] = new JSONString(originPositionKey);
}
{
_json["radius"] = new JSONNumber(radius);
}
}
public static MoveToRandomLocation LoadJsonMoveToRandomLocation(SimpleJSON.JSONNode _json)
{
MoveToRandomLocation obj = new ai.MoveToRandomLocation();
obj.LoadJson((SimpleJSON.JSONObject)_json);
return obj;
}
public static void SaveJsonMoveToRandomLocation(MoveToRandomLocation _obj, SimpleJSON.JSONNode _json)
{
_obj.SaveJson((SimpleJSON.JSONObject)_json);
}
public string originPositionKey;
public float radius;
}
}
| 412 | 0.780135 | 1 | 0.780135 | game-dev | MEDIA | 0.353665 | game-dev | 0.650494 | 1 | 0.650494 |
microsoft/MRDesignLabs_Unity_Tools | 3,219 | HUX/Scripts/Dialogs/Fitbox.cs | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
using HoloToolkit.Unity;
using UnityEngine;
namespace HUX.Dialogs
{
// Used to place the scene origin on startup
// Adapted from Holoacadamy's fitbox
public class Fitbox : MonoBehaviour
{
[Tooltip("Reposition the scene object relative to where the Fitbox was dismissed.")]
public bool MoveCollectionOnDismiss = false;
[Tooltip("The scene object to activate and reposition.")]
public GameObject StartupObject;
private float Distance = 1.0f;
private Interpolator interpolator;
// The offset from the Camera to the StartupObject when
// the app starts up. This is used to place the StartupObject
// in the correct relative position after the Fitbox is
// dismissed.
private Vector3 collectionStartingOffsetFromCamera;
private void Start()
{
// This is the object to show when the Fitbox is dismissed
if (StartupObject != null)
{
collectionStartingOffsetFromCamera = StartupObject.transform.localPosition;
StartupObject.SetActive(false);
}
interpolator = GetComponent<Interpolator>();
interpolator.PositionPerSecond = 2f;
}
private void Tapped()
{
// Show the startup object
if (StartupObject != null)
{
StartupObject.SetActive(true);
if (MoveCollectionOnDismiss)
{
// Update the Hologram Collection's position so it shows up
// where the Fitbox left off. Start with the camera's rotation...
Quaternion camQuat = Camera.main.transform.rotation;
// ... ignore pitch by disabling rotation around the x axis
camQuat.x = 0;
// Rotate the vector and factor y back into the position
Vector3 newPosition = camQuat * collectionStartingOffsetFromCamera;
newPosition.y = collectionStartingOffsetFromCamera.y;
// Position was "Local Position" so add that to where the camera is now
StartupObject.transform.position = Camera.main.transform.position + newPosition;
// Rotate the Hologram Collection to face the user.
Quaternion toQuat = Camera.main.transform.rotation * StartupObject.transform.rotation;
toQuat.x = 0;
toQuat.z = 0;
StartupObject.transform.rotation = toQuat;
}
}
// Destroy the Fitbox
Destroy(gameObject);
}
void LateUpdate()
{
Transform cameraTransform = Camera.main.transform;
interpolator.SetTargetPosition(cameraTransform.position + (cameraTransform.forward * Distance));
interpolator.SetTargetRotation(Quaternion.LookRotation(-cameraTransform.forward, -cameraTransform.up));
}
}
} | 412 | 0.757261 | 1 | 0.757261 | game-dev | MEDIA | 0.441792 | game-dev | 0.957743 | 1 | 0.957743 |
Povstalec/StargateJourney | 3,424 | src/main/java/net/povstalec/sgjourney/common/misc/LocatorHelper.java | package net.povstalec.sgjourney.common.misc;
import net.minecraft.core.BlockPos;
import net.minecraft.core.SectionPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.povstalec.sgjourney.common.block_entities.stargate.AbstractStargateEntity;
import net.povstalec.sgjourney.common.data.TransporterNetwork;
import net.povstalec.sgjourney.common.sgjourney.transporter.Transporter;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class LocatorHelper
{
//============================================================================================
//******************************************Stargate******************************************
//============================================================================================
public static List<AbstractStargateEntity> getNearbyStargates(Level level, BlockPos centerPos, long maxDistance)
{
List<AbstractStargateEntity> stargates = new ArrayList<>();
int chunkX = SectionPos.blockToSectionCoord(centerPos.getX());
int chunkZ = SectionPos.blockToSectionCoord(centerPos.getZ());
int chunkDistance = SectionPos.blockToSectionCoord(maxDistance);
for(int x = chunkX - chunkDistance; x <= chunkX + chunkDistance; x++)
{
for(int z = chunkZ - chunkDistance; z <= chunkZ + chunkDistance; z++)
{
ChunkAccess chunk = level.getChunk(x, z);
for(BlockPos pos : chunk.getBlockEntitiesPos())
{
if(level.getBlockEntity(pos) instanceof AbstractStargateEntity stargate && CoordinateHelper.Relative.distanceSqr(centerPos, stargate.getBlockPos()) <= maxDistance * maxDistance)
stargates.add(stargate);
}
}
}
return stargates;
}
public static List<AbstractStargateEntity> getNearbyStargatesByDistance(Level level, BlockPos centerPos, long maxDistance)
{
List<AbstractStargateEntity> stargates = getNearbyStargates(level, centerPos, maxDistance);
stargates.sort(Comparator.comparing(stargate -> CoordinateHelper.Relative.distance(centerPos, stargate.getBlockPos())));
return stargates;
}
@Nullable
public static AbstractStargateEntity findNearestStargate(Level level, BlockPos centerPos, long maxDistance)
{
List<AbstractStargateEntity> stargates = getNearbyStargatesByDistance(level, centerPos, maxDistance);
if(stargates.isEmpty())
return null;
return stargates.get(0);
}
//============================================================================================
//****************************************Transporter*****************************************
//============================================================================================
public static List<Transporter> findNearestTransporters(ServerLevel level, BlockPos centerPos)
{
List<Transporter> transporters = TransporterNetwork.get(level).getTransportersFromDimension(level.dimension());
transporters.sort(Comparator.comparing(transporter -> CoordinateHelper.Relative.distance(centerPos, transporter.getBlockPos())));
transporters.removeIf(transporter ->
{
if(transporter.getBlockPos() == null || transporter.getDimension() == null)
return true;
//TODO Remove stuff like Transporters on other frequencies, so that they remain invisible
return false;
});
return transporters;
}
}
| 412 | 0.826386 | 1 | 0.826386 | game-dev | MEDIA | 0.788902 | game-dev | 0.662475 | 1 | 0.662475 |
Haruma-K/UnityDebugSheet | 1,226 | Assets/Demo/01_CharacterViewer/Scripts/CharacterViewerDemo.cs | #if !EXCLUDE_UNITY_DEBUG_SHEET
using Demo._01_CharacterViewer.Scripts.Viewer;
using Demo._99_Shared.Scripts;
using UnityDebugSheet.Runtime.Core.Scripts;
using UnityEngine;
using UnityEngine.Assertions;
namespace Demo._01_CharacterViewer.Scripts
{
public sealed class CharacterViewerDemo : MonoBehaviour
{
[SerializeField] private CharacterSpawner _spawner;
[SerializeField] private StandController _standController;
private PageItemDisposer _itemDisposer;
private void Start()
{
Assert.IsNotNull(_spawner);
Assert.IsNotNull(_standController);
_spawner.Initialize();
var initialPage = DebugSheet.Instance.GetOrCreateInitialPage();
var linkButtonId = initialPage.AddPageLinkButton<CharacterViewerPage>("Character Viewer",
icon: DemoSprites.Icon.CharacterViewer,
onLoad: x => { x.page.Setup(_spawner, _standController); },
priority: 0);
_itemDisposer = new PageItemDisposer(initialPage);
_itemDisposer.AddItemId(linkButtonId);
}
private void OnDestroy()
{
_itemDisposer?.Dispose();
}
}
}
#endif
| 412 | 0.837969 | 1 | 0.837969 | game-dev | MEDIA | 0.980027 | game-dev | 0.835352 | 1 | 0.835352 |
adevaucorbeil/karamelo | 1,569 | src/fix_initial_velocity_particles.h | /* -*- c++ -*- ----------------------------------------------------------
*
* *** Karamelo ***
* Parallel Material Point Method Simulator
*
* Copyright (2019) Alban de Vaucorbeil, alban.devaucorbeil@monash.edu
* Materials Science and Engineering, Monash University
* Clayton VIC 3800, Australia
* This software is distributed under the GNU General Public License.
*
* ----------------------------------------------------------------------- */
#ifdef FIX_CLASS
FixStyle(initial_velocity_particles,FixInitialVelocityParticles)
#else
#ifndef MPM_FIX_INITIAL_VELOCITY_PARTICLES_H
#define MPM_FIX_INITIAL_VELOCITY_PARTICLES_H
#include "fix.h"
#include "var.h"
#include <vector>
class FixInitialVelocityParticles : public Fix {
public:
FixInitialVelocityParticles(class MPM *, vector<string>);
~FixInitialVelocityParticles();
void setmask();
void init();
void setup();
void initial_integrate();
void post_particles_to_grid() {};
void post_update_grid_state() {};
void post_grid_to_point() {};
void post_advance_particles() {};
void post_velocities_to_grid() {};
void final_integrate() {};
void write_restart(ofstream *) {};
void read_restart(ifstream *) {};
private:
string usage = "Usage: fix(fix-ID, initial_velocity_particles, group-ID, vx, vy, vz)\n";
int Nargs = 6;
class Var xvalue, yvalue, zvalue; // Set velocities in x, y, and z directions.
bool xset, yset, zset; // Does the fix set the x, y, and z velocities of the group?
};
#endif
#endif
| 412 | 0.832355 | 1 | 0.832355 | game-dev | MEDIA | 0.342509 | game-dev | 0.778526 | 1 | 0.778526 |
rsdn/nemerle | 1,505 | lib/HashSetEx.n | using Nemerle;
using Nemerle.Collections;
using Nemerle.Text;
using Nemerle.Utility;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Nemerle.Collections
{
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(false)]
[DebuggerDisplay("Count = {Count}: {ToString()}")]
[DebuggerNonUserCode]
public class HashSetEx[T] : IEnumerable[T]
{
_hashtable : Hashtable[T, T] = Hashtable();
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public Items : Dictionary[T, T].KeyCollection { get { _hashtable.Keys } }
public IsEmpty : bool { get { _hashtable.Count == 0 } }
public Count : int { get { _hashtable.Count } }
public Contains(item : T) : bool
{
_hashtable.ContainsKey(item)
}
public Add(mutable item : T) : bool
{
AddOrGetFirstAddedItem(ref item)
}
/// <summary>
/// Return true if new item.
/// Return false and replace with old item otherwise.
/// </summary>
public AddOrGetFirstAddedItem(item : ref T) : bool
{
mutable oldKey;
if (_hashtable.TryGetValue(item, out oldKey))
{
item = oldKey;
false;
}
else
{
_hashtable.Add(item, item);
true;
}
}
public TryGetFirstAddedItem(item : T, oldItem : out T) : bool
{
_hashtable.TryGetValue(item, out oldItem)
}
public GetEnumerator() : IEnumerator[T]
{
_hashtable.Keys.GetEnumerator()
}
}
}
| 412 | 0.818408 | 1 | 0.818408 | game-dev | MEDIA | 0.572886 | game-dev,desktop-app | 0.941656 | 1 | 0.941656 |
BluSunrize/ImmersiveEngineering | 1,228 | src/datagen/java/blusunrize/immersiveengineering/data/recipes/builder/ClocheFertilizerBuilder.java | /*
* BluSunrize
* Copyright (c) 2024
*
* This code is licensed under "Blu's License of Common Sense"
* Details can be found in the license file in the root folder of this project
*/
package blusunrize.immersiveengineering.data.recipes.builder;
import blusunrize.immersiveengineering.api.crafting.ClocheFertilizer;
import blusunrize.immersiveengineering.data.recipes.builder.BaseHelpers.UnsizedItemInput;
import net.minecraft.data.recipes.RecipeOutput;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.crafting.Ingredient;
public class ClocheFertilizerBuilder extends IERecipeBuilder<ClocheFertilizerBuilder>
implements UnsizedItemInput<ClocheFertilizerBuilder>
{
private Ingredient input;
private final float modifier;
private ClocheFertilizerBuilder(float modifier)
{
this.modifier = modifier;
}
public static ClocheFertilizerBuilder builder(float modifier)
{
return new ClocheFertilizerBuilder(modifier);
}
@Override
public ClocheFertilizerBuilder input(Ingredient input)
{
this.input = input;
return this;
}
public void build(RecipeOutput out, ResourceLocation name)
{
out.accept(name, new ClocheFertilizer(input, modifier), null, getConditions());
}
}
| 412 | 0.918489 | 1 | 0.918489 | game-dev | MEDIA | 0.954263 | game-dev | 0.914482 | 1 | 0.914482 |
LingASDJ/Magic_Ling_Pixel_Dungeon | 9,633 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/actors/mobs/npcs/DragonGirlBlue.java | package com.shatteredpixel.shatteredpixeldungeon.actors.mobs.npcs;
import static com.shatteredpixel.shatteredpixeldungeon.Dungeon.depth;
import static com.shatteredpixel.shatteredpixeldungeon.Dungeon.hero;
import static com.shatteredpixel.shatteredpixeldungeon.actors.mobs.npcs.DragonGirlBlue.Quest.survey_research_points;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.AscensionChallenge;
import com.shatteredpixel.shatteredpixeldungeon.custom.utils.plot.DragonBluePlot;
import com.shatteredpixel.shatteredpixeldungeon.items.artifacts.TimekeepersHourglass;
import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.LockSword;
import com.shatteredpixel.shatteredpixeldungeon.journal.Notes;
import com.shatteredpixel.shatteredpixeldungeon.levels.features.LevelTransition;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.shatteredpixel.shatteredpixeldungeon.plants.Swiftthistle;
import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene;
import com.shatteredpixel.shatteredpixeldungeon.scenes.InterlevelScene;
import com.shatteredpixel.shatteredpixeldungeon.sprites.DragonGirlBlueSprite;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndDialog;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndDragonGirlBlue;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndOptions;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndQuest;
import com.watabou.noosa.Game;
import com.watabou.utils.Bundle;
import com.watabou.utils.Callback;
public class DragonGirlBlue extends NTNPC{
{
spriteClass = DragonGirlBlueSprite.class;
properties.add(Property.IMMOVABLE);
}
private boolean first=true;
private boolean secnod=true;
private static final String FIRST = "first";
private static final String SECNOD = "secnod";
@Override
public void storeInBundle(Bundle bundle) {
super.storeInBundle(bundle);
bundle.put(FIRST, first);
bundle.put(SECNOD, secnod);
}
@Override
public void restoreFromBundle(Bundle bundle) {
super.restoreFromBundle(bundle);
first = bundle.getBoolean(FIRST);
secnod = bundle.getBoolean(SECNOD);
}
@Override
protected boolean act() {
if (hero.buff(AscensionChallenge.class) != null){
die(null);
Notes.remove( Notes.Landmark.SMALLB);
return true;
}
if (Dungeon.level.visited[pos]){
Notes.add( Notes.Landmark.SMALLB );
}
throwItem();
sprite.turnTo( pos, hero.pos );
spend( TICK );
return super.act();
}
@Override
public boolean interact(Char c) {
sprite.turnTo(pos, hero.pos);
DragonBluePlot plot = new DragonBluePlot();
DragonBluePlot.TwoDialog plot_2 = new DragonBluePlot.TwoDialog();
if(first){
Game.runOnRenderThread(new Callback() {
@Override
public void call() {
GameScene.show(new WndDialog(plot,false));
}
});
first=false;
} else if(secnod) {
Game.runOnRenderThread(new Callback() {
@Override
public void call() {
GameScene.show(new WndDialog(plot_2,false));
}
});
secnod=false;
} else if(!Dungeon.anCityQuest2Progress) {
LockSword lockSword = Dungeon.hero.belongings.getItem(LockSword.class);
if(lockSword!=null) {
Game.runOnRenderThread(new Callback() {
@Override
public void call() {
GameScene.show(new WndOptions(new DragonGirlBlueSprite(),
Messages.titleCase(Messages.get(DragonGirlBlue.class, "name")),
Messages.get(DragonGirlBlue.class, "quest_start_prompt"),
Messages.get(DragonGirlBlue.class, "enter_yes"),
Messages.get(DragonGirlBlue.class, "enter_no")) {
@Override
protected void onSelect(int index) {
if (index == 0) {
TimekeepersHourglass.timeFreeze timeFreeze = Dungeon.hero.buff(TimekeepersHourglass.timeFreeze.class);
if (timeFreeze != null) timeFreeze.disarmPresses();
Swiftthistle.TimeBubble timeBubble = Dungeon.hero.buff(Swiftthistle.TimeBubble.class);
if (timeBubble != null) timeBubble.disarmPresses();
InterlevelScene.mode = InterlevelScene.Mode.ANCITYBOSS;
InterlevelScene.curTransition = new LevelTransition();
InterlevelScene.curTransition.destDepth = depth;
LockSword lockSword = Dungeon.hero.belongings.getItem(LockSword.class);
lockSword.lvl -= 300;
InterlevelScene.curTransition.destType = LevelTransition.Type.BRANCH_ENTRANCE;
InterlevelScene.curTransition.destBranch = Dungeon.branch + 1;
InterlevelScene.curTransition.type = LevelTransition.Type.BRANCH_ENTRANCE;
InterlevelScene.curTransition.centerCell = -1;
Game.switchScene(InterlevelScene.class);
}
}
});
}
});
} else {
Game.runOnRenderThread(new Callback() {
@Override
public void call() {
GameScene.show(new WndQuest(new DragonGirlBlue(), Messages.get(DragonGirlBlue.class,"not_locked")));
}
});
return false;
}
} else if(DragonGirlBlue.Quest.survey_research_points == 0) {
yell(Messages.get(DragonGirlBlue.class,"no_anymore"));
} else {
Game.runOnRenderThread(new Callback() {
@Override
public void call() {
if(survey_research_points>4000) survey_research_points = 4000;
GameScene.show(new WndDragonGirlBlue(DragonGirlBlue.this, Dungeon.hero));
}
});
}
return true;
}
public static class Quest {
public static int survey_research_points;
public static int one_used_points;
public static int three_used_points;
public static int four_used_points;
public static int two_used_points;
public static boolean spawned;
private static boolean completed;
private static boolean bossBeaten;
public static boolean beatBoss(){
return bossBeaten = true;
}
public static void reset() {
survey_research_points = 0;
one_used_points = 0;
two_used_points = 0;
three_used_points = 0;
four_used_points = 0;
spawned = false;
bossBeaten = false;
completed = false;
}
private static final String COMPLETED = "completed";
private static final String NODE = "dragon_girl";
private static final String SURVEY = "survey_research_points";
private static final String ONEUSED = "one_used_points";
private static final String TWOUSED = "two_used_points";
private static final String THREEUSED = "three_used_points";
private static final String FOURUSED = "four_used_points";
private static final String SPAWNED = "spawned";
private static final String BOSS_BEATEN = "boss_beaten";
public static void storeInBundle( Bundle bundle ) {
Bundle node = new Bundle();
node.put( SPAWNED, spawned );
if (spawned) {
node.put( SURVEY, survey_research_points );
node.put( ONEUSED, one_used_points);
node.put(TWOUSED, two_used_points);
node.put(THREEUSED, three_used_points);
node.put(FOURUSED, four_used_points);
node.put( COMPLETED, completed );
node.put( BOSS_BEATEN, bossBeaten );
}
bundle.put( NODE, node );
}
public static void restoreFromBundle( Bundle bundle ) {
Bundle node = bundle.getBundle(NODE);
if (!node.isNull() && (spawned = node.getBoolean(SPAWNED))) {
survey_research_points = node.getInt( SURVEY );
completed = node.getBoolean( COMPLETED );
one_used_points = node.getInt(ONEUSED);
two_used_points = node.getInt(TWOUSED);
three_used_points = node.getInt(THREEUSED);
four_used_points = node.getInt(FOURUSED);
bossBeaten = node.getBoolean( BOSS_BEATEN );
} else {
reset();
}
}
public static void complete(){
completed = true;
if(survey_research_points>4000){
survey_research_points = 4000;
}
}
}
}
| 412 | 0.949176 | 1 | 0.949176 | game-dev | MEDIA | 0.979965 | game-dev | 0.987746 | 1 | 0.987746 |
UnrealMultiple/TShockPlugin | 76,483 | src/ZHIPlayerManager/ZHIPM.Utils.cs | using Microsoft.Xna.Framework;
using System.Security.Cryptography;
using System.Text;
using Terraria;
using Terraria.IO;
using Terraria.Localization;
using TShockAPI;
using TShockAPI.DB;
using Utils = Terraria.Utils;
namespace ZHIPlayerManager;
public partial class ZHIPM
{
/// <summary>
/// 同步玩家的人物数据数据,线上类型,仅同步在线玩家,在内存中的数据
/// </summary>
/// <param name="p">你要被同步的玩家</param>
/// <param name="pd">赋值给他的数据</param>
/// <returns></returns>
private bool UpdatePlayerAll(TSPlayer p, PlayerData pd)
{
if (!pd.exists)
{
return false;
}
//正常同步
if (pd.currentLoadoutIndex == p.TPlayer.CurrentLoadoutIndex)
{
for (var i = 0; i < NetItem.MaxInventory; i++)
{
if (i < NetItem.InventoryIndex.Item2)
{
p.TPlayer.inventory[i] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.inventory[i].stack = pd.inventory[i].Stack;
p.TPlayer.inventory[i].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.ArmorIndex.Item2)
{
var num = i - NetItem.ArmorIndex.Item1;
p.TPlayer.armor[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.armor[num].stack = pd.inventory[i].Stack;
p.TPlayer.armor[num].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.DyeIndex.Item2)
{
var num2 = i - NetItem.DyeIndex.Item1;
p.TPlayer.dye[num2] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.dye[num2].stack = pd.inventory[i].Stack;
p.TPlayer.dye[num2].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.MiscEquipIndex.Item2)
{
var num3 = i - NetItem.MiscEquipIndex.Item1;
p.TPlayer.miscEquips[num3] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.miscEquips[num3].stack = pd.inventory[i].Stack;
p.TPlayer.miscEquips[num3].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.MiscDyeIndex.Item2)
{
var num4 = i - NetItem.MiscDyeIndex.Item1;
p.TPlayer.miscDyes[num4] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.miscDyes[num4].stack = pd.inventory[i].Stack;
p.TPlayer.miscDyes[num4].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.PiggyIndex.Item2)
{
var num5 = i - NetItem.PiggyIndex.Item1;
p.TPlayer.bank.item[num5] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.bank.item[num5].stack = pd.inventory[i].Stack;
p.TPlayer.bank.item[num5].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.SafeIndex.Item2)
{
var num6 = i - NetItem.SafeIndex.Item1;
p.TPlayer.bank2.item[num6] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.bank2.item[num6].stack = pd.inventory[i].Stack;
p.TPlayer.bank2.item[num6].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.TrashIndex.Item2)
{
p.TPlayer.trashItem = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.trashItem.stack = pd.inventory[i].Stack;
p.TPlayer.trashItem.prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.ForgeIndex.Item2)
{
var num7 = i - NetItem.ForgeIndex.Item1;
p.TPlayer.bank3.item[num7] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.bank3.item[num7].stack = pd.inventory[i].Stack;
p.TPlayer.bank3.item[num7].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.VoidIndex.Item2)
{
var num8 = i - NetItem.VoidIndex.Item1;
p.TPlayer.bank4.item[num8] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.bank4.item[num8].stack = pd.inventory[i].Stack;
p.TPlayer.bank4.item[num8].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.Loadout1Armor.Item2)
{
var num9 = i - NetItem.Loadout1Armor.Item1;
p.TPlayer.Loadouts[0].Armor[num9] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[0].Armor[num9].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[0].Armor[num9].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.Loadout1Dye.Item2)
{
var num10 = i - NetItem.Loadout1Dye.Item1;
p.TPlayer.Loadouts[0].Dye[num10] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[0].Dye[num10].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[0].Dye[num10].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.Loadout2Armor.Item2)
{
var num11 = i - NetItem.Loadout2Armor.Item1;
p.TPlayer.Loadouts[1].Armor[num11] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[1].Armor[num11].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[1].Armor[num11].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.Loadout2Dye.Item2)
{
var num12 = i - NetItem.Loadout2Dye.Item1;
p.TPlayer.Loadouts[1].Dye[num12] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[1].Dye[num12].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[1].Dye[num12].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.Loadout3Armor.Item2)
{
var num13 = i - NetItem.Loadout3Armor.Item1;
p.TPlayer.Loadouts[2].Armor[num13] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[2].Armor[num13].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[2].Armor[num13].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.Loadout3Dye.Item2)
{
var num14 = i - NetItem.Loadout3Dye.Item1;
p.TPlayer.Loadouts[2].Dye[num14] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[2].Dye[num14].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[2].Dye[num14].prefix = pd.inventory[i].PrefixId;
}
p.SendData(PacketTypes.PlayerSlot, "", p.Index, i, pd.inventory[i].PrefixId);
}
}
//异常同步
else
{
var notSelected = 0;
for (var i = 0; i < 3; i++)
{
if (p.TPlayer.CurrentLoadoutIndex != i && pd.currentLoadoutIndex != i)
{
notSelected = i;
}
}
for (var i = 0; i < NetItem.MaxInventory; i++)
{
if (i < NetItem.InventoryIndex.Item2)
{
p.TPlayer.inventory[i] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.inventory[i].stack = pd.inventory[i].Stack;
p.TPlayer.inventory[i].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.ArmorIndex.Item2)
{
var num = i - NetItem.ArmorIndex.Item1;
p.TPlayer.Loadouts[pd.currentLoadoutIndex].Armor[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[pd.currentLoadoutIndex].Armor[num].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[pd.currentLoadoutIndex].Armor[num].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.DyeIndex.Item2)
{
var num = i - NetItem.DyeIndex.Item1;
p.TPlayer.Loadouts[pd.currentLoadoutIndex].Dye[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[pd.currentLoadoutIndex].Dye[num].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[pd.currentLoadoutIndex].Dye[num].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.MiscEquipIndex.Item2)
{
var num = i - NetItem.MiscEquipIndex.Item1;
p.TPlayer.miscEquips[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.miscEquips[num].stack = pd.inventory[i].Stack;
p.TPlayer.miscEquips[num].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.MiscDyeIndex.Item2)
{
var num = i - NetItem.MiscDyeIndex.Item1;
p.TPlayer.miscDyes[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.miscDyes[num].stack = pd.inventory[i].Stack;
p.TPlayer.miscDyes[num].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.PiggyIndex.Item2)
{
var num = i - NetItem.PiggyIndex.Item1;
p.TPlayer.bank.item[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.bank.item[num].stack = pd.inventory[i].Stack;
p.TPlayer.bank.item[num].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.SafeIndex.Item2)
{
var num = i - NetItem.SafeIndex.Item1;
p.TPlayer.bank2.item[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.bank2.item[num].stack = pd.inventory[i].Stack;
p.TPlayer.bank2.item[num].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.TrashIndex.Item2)
{
p.TPlayer.trashItem = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.trashItem.stack = pd.inventory[i].Stack;
p.TPlayer.trashItem.prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.ForgeIndex.Item2)
{
var num = i - NetItem.ForgeIndex.Item1;
p.TPlayer.bank3.item[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.bank3.item[num].stack = pd.inventory[i].Stack;
p.TPlayer.bank3.item[num].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.VoidIndex.Item2)
{
var num = i - NetItem.VoidIndex.Item1;
p.TPlayer.bank4.item[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.bank4.item[num].stack = pd.inventory[i].Stack;
p.TPlayer.bank4.item[num].prefix = pd.inventory[i].PrefixId;
}
else if (i < NetItem.Loadout1Armor.Item2)
{
var num = i - NetItem.Loadout1Armor.Item1;
if (pd.currentLoadoutIndex != 0)
{
if (notSelected == 0)
{
p.TPlayer.Loadouts[0].Armor[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[0].Armor[num].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[0].Armor[num].prefix = pd.inventory[i].PrefixId;
}
else if (p.TPlayer.CurrentLoadoutIndex != 0)
{
p.TPlayer.Loadouts[0].Armor[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[0].Armor[num].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[0].Armor[num].prefix = pd.inventory[i].PrefixId;
}
else
{
p.TPlayer.Loadouts[0].Armor[num].TurnToAir();
p.TPlayer.armor[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.armor[num].stack = pd.inventory[i].Stack;
p.TPlayer.armor[num].prefix = pd.inventory[i].PrefixId;
}
}
}
else if (i < NetItem.Loadout1Dye.Item2)
{
var num = i - NetItem.Loadout1Dye.Item1;
if (pd.currentLoadoutIndex != 0)
{
if (notSelected == 0)
{
p.TPlayer.Loadouts[0].Dye[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[0].Dye[num].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[0].Dye[num].prefix = pd.inventory[i].PrefixId;
}
else if (p.TPlayer.CurrentLoadoutIndex != 0)
{
p.TPlayer.Loadouts[0].Dye[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[0].Dye[num].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[0].Dye[num].prefix = pd.inventory[i].PrefixId;
}
else
{
p.TPlayer.Loadouts[0].Dye[num].TurnToAir();
p.TPlayer.dye[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.dye[num].stack = pd.inventory[i].Stack;
p.TPlayer.dye[num].prefix = pd.inventory[i].PrefixId;
}
}
}
else if (i < NetItem.Loadout2Armor.Item2)
{
var num = i - NetItem.Loadout2Armor.Item1;
if (pd.currentLoadoutIndex != 1)
{
if (notSelected == 1)
{
p.TPlayer.Loadouts[1].Armor[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[1].Armor[num].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[1].Armor[num].prefix = pd.inventory[i].PrefixId;
}
else if (p.TPlayer.CurrentLoadoutIndex != 1)
{
p.TPlayer.Loadouts[1].Armor[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[1].Armor[num].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[1].Armor[num].prefix = pd.inventory[i].PrefixId;
}
else
{
p.TPlayer.Loadouts[1].Armor[num].TurnToAir();
p.TPlayer.armor[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.armor[num].stack = pd.inventory[i].Stack;
p.TPlayer.armor[num].prefix = pd.inventory[i].PrefixId;
}
}
}
else if (i < NetItem.Loadout2Dye.Item2)
{
var num = i - NetItem.Loadout2Dye.Item1;
if (pd.currentLoadoutIndex != 1)
{
if (notSelected == 1)
{
p.TPlayer.Loadouts[1].Dye[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[1].Dye[num].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[1].Dye[num].prefix = pd.inventory[i].PrefixId;
}
else if (p.TPlayer.CurrentLoadoutIndex != 1)
{
p.TPlayer.Loadouts[1].Dye[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[1].Dye[num].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[1].Dye[num].prefix = pd.inventory[i].PrefixId;
}
else
{
p.TPlayer.Loadouts[1].Dye[num].TurnToAir();
p.TPlayer.dye[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.dye[num].stack = pd.inventory[i].Stack;
p.TPlayer.dye[num].prefix = pd.inventory[i].PrefixId;
}
}
}
else if (i < NetItem.Loadout3Armor.Item2)
{
var num = i - NetItem.Loadout3Armor.Item1;
if (pd.currentLoadoutIndex != 2)
{
if (notSelected == 2)
{
p.TPlayer.Loadouts[2].Armor[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[2].Armor[num].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[2].Armor[num].prefix = pd.inventory[i].PrefixId;
}
else
{
if (p.TPlayer.CurrentLoadoutIndex != 2)
{
p.TPlayer.Loadouts[2].Armor[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[2].Armor[num].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[2].Armor[num].prefix = pd.inventory[i].PrefixId;
}
else
{
p.TPlayer.Loadouts[2].Armor[num].TurnToAir();
p.TPlayer.armor[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.armor[num].stack = pd.inventory[i].Stack;
p.TPlayer.armor[num].prefix = pd.inventory[i].PrefixId;
}
}
}
}
else if (i < NetItem.Loadout3Dye.Item2)
{
var num = i - NetItem.Loadout3Dye.Item1;
if (pd.currentLoadoutIndex != 2)
{
if (notSelected == 2)
{
p.TPlayer.Loadouts[2].Dye[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[2].Dye[num].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[2].Dye[num].prefix = pd.inventory[i].PrefixId;
}
else if (p.TPlayer.CurrentLoadoutIndex != 2)
{
p.TPlayer.Loadouts[2].Dye[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.Loadouts[2].Dye[num].stack = pd.inventory[i].Stack;
p.TPlayer.Loadouts[2].Dye[num].prefix = pd.inventory[i].PrefixId;
}
else
{
p.TPlayer.Loadouts[2].Dye[num].TurnToAir();
p.TPlayer.dye[num] = TShock.Utils.GetItemById(pd.inventory[i].NetId);
p.TPlayer.dye[num].stack = pd.inventory[i].Stack;
p.TPlayer.dye[num].prefix = pd.inventory[i].PrefixId;
}
}
}
}
for (var i = 0; i < NetItem.MaxInventory; i++)
{
p.SendData(PacketTypes.PlayerSlot, "", p.Index, i, pd.inventory[i].PrefixId);
}
}
p.TPlayer.statLife = pd.health;
p.TPlayer.statLifeMax = pd.maxHealth;
p.TPlayer.statMana = pd.mana;
p.TPlayer.statManaMax = pd.maxMana;
p.TPlayer.extraAccessory = pd.extraSlot == 1;
p.TPlayer.skinVariant = pd.skinVariant!.Value;
p.TPlayer.hair = pd.hair!.Value;
p.TPlayer.hairDye = pd.hairDye;
p.TPlayer.hairColor = pd.hairColor!.Value;
p.TPlayer.pantsColor = pd.pantsColor!.Value;
p.TPlayer.shirtColor = pd.shirtColor!.Value;
p.TPlayer.underShirtColor = pd.underShirtColor!.Value;
p.TPlayer.shoeColor = pd.shoeColor!.Value;
p.TPlayer.hideVisibleAccessory = pd.hideVisuals;
p.TPlayer.skinColor = pd.skinColor!.Value;
p.TPlayer.eyeColor = pd.eyeColor!.Value;
p.TPlayer.anglerQuestsFinished = pd.questsCompleted;
p.TPlayer.UsingBiomeTorches = pd.usingBiomeTorches == 1;
p.TPlayer.happyFunTorchTime = pd.happyFunTorchTime == 1;
p.TPlayer.unlockedBiomeTorches = pd.unlockedBiomeTorches == 1;
p.TPlayer.ateArtisanBread = pd.ateArtisanBread == 1;
p.TPlayer.usedAegisCrystal = pd.usedAegisCrystal == 1;
p.TPlayer.usedAegisFruit = pd.usedAegisFruit == 1;
p.TPlayer.usedAegisCrystal = pd.usedArcaneCrystal == 1;
p.TPlayer.usedGalaxyPearl = pd.usedGalaxyPearl == 1;
p.TPlayer.usedGummyWorm = pd.usedGummyWorm == 1;
p.TPlayer.usedAmbrosia = pd.usedAmbrosia == 1;
p.TPlayer.unlockedSuperCart = pd.unlockedSuperCart == 1;
p.TPlayer.enabledSuperCart = pd.enabledSuperCart == 1;
//玩家衣服服装,银河珍珠等属性的同步
p.SendData(PacketTypes.PlayerInfo, "", p.Index);
//生命值同步,包含最大值上限
p.SendData(PacketTypes.PlayerHp, "", p.Index);
//魔力值同步,包括上限
p.SendData(PacketTypes.PlayerMana, "", p.Index);
//钓鱼完成任务数目
p.SendData(PacketTypes.NumberOfAnglerQuestsCompleted, "", p.Index);
//清空玩家的buff
ClearAllBuffFromPlayer(p);
return true;
}
/// <summary>
/// 更新玩家的人物属性数据,线下更新类型,写入数据库,不是更新在线的操作
/// </summary>
/// <param name="accId"></param>
/// <param name="pd"></param>
/// <returns></returns>
private bool UpdateTshockDbCharacter(int accId, PlayerData pd)
{
if (!pd.exists)
{
return false;
}
try
{
var temp = TShock.CharacterDB.GetPlayerData(new TSPlayer(-1), accId);
if (temp is { exists: true })
{
TShock.DB.Query("UPDATE tsCharacter SET Health = @0, MaxHealth = @1, Mana = @2, MaxMana = @3, Inventory = @4, spawnX = @6, spawnY = @7, hair = @8, hairDye = @9, hairColor = @10, pantsColor = @11, shirtColor = @12, underShirtColor = @13, shoeColor = @14, hideVisuals = @15, skinColor = @16, eyeColor = @17, questsCompleted = @18, skinVariant = @19, extraSlot = @20, usingBiomeTorches = @21, happyFunTorchTime = @22, unlockedBiomeTorches = @23, currentLoadoutIndex = @24, ateArtisanBread = @25, usedAegisCrystal = @26, usedAegisFruit = @27, usedArcaneCrystal = @28, usedGalaxyPearl = @29, usedGummyWorm = @30, usedAmbrosia = @31, unlockedSuperCart = @32, enabledSuperCart = @33 WHERE Account = @5;", pd.health, pd.maxHealth, pd.mana, pd.maxMana, string.Join("~", pd.inventory), accId, pd.spawnX, pd.spawnY, pd.hair!, pd.hairDye, TShock.Utils.EncodeColor(pd.hairColor)!, TShock.Utils.EncodeColor(pd.pantsColor)!, TShock.Utils.EncodeColor(pd.shirtColor)!, TShock.Utils.EncodeColor(pd.underShirtColor)!, TShock.Utils.EncodeColor(pd.shoeColor)!, TShock.Utils.EncodeBoolArray(pd.hideVisuals)!, TShock.Utils.EncodeColor(pd.skinColor)!, TShock.Utils.EncodeColor(pd.eyeColor)!, pd.questsCompleted, pd.skinVariant!, pd.extraSlot!, pd.usingBiomeTorches, pd.happyFunTorchTime, pd.unlockedBiomeTorches, pd.currentLoadoutIndex, pd.ateArtisanBread, pd.usedAegisCrystal, pd.usedAegisFruit, pd.usedArcaneCrystal, pd.usedGalaxyPearl, pd.usedGummyWorm, pd.usedAmbrosia, pd.unlockedSuperCart, pd.enabledSuperCart);
}
return true;
}
catch (Exception ex)
{
TShock.Log.ConsoleError(GetString("错误:UpdateTshockDBCharacter ") + ex);
return false;
}
}
/// <summary>
/// 在线重置一个玩家的人物数据,离线自己删数据库去
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
private bool ResetPlayer(TSPlayer p)
{
if (!p.IsLoggedIn)
{
return false;
}
try
{
p.TPlayer.statLife = TShock.ServerSideCharacterConfig.Settings.StartingHealth;
p.TPlayer.statLifeMax = TShock.ServerSideCharacterConfig.Settings.StartingHealth;
p.TPlayer.statMana = TShock.ServerSideCharacterConfig.Settings.StartingMana;
p.TPlayer.statManaMax = TShock.ServerSideCharacterConfig.Settings.StartingMana;
//完全清理背包
for (var i = 0; i < NetItem.MaxInventory; i++)
{
if (i < NetItem.InventoryIndex.Item2)
{
p.TPlayer.inventory[i].TurnToAir();
}
else if (i < NetItem.ArmorIndex.Item2)
{
var num = i - NetItem.ArmorIndex.Item1;
p.TPlayer.armor[num].TurnToAir();
}
else if (i < NetItem.DyeIndex.Item2)
{
var num = i - NetItem.DyeIndex.Item1;
p.TPlayer.dye[num].TurnToAir();
}
else if (i < NetItem.MiscEquipIndex.Item2)
{
var num = i - NetItem.MiscEquipIndex.Item1;
p.TPlayer.miscEquips[num].TurnToAir();
}
else if (i < NetItem.MiscDyeIndex.Item2)
{
var num = i - NetItem.MiscDyeIndex.Item1;
p.TPlayer.miscDyes[num].TurnToAir();
}
else if (i < NetItem.PiggyIndex.Item2)
{
var num = i - NetItem.PiggyIndex.Item1;
p.TPlayer.bank.item[num].TurnToAir();
}
else if (i < NetItem.SafeIndex.Item2)
{
var num = i - NetItem.SafeIndex.Item1;
p.TPlayer.bank2.item[num].TurnToAir();
}
else if (i < NetItem.TrashIndex.Item2)
{
p.TPlayer.trashItem.TurnToAir();
}
else if (i < NetItem.ForgeIndex.Item2)
{
var num = i - NetItem.ForgeIndex.Item1;
p.TPlayer.bank3.item[num].TurnToAir();
}
else if (i < NetItem.VoidIndex.Item2)
{
var num = i - NetItem.VoidIndex.Item1;
p.TPlayer.bank4.item[num].TurnToAir();
}
else if (i < NetItem.Loadout1Armor.Item2)
{
var num = i - NetItem.Loadout1Armor.Item1;
p.TPlayer.Loadouts[0].Armor[num].TurnToAir();
}
else if (i < NetItem.Loadout1Dye.Item2)
{
var num = i - NetItem.Loadout1Dye.Item1;
p.TPlayer.Loadouts[0].Dye[num].TurnToAir();
}
else if (i < NetItem.Loadout2Armor.Item2)
{
var num = i - NetItem.Loadout2Armor.Item1;
p.TPlayer.Loadouts[1].Armor[num].TurnToAir();
}
else if (i < NetItem.Loadout2Dye.Item2)
{
var num = i - NetItem.Loadout2Dye.Item1;
p.TPlayer.Loadouts[1].Dye[num].TurnToAir();
}
else if (i < NetItem.Loadout3Armor.Item2)
{
var num = i - NetItem.Loadout3Armor.Item1;
p.TPlayer.Loadouts[2].Armor[num].TurnToAir();
}
else if (i < NetItem.Loadout3Dye.Item2)
{
var num = i - NetItem.Loadout3Dye.Item1;
p.TPlayer.Loadouts[2].Dye[num].TurnToAir();
}
p.SendData(PacketTypes.PlayerSlot, "", p.Index, i);
}
//按照sscConfig的配置进行重置
for (var i = 0; i < NetItem.MaxInventory; i++)
{
if (i < NetItem.InventoryIndex.Item2 && i < TShock.ServerSideCharacterConfig.Settings.StartingInventory.Count && TShock.ServerSideCharacterConfig.Settings.StartingInventory[i].NetId != 0)
{
p.TPlayer.inventory[i] = TShock.Utils.GetItemById(TShock.ServerSideCharacterConfig.Settings.StartingInventory[i].NetId);
p.TPlayer.inventory[i].stack = TShock.ServerSideCharacterConfig.Settings.StartingInventory[i].Stack;
p.TPlayer.inventory[i].prefix = TShock.ServerSideCharacterConfig.Settings.StartingInventory[i].PrefixId;
p.SendData(PacketTypes.PlayerSlot, "", p.Index, i, p.TPlayer.inventory[i].prefix);
}
}
p.TPlayer.unlockedBiomeTorches = false;
p.TPlayer.extraAccessory = false;
p.TPlayer.ateArtisanBread = false;
p.TPlayer.usedAegisCrystal = false;
p.TPlayer.usedAegisFruit = false;
p.TPlayer.usedArcaneCrystal = false;
p.TPlayer.usedGalaxyPearl = false;
p.TPlayer.usedGummyWorm = false;
p.TPlayer.usedAmbrosia = false;
p.TPlayer.unlockedSuperCart = false;
p.SendData(PacketTypes.PlayerInfo, "", p.Index);
p.SendData(PacketTypes.PlayerHp, "", p.Index);
p.SendData(PacketTypes.PlayerMana, "", p.Index);
p.TPlayer.anglerQuestsFinished = 0;
p.SendData(PacketTypes.NumberOfAnglerQuestsCompleted, "", p.Index);
//清理所有buff
ClearAllBuffFromPlayer(p);
return true;
}
catch (Exception ex)
{
TShock.Log.ConsoleError(GetString("错误 ResetPlayer :") + ex);
return false;
}
}
/// <summary>
/// 返回玩家身上物品的字符串,一般情况slot = items.length
/// </summary>
/// <param name="items"></param>
/// <param name="slots"></param>
/// <param name="model">0 返回图标文本,1 返回纯文本</param>
/// <returns></returns>
private static string GetItemsString(Item[] items, int slots, int model = 0)
{
var sb = new StringBuilder();
for (var i = 0; i < slots; i++)
{
var item = items[i];
if (model == 0 && !item.IsAir)
{
sb.Append(item.prefix != 0 ? $"【[i/p{item.prefix}:{item.netID}]】 " : $"【[i/s{item.stack}:{item.netID}]】 ");
}
if (model == 1 && !item.IsAir)
{
if (item.prefix != 0)
{
sb.Append($"[{Lang.prefix[item.prefix].Value}.{item.Name}]");
}
else if (item.stack != 1)
{
sb.Append($"[{item.Name}:{item.stack}]");
}
else
{
sb.Append($"[{item.Name}]");
}
}
}
return sb.ToString();
}
/// <summary>
/// 返回离线玩家身上的字符串,一般情况slot = items.length
/// </summary>
/// <param name="items"></param>
/// <param name="slots"></param>
/// <param name="model">0 返回图标文本,1 返回纯文本</param>
/// <returns></returns>
private static string GetItemsString(NetItem[] items, int slots, int model = 0)
{
var sb = new StringBuilder();
for (var i = 0; i < slots; i++)
{
var item = items[i];
if (model == 0 && item.NetId != 0)
{
if (item.PrefixId != 0)
{
sb.Append($"【[i/p{item.PrefixId}:{item.NetId}]】 ");
}
else
{
sb.Append($"【[i/s{item.Stack}:{item.NetId}]】 ");
}
}
if (model == 1 && item.NetId != 0)
{
if (item.PrefixId != 0)
{
sb.Append($"[{Lang.prefix[item.PrefixId].Value}.{Lang.GetItemName(item.NetId)}]");
}
else if (item.Stack != 1)
{
sb.Append($"[{Lang.GetItemName(item.NetId)}:{item.Stack}]");
}
else
{
sb.Append($"[{Lang.GetItemName(item.NetId)}]");
}
}
}
return sb.ToString();
}
/// <summary>
/// 给出一个字符串和每行几个物品数,返回排列好的字符串,按空格进行分割
/// </summary>
/// <param name="str"> 需要排列的文本 </param>
/// <param name="num"> 一行几个 </param>
/// <param name="block"> </param>
/// <returns></returns>
private static string FormatArrangement(string str, int num, string block = "")
{
if (!string.IsNullOrWhiteSpace(str))
{
var ls = str.Split(' ').ToList();
for (var i = 0; i < ls.Count; i++)
{
if ((i + 1) % (num + 1) == 0)
{
ls.Insert(i, "\n");
}
}
if (block == "")
{
return string.Join(block, ls);
}
var sb = new StringBuilder();
foreach (var s in ls)
{
if (s != "\n")
{
sb.Append(s);
sb.Append(block);
}
else
{
sb.AppendLine();
}
}
return sb.ToString();
}
return "";
}
/// <summary>
/// 返回随机好看的颜色
/// </summary>
/// <returns></returns>
private static Color TextColor()
{
var r = Main.rand.Next(60, 255);
var g = Main.rand.Next(60, 255);
var b = Main.rand.Next(60, 255);
return new Color(r, g, b);
}
/// <summary>
/// 仅仅是回档指令的函数分出的方法,无特殊意义
/// </summary>
/// <param name="args"></param>
/// <param name="slot"></param>
private void MySscBack2(CommandArgs args, int slot)
{
var list = this.BestFindPlayerByNameOrIndex(args.Parameters[0]);
if (list.Count > 1)
{
var names = GetString("检测到符合该条件的玩家数目不唯一,请重新输入\n包含:");
foreach (var v in list)
{
names += v.Name + ", ";
}
_ = names.Remove(names.Length - 2, 2);
args.Player.SendInfoMessage(names);
return;
}
//离线回档
if (list.Count == 0)
{
args.Player.SendInfoMessage(this.playerOfflineWarning);
var user = TShock.UserAccounts.GetUserAccountByName(args.Parameters[0]);
if (user == null)
{
args.Player.SendInfoMessage(this.nonExistPlayerWarning);
}
else
{
var playerData = TShock.CharacterDB.GetPlayerData(new TSPlayer(-1), user.ID);
if (playerData == null || !playerData.exists)
{
args.Player.SendInfoMessage(GetString("未在原数据库中查到该玩家,请检查输入是否正确,该玩家是否避免SSC检测,再重新输入"));
}
else
{
try
{
var playerData2 = ZPDataBase.ReadZPlayerDB(new TSPlayer(-1), user.ID, slot);
if (!playerData2.exists)
{
args.Player.SendMessage(GetString($"回档失败!未找到 [{user.ID} - {slot}] 号该备份"), new Color(255, 0, 0));
}
else
{
if (this.UpdateTshockDbCharacter(user.ID, playerData2))
{
args.Player.SendMessage(GetString($"玩家 [{user.Name}] 回档成功!启用备份 [ {user.ID + "-" + slot} ]"), new Color(0, 255, 0));
}
else
{
args.Player.SendMessage(GetString("回档失败!"), new Color(255, 0, 0));
}
}
}
catch (Exception ex)
{
TShock.Log.ConsoleError(GetString("错误:BackUp ") + ex);
}
}
}
return;
}
//在线回档
if (list.Count == 1)
{
//如果这个人不是管理(无ssc避免),需要同步在线属性UpdatePlayerAll,并且需要原版数据库写入更新才算成功
if (!list[0].HasPermission(Permissions.bypassssc) && this.UpdatePlayerAll(list[0], ZPDataBase.ReadZPlayerDB(list[0], list[0].Account.ID, slot)) && TShock.CharacterDB.InsertPlayerData(list[0]))
{
if (args.Player.Index != list[0].Index)
{
args.Player.SendMessage(GetString($"玩家 [{list[0].Name}] 回档成功!启用备份 [ {list[0].Account.ID + "-" + slot} ]"), new Color(0, 255, 0));
list[0].SendMessage(GetString("您已回档成功!"), new Color(0, 255, 0));
}
else
{
args.Player.SendMessage(GetString($"玩家 [{list[0].Name}] 回档成功!启用备份 [ {list[0].Account.ID + "-" + slot} ]"), new Color(0, 255, 0));
}
}
//如果他是管理,那就不用向原版数据写入了
else if (list[0].HasPermission(Permissions.bypassssc) && this.UpdatePlayerAll(list[0], ZPDataBase.ReadZPlayerDB(list[0], list[0].Account.ID, slot)))
{
if (args.Player.Index != list[0].Index)
{
args.Player.SendMessage(GetString($"玩家 [{list[0].Name}] 回档成功!启用备份 [ {list[0].Account.ID + "-" + slot} ]"), new Color(0, 255, 0));
list[0].SendMessage(GetString("您已回档成功!"), new Color(0, 255, 0));
}
else
{
args.Player.SendMessage(GetString($"玩家 [{list[0].Name}] 回档成功!启用备份 [ {list[0].Account.ID + "-" + slot} ]"), new Color(0, 255, 0));
}
}
else
{
args.Player.SendMessage(GetString("回档失败!未备份数据或该玩家未登录"), new Color(255, 0, 0));
}
}
}
/// <summary>
/// 将 long 秒数时间转化成 xx小时 xx分钟 xx秒 的字符串
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
private string Timetostring(long t)
{
var s = t % 60L;
var min = t / 60L;
var h = 0L;
if (min >= 60L)
{
h = min / 60L;
min %= 60L;
}
return GetString($"{h}小时 {min}分钟 {s}秒");
}
/// <summary>
/// 将 long 硬币数转化成 xx铂 xx金 xx银 xx铜 的字符串
/// </summary>
/// <param name="coin"></param>
/// <param name="model">0代表图标字符串,1代表纯文本</param>
/// <returns></returns>
private string Cointostring(long coin, int model = 0)
{
var copper = coin % 100; //71
coin /= 100;
var silver = coin % 100; //72
coin /= 100;
var gold = coin % 100; //72
coin /= 100;
var platinum = coin; //74
return model == 0
? GetString($"{platinum}[i:74] {gold}[i:73] {silver}[i:72] {copper}[i:71]")
: GetString($"{platinum}铂金币 {gold}金币 {silver}银币 {copper}铜币");
}
/// <summary>
/// 将 50~1,1~25, 这种类型的 id~击杀数, 字符串转化成对应的字典集合
/// </summary>
/// <param name="killstring"></param>
/// <returns></returns>
private static Dictionary<int, int> KillNpcStringToDictionary(string killstring)
{
if (string.IsNullOrWhiteSpace(killstring))
{
return new Dictionary<int, int>();
}
var keyValues = new Dictionary<int, int>();
var list1 = new List<string>(killstring.Split(','));
list1.RemoveAll(string.IsNullOrWhiteSpace);
foreach (var str in list1)
{
var lst = new List<string>(str.Split('~'));
lst.RemoveAll(x => !int.TryParse(x, out _));
if (lst.Count == 2)
{
keyValues.Add(int.Parse(lst[0]), int.Parse(lst[1]));
}
}
return keyValues;
}
/// <summary>
/// 将字典集合转化成对应的 50~1,1~25, 这种类型的 id~击杀数, 字符串
/// </summary>
/// <param name="keyValues"></param>
/// <returns></returns>
private static string DictionaryToKillNpcString(Dictionary<int, int> keyValues)
{
var sb = new StringBuilder();
foreach (var v in keyValues)
{
sb.Append(v.Key);
sb.Append('~');
sb.Append(v.Value);
sb.Append(',');
}
return sb.ToString();
}
/// <summary>
/// 将字典转化成 史莱姆王(2),金金鱼(12),宝箱怪(20) 这样的类型
/// </summary>
/// <param name="keyValues"> 数据 </param>
/// <param name="iswrap"> 是否自动换行 </param>
/// <returns></returns>
private static string DictionaryToVsString(Dictionary<int, int> keyValues, bool iswrap = true)
{
var sb = new StringBuilder();
var count = 0;
foreach (var v in keyValues)
{
count++;
switch (v.Key)//处理一下特殊npc
{
case 592:
sb.Append(GetString($"蹦跶{Lang.GetNPCNameValue(v.Key)}({v.Value}),"));
break;
case 593:
sb.Append(GetString($"游雨{Lang.GetNPCNameValue(v.Key)}({v.Value}),"));
break;
case 564:
sb.Append($"T1{Lang.GetNPCNameValue(v.Key)}({v.Value}),");
break;
case 565:
sb.Append($"T3{Lang.GetNPCNameValue(v.Key)}({v.Value}),");
break;
case 576:
sb.Append($"T2{Lang.GetNPCNameValue(v.Key)}({v.Value}),");
break;
case 577:
sb.Append($"T3{Lang.GetNPCNameValue(v.Key)}({v.Value}),");
break;
case 398:
sb.Append(GetString($"月亮领主({v.Value})"));
break;
default:
sb.Append($"{Lang.GetNPCNameValue(v.Key)}({v.Value}),");
break;
}
if (count % 10 == 0 && iswrap)//防止一行字数过多卡到屏幕边缘看不见了
{
sb.AppendLine();
}
}
if (sb.Length == 0)
{
sb.Append('无');
}
return sb.ToString().Trim().Trim(',');
}
/// <summary>
/// 获得 击杀生物 的总数,由字典计算出
/// </summary>
/// <returns></returns>
private int GetKillNumFromDictionary(Dictionary<int, int> keyValues)
{
return keyValues.Sum(v => v.Value);
}
/// <summary>
/// 导出这个用户成存档plr
/// </summary>
/// <param name="player"></param>
/// <param name="time"> 如果你想导出这个玩家的游玩时间就填,单位秒 </param>
/// <returns></returns>
private bool ExportPlayer(Player? player, long time = 0L)
{
if (player == null)
{
return false;
}
var text = new string(player.name);
//移除不合法的字符
text = this.FormatFileName(text);
var worldname = new string(Main.worldName);
//移除不合法的字符
worldname = this.FormatFileName(worldname);
var playerFileData = new PlayerFileData
{
Metadata = FileMetadata.FromCurrentSettings(FileType.Player),
Player = player,
_isCloudSave = false
};
FileData fileData = playerFileData;
fileData._path = TShock.SavePath + $"/Zhipm/{worldname + this.now}/{text}.plr";
playerFileData.SetPlayTime(new TimeSpan(time * 10000000L));
Main.LocalFavoriteData.ClearEntry(playerFileData);
try
{
var path = playerFileData.Path;
if (string.IsNullOrEmpty(path))
{
return false;
}
if (!Directory.Exists(TShock.SavePath + "/Zhipm/" + worldname + this.now))
{
Directory.CreateDirectory(TShock.SavePath + "/Zhipm/" + worldname + this.now);
}
var aes = Aes.Create();
using Stream stream = new FileStream(path, FileMode.Create);
using var cryptoStream = new CryptoStream(stream, aes.CreateEncryptor(Player.ENCRYPTION_KEY, Player.ENCRYPTION_KEY), CryptoStreamMode.Write);
using var binaryWriter = new BinaryWriter(cryptoStream);
binaryWriter.Write(279);
playerFileData.Metadata.Write(binaryWriter);
Player.Serialize(playerFileData, player, binaryWriter);
binaryWriter.Flush();
cryptoStream.FlushFinalBlock();
stream.Flush();
return true;
}
catch (Exception ex)
{
TShock.Log.ConsoleError(GetString("错误:ExportPlayer ") + ex);
TShock.Log.ConsoleError(GetString("路径:") + playerFileData.Path + GetString(" 名字:") + text);
return false;
}
}
/// <summary>
/// 创造一个玩家,复制其数据,用于导出人物存档
/// </summary>
/// <param name="name"></param>
/// <param name="data"></param>
/// <returns></returns>
private Player? CreateAPlayer(string name, PlayerData data)
{
try
{
var player = new Player
{
name = name,
statLife = data.health,
statLifeMax = data.maxHealth,
statMana = data.mana,
statManaMax = data.maxMana,
extraAccessory = data.extraSlot == 1,
skinVariant = data.skinVariant!.Value,
hair = data.hair!.Value,
hairDye = data.hairDye,
hairColor = data.hairColor!.Value,
pantsColor = data.pantsColor!.Value,
shirtColor = data.shirtColor!.Value,
underShirtColor = data.underShirtColor!.Value,
shoeColor = data.shoeColor!.Value,
hideVisibleAccessory = data.hideVisuals,
skinColor = data.skinColor!.Value,
eyeColor = data.eyeColor!.Value,
anglerQuestsFinished = data.questsCompleted,
UsingBiomeTorches = data.usingBiomeTorches == 1,
happyFunTorchTime = data.happyFunTorchTime == 1,
unlockedBiomeTorches = data.unlockedBiomeTorches == 1,
ateArtisanBread = data.ateArtisanBread == 1,
usedAegisCrystal = data.usedAegisCrystal == 1,
usedAegisFruit = data.usedAegisFruit == 1
};
player.usedAegisCrystal = data.usedArcaneCrystal == 1;
player.usedGalaxyPearl = data.usedGalaxyPearl == 1;
player.usedGummyWorm = data.usedGummyWorm == 1;
player.usedAmbrosia = data.usedAmbrosia == 1;
player.unlockedSuperCart = data.unlockedSuperCart == 1;
player.enabledSuperCart = data.enabledSuperCart == 1;
//正常同步
if (data.currentLoadoutIndex == player.CurrentLoadoutIndex)
{
for (var i = 0; i < NetItem.MaxInventory; i++)
{
if (i < NetItem.InventoryIndex.Item2)
{
player.inventory[i] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.inventory[i].stack = data.inventory[i].Stack;
player.inventory[i].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.ArmorIndex.Item2)
{
var num = i - NetItem.ArmorIndex.Item1;
player.armor[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.armor[num].stack = data.inventory[i].Stack;
player.armor[num].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.DyeIndex.Item2)
{
var num2 = i - NetItem.DyeIndex.Item1;
player.dye[num2] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.dye[num2].stack = data.inventory[i].Stack;
player.dye[num2].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.MiscEquipIndex.Item2)
{
var num3 = i - NetItem.MiscEquipIndex.Item1;
player.miscEquips[num3] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.miscEquips[num3].stack = data.inventory[i].Stack;
player.miscEquips[num3].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.MiscDyeIndex.Item2)
{
var num4 = i - NetItem.MiscDyeIndex.Item1;
player.miscDyes[num4] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.miscDyes[num4].stack = data.inventory[i].Stack;
player.miscDyes[num4].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.PiggyIndex.Item2)
{
var num5 = i - NetItem.PiggyIndex.Item1;
player.bank.item[num5] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.bank.item[num5].stack = data.inventory[i].Stack;
player.bank.item[num5].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.SafeIndex.Item2)
{
var num6 = i - NetItem.SafeIndex.Item1;
player.bank2.item[num6] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.bank2.item[num6].stack = data.inventory[i].Stack;
player.bank2.item[num6].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.TrashIndex.Item2)
{
player.trashItem = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.trashItem.stack = data.inventory[i].Stack;
player.trashItem.prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.ForgeIndex.Item2)
{
var num7 = i - NetItem.ForgeIndex.Item1;
player.bank3.item[num7] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.bank3.item[num7].stack = data.inventory[i].Stack;
player.bank3.item[num7].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.VoidIndex.Item2)
{
var num8 = i - NetItem.VoidIndex.Item1;
player.bank4.item[num8] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.bank4.item[num8].stack = data.inventory[i].Stack;
player.bank4.item[num8].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.Loadout1Armor.Item2)
{
var num9 = i - NetItem.Loadout1Armor.Item1;
player.Loadouts[0].Armor[num9] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[0].Armor[num9].stack = data.inventory[i].Stack;
player.Loadouts[0].Armor[num9].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.Loadout1Dye.Item2)
{
var num10 = i - NetItem.Loadout1Dye.Item1;
player.Loadouts[0].Dye[num10] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[0].Dye[num10].stack = data.inventory[i].Stack;
player.Loadouts[0].Dye[num10].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.Loadout2Armor.Item2)
{
var num11 = i - NetItem.Loadout2Armor.Item1;
player.Loadouts[1].Armor[num11] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[1].Armor[num11].stack = data.inventory[i].Stack;
player.Loadouts[1].Armor[num11].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.Loadout2Dye.Item2)
{
var num12 = i - NetItem.Loadout2Dye.Item1;
player.Loadouts[1].Dye[num12] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[1].Dye[num12].stack = data.inventory[i].Stack;
player.Loadouts[1].Dye[num12].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.Loadout3Armor.Item2)
{
var num13 = i - NetItem.Loadout3Armor.Item1;
player.Loadouts[2].Armor[num13] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[2].Armor[num13].stack = data.inventory[i].Stack;
player.Loadouts[2].Armor[num13].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.Loadout3Dye.Item2)
{
var num14 = i - NetItem.Loadout3Dye.Item1;
player.Loadouts[2].Dye[num14] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[2].Dye[num14].stack = data.inventory[i].Stack;
player.Loadouts[2].Dye[num14].prefix = data.inventory[i].PrefixId;
}
}
}
//异常同步
else
{
var notselected = 0;
for (var i = 0; i < 3; i++)
{
if (player.CurrentLoadoutIndex != i && data.currentLoadoutIndex != i)
{
notselected = i;
}
}
for (var i = 0; i < NetItem.MaxInventory; i++)
{
if (i < NetItem.InventoryIndex.Item2)
{
player.inventory[i] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.inventory[i].stack = data.inventory[i].Stack;
player.inventory[i].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.ArmorIndex.Item2)
{
var num = i - NetItem.ArmorIndex.Item1;
player.Loadouts[data.currentLoadoutIndex].Armor[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[data.currentLoadoutIndex].Armor[num].stack = data.inventory[i].Stack;
player.Loadouts[data.currentLoadoutIndex].Armor[num].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.DyeIndex.Item2)
{
var num = i - NetItem.DyeIndex.Item1;
player.Loadouts[data.currentLoadoutIndex].Dye[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[data.currentLoadoutIndex].Dye[num].stack = data.inventory[i].Stack;
player.Loadouts[data.currentLoadoutIndex].Dye[num].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.MiscEquipIndex.Item2)
{
var num = i - NetItem.MiscEquipIndex.Item1;
player.miscEquips[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.miscEquips[num].stack = data.inventory[i].Stack;
player.miscEquips[num].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.MiscDyeIndex.Item2)
{
var num = i - NetItem.MiscDyeIndex.Item1;
player.miscDyes[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.miscDyes[num].stack = data.inventory[i].Stack;
player.miscDyes[num].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.PiggyIndex.Item2)
{
var num = i - NetItem.PiggyIndex.Item1;
player.bank.item[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.bank.item[num].stack = data.inventory[i].Stack;
player.bank.item[num].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.SafeIndex.Item2)
{
var num = i - NetItem.SafeIndex.Item1;
player.bank2.item[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.bank2.item[num].stack = data.inventory[i].Stack;
player.bank2.item[num].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.TrashIndex.Item2)
{
player.trashItem = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.trashItem.stack = data.inventory[i].Stack;
player.trashItem.prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.ForgeIndex.Item2)
{
var num = i - NetItem.ForgeIndex.Item1;
player.bank3.item[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.bank3.item[num].stack = data.inventory[i].Stack;
player.bank3.item[num].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.VoidIndex.Item2)
{
var num = i - NetItem.VoidIndex.Item1;
player.bank4.item[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.bank4.item[num].stack = data.inventory[i].Stack;
player.bank4.item[num].prefix = data.inventory[i].PrefixId;
}
else if (i < NetItem.Loadout1Armor.Item2)
{
var num = i - NetItem.Loadout1Armor.Item1;
if (data.currentLoadoutIndex != 0)
{
if (notselected == 0)
{
player.Loadouts[0].Armor[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[0].Armor[num].stack = data.inventory[i].Stack;
player.Loadouts[0].Armor[num].prefix = data.inventory[i].PrefixId;
}
else if (player.CurrentLoadoutIndex != 0)
{
player.Loadouts[0].Armor[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[0].Armor[num].stack = data.inventory[i].Stack;
player.Loadouts[0].Armor[num].prefix = data.inventory[i].PrefixId;
}
else
{
player.Loadouts[0].Armor[num].TurnToAir();
player.armor[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.armor[num].stack = data.inventory[i].Stack;
player.armor[num].prefix = data.inventory[i].PrefixId;
}
}
}
else if (i < NetItem.Loadout1Dye.Item2)
{
var num = i - NetItem.Loadout1Dye.Item1;
if (data.currentLoadoutIndex != 0)
{
if (notselected == 0)
{
player.Loadouts[0].Dye[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[0].Dye[num].stack = data.inventory[i].Stack;
player.Loadouts[0].Dye[num].prefix = data.inventory[i].PrefixId;
}
else if (player.CurrentLoadoutIndex != 0)
{
player.Loadouts[0].Dye[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[0].Dye[num].stack = data.inventory[i].Stack;
player.Loadouts[0].Dye[num].prefix = data.inventory[i].PrefixId;
}
else
{
player.Loadouts[0].Dye[num].TurnToAir();
player.dye[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.dye[num].stack = data.inventory[i].Stack;
player.dye[num].prefix = data.inventory[i].PrefixId;
}
}
}
else if (i < NetItem.Loadout2Armor.Item2)
{
var num = i - NetItem.Loadout2Armor.Item1;
if (data.currentLoadoutIndex != 1)
{
if (notselected == 1)
{
player.Loadouts[1].Armor[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[1].Armor[num].stack = data.inventory[i].Stack;
player.Loadouts[1].Armor[num].prefix = data.inventory[i].PrefixId;
}
else if (player.CurrentLoadoutIndex != 1)
{
player.Loadouts[1].Armor[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[1].Armor[num].stack = data.inventory[i].Stack;
player.Loadouts[1].Armor[num].prefix = data.inventory[i].PrefixId;
}
else
{
player.Loadouts[1].Armor[num].TurnToAir();
player.armor[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.armor[num].stack = data.inventory[i].Stack;
player.armor[num].prefix = data.inventory[i].PrefixId;
}
}
}
else if (i < NetItem.Loadout2Dye.Item2)
{
var num = i - NetItem.Loadout2Dye.Item1;
if (data.currentLoadoutIndex != 1)
{
if (notselected == 1)
{
player.Loadouts[1].Dye[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[1].Dye[num].stack = data.inventory[i].Stack;
player.Loadouts[1].Dye[num].prefix = data.inventory[i].PrefixId;
}
else if (player.CurrentLoadoutIndex != 1)
{
player.Loadouts[1].Dye[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[1].Dye[num].stack = data.inventory[i].Stack;
player.Loadouts[1].Dye[num].prefix = data.inventory[i].PrefixId;
}
else
{
player.Loadouts[1].Dye[num].TurnToAir();
player.dye[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.dye[num].stack = data.inventory[i].Stack;
player.dye[num].prefix = data.inventory[i].PrefixId;
}
}
}
else if (i < NetItem.Loadout3Armor.Item2)
{
var num = i - NetItem.Loadout3Armor.Item1;
if (data.currentLoadoutIndex != 2)
{
if (notselected == 2)
{
player.Loadouts[2].Armor[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[2].Armor[num].stack = data.inventory[i].Stack;
player.Loadouts[2].Armor[num].prefix = data.inventory[i].PrefixId;
}
else
{
if (player.CurrentLoadoutIndex != 2)
{
player.Loadouts[2].Armor[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[2].Armor[num].stack = data.inventory[i].Stack;
player.Loadouts[2].Armor[num].prefix = data.inventory[i].PrefixId;
}
else
{
player.Loadouts[2].Armor[num].TurnToAir();
player.armor[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.armor[num].stack = data.inventory[i].Stack;
player.armor[num].prefix = data.inventory[i].PrefixId;
}
}
}
}
else if (i < NetItem.Loadout3Dye.Item2)
{
var num = i - NetItem.Loadout3Dye.Item1;
if (data.currentLoadoutIndex != 2)
{
if (notselected == 2)
{
player.Loadouts[2].Dye[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[2].Dye[num].stack = data.inventory[i].Stack;
player.Loadouts[2].Dye[num].prefix = data.inventory[i].PrefixId;
}
else if (player.CurrentLoadoutIndex != 2)
{
player.Loadouts[2].Dye[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.Loadouts[2].Dye[num].stack = data.inventory[i].Stack;
player.Loadouts[2].Dye[num].prefix = data.inventory[i].PrefixId;
}
else
{
player.Loadouts[2].Dye[num].TurnToAir();
player.dye[num] = TShock.Utils.GetItemById(data.inventory[i].NetId);
player.dye[num].stack = data.inventory[i].Stack;
player.dye[num].prefix = data.inventory[i].PrefixId;
}
}
}
}
}
return player;
}
catch
{
TShock.Log.ConsoleError(GetString($"正常的意外因玩家 [ {name} ] 数据残缺而导出人物失败 CreateAPlayer"));
return null;
}
}
/// <summary>
/// 最好的 在线 查找,先查找用户索引,索引不会被名字干扰,找不到再匹配名字完全相同的玩家,包括大小写,再找不到就模糊查找,不区分大小写
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private List<TSPlayer> BestFindPlayerByNameOrIndex(string str)
{
if (int.TryParse(str, out var num))
{
foreach (var tsPlayer in TShock.Players)
{
if (tsPlayer != null && tsPlayer.Index == num)
{
return new List<TSPlayer> { tsPlayer };
}
}
}
foreach (var tsplayer in TShock.Players)
{
if (tsplayer != null && tsplayer.Name.Equals(str))
{
return new List<TSPlayer> { tsplayer };
}
}
var list = new List<TSPlayer>();
foreach (var tsplayer in TShock.Players)
{
if (tsplayer != null && tsplayer.Name.Contains(str, StringComparison.OrdinalIgnoreCase))
{
list.Add(tsplayer);
}
}
return list;
}
/// <summary>
/// 获得这个玩家身上的钱币数目,单位铜币,支持离线和在线,返回-1代表这个玩家不存在或数据错误
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private long GetPlayerCoin(string name)
{
//如果在线的话
foreach (var ts in TShock.Players)
{
if (ts != null && ts.Name == name)
{
var num = Utils.CoinsCount(out _, ts.TPlayer.inventory, 58, 57, 56, 55, 54);
var num2 = Utils.CoinsCount(out _, ts.TPlayer.bank.item);
var num3 = Utils.CoinsCount(out _, ts.TPlayer.bank2.item);
var num4 = Utils.CoinsCount(out _, ts.TPlayer.bank3.item);
var num5 = Utils.CoinsCount(out _, ts.TPlayer.bank4.item);
return num + num2 + num3 + num4 + num5;
}
}
//离线的话
var user = TShock.UserAccounts.GetUserAccountByName(name);
if (user == null)
{
return -1L;
}
var pd = TShock.CharacterDB.GetPlayerData(new TSPlayer(-1), user.ID);
if (!pd.exists)
{
return -1L;
}
var items = new List<Item>();
foreach (var t in pd.inventory)
{
if (t.NetId is 71 or 72 or 73 or 74)
{
var temp = TShock.Utils.GetItemById(t.NetId);
temp.stack = t.Stack;
temp.prefix = t.PrefixId;
items.Add(temp);
}
}
return Utils.CoinsCount(out _, items.ToArray());
}
/// <summary>
/// 清理这个玩家身上所有buff
/// </summary>
/// <param name="ts"></param>
private static void ClearAllBuffFromPlayer(TSPlayer ts)
{
for (var i = 0; i < 22; i++)
{
ts.TPlayer.buffType[i] = 0;
}
ts.SendData(PacketTypes.PlayerBuff, "", ts.Index);
}
/// <summary>
/// 将tshock里的ips 转换成单独的ip字符串数组
/// </summary>
/// <param name="knownIps"></param>
/// <returns></returns>
private static string[] ToIpStrings(string knownIps)
{
if (string.IsNullOrEmpty(knownIps))
{
return Array.Empty<string>();
}
var ips = knownIps.Split(',');
for (var i = 0; i < ips.Length; i++)
{
ips[i] = ips[i].Replace("\"", "");
ips[i] = ips[i].Replace("[", "");
ips[i] = ips[i].Replace("]", "");
ips[i] = ips[i].Trim();
}
return ips;
}
/// <summary>
/// 向某个玩家发送悬浮字体
/// </summary>
/// <param name="ts"> 需要发送的玩家 </param>
/// <param name="text"> 内容文本 </param>
/// <param name="color"> 颜色 </param>
/// <param name="pos"> 位置 </param>
private void SendText(TSPlayer ts, string text, Color color, Vector2 pos)
{
ts.SendData(PacketTypes.CreateCombatTextExtended, text, (int) color.packedValue, pos.X, pos.Y);
}
/// <summary>
/// 给所有玩家发送悬浮字体,但是根据发起者区分颜色
/// </summary>
/// <param name="ts"> 需要发送的玩家 </param>
/// <param name="text"> 发送文本 </param>
/// <param name="color1"> 被发送者所看见的颜色 </param>
/// <param name="color2"> 除了被发送者其他玩家所看见的颜色 </param>
/// <param name="pos"> 位置 </param>
private void SendAllText(TSPlayer ts, string text, Color color1, Color color2, Vector2 pos)
{
if (!ts.RealPlayer || ts.ConnectionAlive)
{
NetMessage.SendData(119, ts.Index, -1, NetworkText.FromLiteral(text), (int) color1.packedValue, pos.X, pos.Y);
NetMessage.SendData(119, -1, ts.Index, NetworkText.FromLiteral(text), (int) color2.packedValue, pos.X, pos.Y);
}
}
/// <summary>
/// 将boss击杀排行榜的信息打印出来
/// </summary>
/// <param name="bossName"></param>
/// <param name="playerAndDamage"></param>
/// <param name="allDamage"></param>
private static void SendKillBossMessage(string bossName, Dictionary<string, int> playerAndDamage, int allDamage)
{
var sb = new StringBuilder();
var sortpairs = new Dictionary<string, int>();
sb.AppendLine(GetString($"共有 [c/74F3C9:{playerAndDamage.Count}] 位玩家击败了 [c/74F3C9:{bossName}]"));
//简单的排个序
while (playerAndDamage.Count > 0)
{
var key = "";
var damage = 0;
foreach (var v in playerAndDamage)
{
if (v.Value > damage)
{
key = v.Key;
damage = v.Value;
}
}
if (key != "")
{
sortpairs.Add(key, damage);
playerAndDamage.Remove(key);
}
}
foreach (var v in sortpairs)
{
sb.AppendLine(GetString($"{v.Key} 伤害: [c/74F3C9:{v.Value}] 比重: {v.Value * 1.0f / allDamage:0.00%} "));
}
TSPlayer.All.SendMessage(sb.ToString(), Color.Bisque);
}
/// <summary>
/// 将 string 转化为能直接作用于文件名的 string
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private string FormatFileName(string text)
{
//移除不合法的字符
for (var i = 0; i < text.Length; ++i)
{
var flag = text[i] == '\\' || text[i] == '/' || text[i] == ':' || text[i] == '*' || text[i] == '?' || text[i] == '"' || text[i] == '<' || text[i] == '>' || text[i] == '|';
if (flag)
{
text = text.Replace(text[i], '-');
}
}
return text;
}
} | 412 | 0.864646 | 1 | 0.864646 | game-dev | MEDIA | 0.913261 | game-dev | 0.869782 | 1 | 0.869782 |
osgcc/ryzom | 6,174 | ryzom/server/src/entities_game_service/phrase_manager/combat_action_simple_effect.cpp | // Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
// Copyright (C) 2010 Winch Gate Property Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "stdpch.h"
// net
#include "nel/net/message.h"
//
#include "combat_action_simple_effect.h"
#include "phrase_manager/phrase_utilities_functions.h"
#include "combat_phrase.h"
#include "player_manager/player.h"
using namespace std;
using namespace NLMISC;
using namespace NLNET;
//--------------------------------------------------------------
// apply()
//--------------------------------------------------------------
void CCombatActionSimpleEffect::apply(CCombatPhrase *phrase)
{
#if !FINAL_VERSION
nlassert(phrase);
#endif
H_AUTO(CCombatActionSimpleEffect_apply);
_CombatPhrase = phrase;
if (_ApplyOnTargets)
{
const std::vector<CCombatPhrase::TTargetInfos> &targets = phrase->getTargets();
for (uint i = 0; i < targets.size() ; ++i)
{
// if ( !phrase->hasTargetDodged(i) )
if ( phrase->getTargetDodgeFactor(i) == 0.0f )
{
if (targets[i].Target != NULL)
{
//applyOnEntity(targets[i].Target->getEntity(), phrase->getPhraseSuccessDamageFactor());
applyOnEntity(targets[i].Target->getEntity(), 1.0f - phrase->getTargetDodgeFactor(i));
}
}
}
}
else
{
CEntityBase *entity = CEntityBaseManager::getEntityBasePtr(_ActorRowId);
if (!entity)
{
nlwarning("COMBAT : <CCombatActionRegenModifier::apply> Cannot find the target entity, cancel");
return;
}
//applyOnEntity(entity, phrase->getPhraseSuccessDamageFactor());
applyOnEntity(entity, 1.0f);
}
} // apply //
//--------------------------------------------------------------
// applyOnEntity()
//--------------------------------------------------------------
void CCombatActionSimpleEffect::applyOnEntity( CEntityBase *entity, float successFactor )
{
H_AUTO(CCombatActionSimpleEffect_applyOnEntity);
if (!entity || !_CombatPhrase) return;
// if entity is already dead, return
if (entity->isDead())
return;
TGameCycle endDate;
if ( _UsePhraseLatencyAsDuration == true && _CombatPhrase != 0)
{
endDate = _CombatPhrase->latencyEndDate();
}
else
{
endDate = TGameCycle(_Duration*successFactor) + CTickEventHandler::getGameCycle();
}
_Effect = new CSimpleEffect( _ActorRowId, entity->getEntityRowId(), _Family, _EffectValue, endDate, _EffectPower);
if (!_Effect)
{
nlwarning("COMBAT : <CCombatActionSimpleEffect::apply> Failed to allocate new CSimpleEffect object !");
return;
}
entity->addSabrinaEffect(_Effect);
// check an effect name has been set
/* if (_EffectName.empty())
{
nlwarning("COMBAT : Effect name not set for effect family %s", EFFECT_FAMILIES::toString(_Family).c_str() );
return;
}
CEntityId actorId;
if (TheDataset.isDataSetRowStillValid(_ActorRowId))
actorId = TheDataset.getEntityId(_ActorRowId);
TVectorParamCheck params;
/// todo: send info messages to client and spectators
if (entity->getEntityRowId() != _ActorRowId)
{
string msgName = "EFFECT_"+_EffectName+"_BEGIN";
// effect creator
if ( actorId.getType() == RYZOMID::player)
{
params.resize(1);
params[0].Type = STRING_MANAGER::entity;
params[0].EId = entity->getId();
const string str = NLMISC::toString("%s_CREATOR",msgName.c_str());
PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, str, params);
}
// effect target
if (entity->getId().getType() == RYZOMID::player)
{
params.resize(1);
params[0].Type = STRING_MANAGER::entity;
params[0].EId = actorId;
const string str = NLMISC::toString("%s_TARGET",msgName.c_str());
PHRASE_UTILITIES::sendDynamicSystemMessage(entity->getEntityRowId(), str, params);
}
// spectators
CEntityId centerId;
if ( entity->getId().getType() == RYZOMID::player || entity->getId().getType() == RYZOMID::npc)
centerId = entity->getId();
else if ( actorId.getType() == RYZOMID::player || actorId.getType() == RYZOMID::npc)
centerId = actorId;
else
return;
params.resize(2);
params[0].Type = STRING_MANAGER::entity;
params[0].EId = actorId;
params[1].Type = STRING_MANAGER::entity;
params[1].EId = entity->getId();
vector<CEntityId> excluded;
excluded.push_back(actorId);
excluded.push_back(entity->getId());
const string str = NLMISC::toString("%s_SPECTATORS",msgName.c_str());
PHRASE_UTILITIES::sendDynamicGroupSystemMessage(TheDataset.getDataSetRow(centerId), excluded, str, params);
}
else
{
string msgName = "EFFECT_"+_EffectName+"_SELF_BEGIN";
if ( actorId.getType() == RYZOMID::player)
{
const string str = NLMISC::toString("%s_CREATOR",msgName.c_str());
PHRASE_UTILITIES::sendDynamicSystemMessage(_ActorRowId, str);
}
else if( actorId.getType() != RYZOMID::npc )
{
// cannot send spectator messages for creatures
return;
}
params.resize(1);
// send to spectators
switch(actorId.getType())
{
case RYZOMID::player:
params[0].Type = STRING_MANAGER::player;
msgName = "EFFECT_"+_EffectName+"_SELF_BEGIN_SPECTATORS_PLAYER";
break;
case RYZOMID::npc:
params[0].Type = STRING_MANAGER::bot;
msgName = "EFFECT_"+_EffectName+"_SELF_BEGIN_SPECTATORS_NPC";
break;
default:
params[0].Type = STRING_MANAGER::creature;
msgName = "EFFECT_"+_EffectName+"_SELF_BEGIN_SPECTATORS_CREATURE";
break;
};
params[0].EId = actorId;
vector<CEntityId> excluded;
excluded.push_back(actorId);
PHRASE_UTILITIES::sendDynamicGroupSystemMessage(TheDataset.getDataSetRow(actorId), excluded, msgName, params);
}
*/
} // applyOnEntity //
| 412 | 0.864662 | 1 | 0.864662 | game-dev | MEDIA | 0.938505 | game-dev | 0.932939 | 1 | 0.932939 |
Arkensor/DayZCommunityOfflineMode | 2,852 | Missions/DayZCommunityOfflineMode.Enoch/core/CommunityOfflineClient.c | class CommunityOfflineClient extends MissionGameplay
{
protected bool HIVE_ENABLED = true; //Local Hive / Economy / Infected spawn
protected bool m_loaded;
void CommunityOfflineClient()
{
m_loaded = false;
NewModuleManager();
}
override void OnInit()
{
super.OnInit();
InitHive();
SetupWeather();
SpawnPlayer();
GetDayZGame().SetMissionPath( "$saves:CommunityOfflineMode\\" ); // CameraToolsMenu
}
override void OnMissionStart()
{
super.OnMissionStart();
COM_GetModuleManager().OnInit();
COM_GetModuleManager().OnMissionStart();
}
override void OnMissionFinish()
{
COM_GetModuleManager().OnMissionFinish();
CloseAllMenus();
DestroyAllMenus();
if( GetHive() )
{
DestroyHive();
}
super.OnMissionFinish();
}
void OnMissionLoaded()
{
COM_GetModuleManager().OnMissionLoaded();
}
override void OnUpdate( float timeslice )
{
super.OnUpdate( timeslice );
COM_GetModuleManager().OnUpdate( timeslice );
if( !m_loaded && !GetDayZGame().IsLoading() )
{
m_loaded = true;
OnMissionLoaded();
}
}
void SpawnPlayer()
{
// #ifndef MODULE_PERSISTENCY
// GetGame().SelectPlayer( NULL, COM_CreateCustomDefaultCharacter() );
// #endif
// #ifdef DISABLE_PERSISTENCY
GetGame().SelectPlayer( NULL, COM_CreateCustomDefaultCharacter() );
// #endif
}
void InitHive()
{
if ( GetGame().IsClient() && GetGame().IsMultiplayer() ) return;
// RD /s /q "storage_-1" > nul 2>&1
if ( !HIVE_ENABLED ) return;
Hive oHive = GetHive();
if( !oHive )
{
oHive = CreateHive();
}
if( oHive )
{
oHive.InitOffline();
}
oHive.SetShardID("100");
oHive.SetEnviroment("stable");
}
static void SetupWeather()
{
Weather weather = g_Game.GetWeather();
weather.GetOvercast().SetLimits( 0.0 , 2.0 );
weather.GetRain().SetLimits( 0.0 , 2.0 );
weather.GetFog().SetLimits( 0.0 , 2.0 );
weather.GetOvercast().SetForecastChangeLimits( 0.0, 0.0 );
weather.GetRain().SetForecastChangeLimits( 0.0, 0.0 );
weather.GetFog().SetForecastChangeLimits( 0.0, 0.0 );
weather.GetOvercast().SetForecastTimeLimits( 1800 , 1800 );
weather.GetRain().SetForecastTimeLimits( 600 , 600 );
weather.GetFog().SetForecastTimeLimits( 600 , 600 );
weather.GetOvercast().Set( 0.0, 0, 0 );
weather.GetRain().Set( 0.0, 0, 0 );
weather.GetFog().Set( 0.0, 0, 0 );
weather.SetWindMaximumSpeed( 50 );
weather.SetWindFunctionParams( 0, 0, 1 );
}
override UIScriptedMenu CreateScriptedMenu(int id)
{
if(id == EditorMenu.MENU_ID)
{
return new EditorMenu();
}
return super.CreateScriptedMenu(id);
}
}
| 412 | 0.925878 | 1 | 0.925878 | game-dev | MEDIA | 0.902642 | game-dev | 0.989511 | 1 | 0.989511 |
bozimmerman/CoffeeMud | 6,096 | com/planet_ink/coffee_mud/Abilities/Thief/Thief_UsePotion.java | package com.planet_ink.coffee_mud.Abilities.Thief;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2020-2025 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Thief_UsePotion extends ThiefSkill
{
@Override
public String ID()
{
return "Thief_UsePotion";
}
private final static String localizedName = CMLib.lang().L("Use Potion");
@Override
public String name()
{
return localizedName;
}
@Override
protected int canAffectCode()
{
return 0;
}
@Override
protected int canTargetCode()
{
return Ability.CAN_ITEMS;
}
@Override
public int abstractQuality()
{
return Ability.QUALITY_INDIFFERENT;
}
private static final String[] triggerStrings =I(new String[] {"POTION","USEPOTION"});
@Override
public int classificationCode()
{
return Ability.ACODE_THIEF_SKILL|Ability.DOMAIN_POISONING;
}
@Override
public String[] triggerStrings()
{
return triggerStrings;
}
@Override
public int usageType()
{
return USAGE_MOVEMENT|USAGE_MANA;
}
public List<Ability> returnOffensiveAffects(final Potion fromMe)
{
final List<Ability> offenders=new ArrayList<Ability>();
for(final Iterator<Ability> a=fromMe.getSpells().iterator();a.hasNext();)
{
final Ability A=a.next();
if((A!=null)
&&(((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_PRAYER)
||((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_SPELL))
&&(A.abstractQuality()==Ability.QUALITY_MALICIOUS)
&&(A.canTarget(Ability.CAN_MOBS))
&&(CMLib.ableMapper().lowestQualifyingLevel(A.ID())<24)
&&(!A.ID().equals("Poison_Rotten")))
offenders.add(A);
}
return offenders;
}
@Override
public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel)
{
if(commands.size()<2)
{
mob.tell(L("What would you like to apply a potion to, and which potion would you use?"));
return false;
}
final Item target=mob.fetchItem(null,Wearable.FILTER_UNWORNONLY,commands.get(0));
if((target==null)||(!CMLib.flags().canBeSeenBy(target,mob)))
{
mob.tell(L("You don't see '@x1' here.",(commands.get(0))));
return false;
}
if((!(target instanceof Food))
&&(!(target instanceof Drink))
&&(!(target instanceof Weapon)))
{
mob.tell(L("You don't know how to apply a potion to @x1.",target.name(mob)));
return false;
}
if(target.numEffects()>0)
{
if(target.fetchEffect("TemporaryAffects")!=null)
{
mob.tell(L("@x1 is already affected by something.",target.name(mob)));
return false;
}
if((!(target instanceof Weapon))
&&target.fetchEffect("Prop_UseSpellCast2")!=null)
{
mob.tell(L("@x1 is already affected by something.",target.name(mob)));
return false;
}
}
final Item potion=mob.fetchItem(null,Wearable.FILTER_UNWORNONLY,CMParms.combine(commands,1));
if((potion==null)||(!CMLib.flags().canBeSeenBy(potion,mob)))
{
mob.tell(L("You don't see '@x1' here.",CMParms.combine(commands,1)));
return false;
}
if(!(potion instanceof Potion))
{
mob.tell(L("@x1 is not a potion!",potion.name()));
return false;
}
final List<Ability> V=returnOffensiveAffects((Potion)potion);
if((V.size()==0)||(!(potion instanceof Drink)))
{
if(potion.fetchEffect("Poison_Rotten")!=null)
mob.tell(L("@x1 is no longer a potion!",potion.name()));
else
mob.tell(L("@x1 is not an appropriate potion!",potion.name()));
return false;
}
final Drink dPotion=(Drink)potion;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSG_THIEF_ACT,L("<S-NAME> attempt(s) to apply a potion to <T-NAMESELF>."));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
if(success)
{
final Ability A=V.get(0);
if(A!=null)
{
if(target instanceof Weapon)
{
Ability tempA=target.fetchEffect("TemporaryAffects");
if(tempA == null)
{
tempA=CMClass.getAbility("TemporaryAffects");
tempA.startTickDown(mob, target, 10);
tempA.makeLongLasting();
}
tempA.setMiscText("+Prop_FightSpellCast "+adjustedLevel(mob,asLevel)+" 30% "+A.ID());
}
else
{
final Ability tempA=CMClass.getAbility("Prop_UseSpellCast2");
target.addNonUninvokableEffect(tempA);
tempA.setMiscText(A.ID());
}
int amountToTake=dPotion.thirstQuenched()/5;
if(amountToTake<1)
amountToTake=1;
dPotion.setLiquidRemaining(dPotion.liquidRemaining()-amountToTake);
if(dPotion.disappearsAfterDrinking()
||((dPotion instanceof RawMaterial)&&(dPotion.liquidRemaining()<=0)))
dPotion.destroy();
}
}
}
return success;
}
}
| 412 | 0.875749 | 1 | 0.875749 | game-dev | MEDIA | 0.994738 | game-dev | 0.946851 | 1 | 0.946851 |
realharshgautam/Leetcode | 1,616 | 2306-create-binary-tree-from-descriptions/create-binary-tree-from-descriptions.cpp | class Solution {
public:
TreeNode* createBinaryTree(vector<vector<int>>& descriptions) {
unordered_set<int> childrenSet;
unordered_map<int, pair<int, int>> childrenHashmap;
for (auto& desc : descriptions) {
int parent = desc[0];
int child = desc[1];
bool isLeft = desc[2] == 1;
if (childrenHashmap.find(parent) == childrenHashmap.end()) {
childrenHashmap[parent] = { -1, -1 };
}
childrenSet.insert(child);
if (isLeft) {
childrenHashmap[parent].first = child;
} else {
childrenHashmap[parent].second = child;
}
}
int headNodeVal;
for (auto& [parent, children] : childrenHashmap) {
if (childrenSet.find(parent) == childrenSet.end()) {
headNodeVal = parent;
break;
}
}
return constructTree(headNodeVal, childrenHashmap);
}
private:
TreeNode* constructTree(int curNodeVal, unordered_map<int, pair<int, int>>& childrenHashmap) {
TreeNode* newNode = new TreeNode(curNodeVal);
if (childrenHashmap.find(curNodeVal) != childrenHashmap.end()) {
auto& children = childrenHashmap[curNodeVal];
if (children.first != -1) {
newNode->left = constructTree(children.first, childrenHashmap);
}
if (children.second != -1) {
newNode->right = constructTree(children.second, childrenHashmap);
}
}
return newNode;
}
}; | 412 | 0.645153 | 1 | 0.645153 | game-dev | MEDIA | 0.665136 | game-dev | 0.832519 | 1 | 0.832519 |
AstralStudio-Development/ThePitMeltdown | 1,040 | src/main/java/cn/charlotte/pit/enchantment/type/normal/PebbleEnchant.java | package cn.charlotte.pit.enchantment.type.normal;
import cn.charlotte.pit.enchantment.AbstractEnchantment;
import cn.charlotte.pit.enchantment.param.item.ArmorOnly;
import cn.charlotte.pit.enchantment.rarity.EnchantmentRarity;
import cn.charlotte.pit.util.cooldown.Cooldown;
/**
* @Author: Misoryan
* @Created_In: 2021/2/25 14:48
*/
@ArmorOnly
public class PebbleEnchant extends AbstractEnchantment {
@Override
public String getEnchantName() {
return "鹅卵石";
}
@Override
public int getMaxEnchantLevel() {
return 3;
}
@Override
public String getNbtName() {
return "pebble_enchant";
}
@Override
public EnchantmentRarity getRarity() {
return EnchantmentRarity.NORMAL;
}
@Override
public Cooldown getCooldown() {
return null;
}
@Override
public String getUsefulnessLore(int enchantLevel) {
return "&7拾起金锭时获得 &6" + (enchantLevel * 10) + " 硬币" + (enchantLevel >= 3 ?
"/s&7并恢复自身 &c1❤ &7生命值" : "");
}
}
| 412 | 0.599147 | 1 | 0.599147 | game-dev | MEDIA | 0.610012 | game-dev | 0.658003 | 1 | 0.658003 |
shawwn/noh | 7,831 | src/k2/c_occlusionmap.cpp | // (C)2008 S2 Games
// c_occlusionmap.cpp
//
//=============================================================================
//=============================================================================
// Headers
//=============================================================================
#include "k2_common.h"
#include "c_occlusionmap.h"
#include "c_world.h"
#include "c_worldentity.h"
#include "c_heightmap.h"
//=============================================================================
//=============================================================================
// Globals
//=============================================================================
//=============================================================================
/*====================
COcclusionMap::COcclusionMap
====================*/
COcclusionMap::COcclusionMap(EWorldComponent eComponent) :
IWorldComponent(eComponent, _T("OcclusionMap")),
m_bInitialized(false),
m_pTerrain(nullptr),
m_pCombined(nullptr),
m_uiSize(2),
m_fScale(1.0f),
m_bRebuildOcclusion(true)
{
}
/*====================
COcclusionMap::~COcclusionMap
====================*/
COcclusionMap::~COcclusionMap()
{
Release();
}
/*====================
COcclusionMap::Release
====================*/
void COcclusionMap::Release()
{
PROFILE("COcclusionMap::Release");
SAFE_DELETE_ARRAY(m_pTerrain);
SAFE_DELETE_ARRAY(m_pCombined);
}
/*====================
COcclusionMap::Update
====================*/
void COcclusionMap::Update(const CRecti &rect)
{
try
{
}
catch (CException &ex)
{
ex.Process(_T("COcclusionMap::Update() - "), NO_THROW);
}
}
/*====================
COcclusionMap::InitTerrainHeight
====================*/
void COcclusionMap::InitTerrainHeight()
{
try
{
uint uiTileWidth(m_pWorld->GetTileWidth() / m_uiSize);
uint uiTileHeight(m_pWorld->GetTileHeight() / m_uiSize);
for (uint uiMapY(0); uiMapY < uiTileHeight; ++uiMapY)
{
for (uint uiMapX(0); uiMapX < uiTileWidth; ++uiMapX)
{
float fTerrainHeightMax(-FAR_AWAY);
int iBeginX(uiMapX * m_uiSize);
int iBeginY(uiMapY * m_uiSize);
int iEndX((uiMapX + 1) * m_uiSize);
int iEndY((uiMapY + 1) * m_uiSize);
for (int iY(iBeginY); iY < iEndY; ++iY)
{
for (int iX(iBeginX); iX < iEndX; ++iX)
{
if (m_pWorld->GetVisBlocker(iX, iY))
{
fTerrainHeightMax = FAR_AWAY;
}
else
{
// The four grid points associated with this terrain tile
float p1(m_pWorld->GetGridPoint(iX, iY));
float p2(m_pWorld->GetGridPoint(iX, iY + 1));
float p3(m_pWorld->GetGridPoint(iX + 1, iY));
float p4(m_pWorld->GetGridPoint(iX + 1, iY + 1));
fTerrainHeightMax = MAX(fTerrainHeightMax, p1);
fTerrainHeightMax = MAX(fTerrainHeightMax, p2);
fTerrainHeightMax = MAX(fTerrainHeightMax, p3);
fTerrainHeightMax = MAX(fTerrainHeightMax, p4);
}
}
}
m_pTerrain[uiMapY * uiTileWidth + uiMapX] = fTerrainHeightMax;
}
}
}
catch (CException &ex)
{
ex.Process(_T("COcclusionMap::InitTerrainHeight() - "), NO_THROW);
}
}
/*====================
COcclusionMap::Generate
====================*/
bool COcclusionMap::Generate(const CWorld *pWorld)
{
PROFILE("COcclusionMap::Generate");
try
{
Release();
m_pWorld = pWorld;
if (m_pWorld == nullptr)
EX_ERROR(_T("Invalid CWorld pointer"));
m_uiSize = 1 << m_pWorld->GetVisibilitySize();
m_uiTileWidth = m_pWorld->GetTileWidth() / m_uiSize;
m_uiTileHeight = m_pWorld->GetTileHeight() / m_uiSize;
m_fScale = m_pWorld->GetScale() * m_uiSize;
m_pTerrain = K2_NEW_ARRAY(ctx_World, float, m_uiTileWidth*m_uiTileHeight);
m_pCombined = K2_NEW_ARRAY(ctx_World, float, m_uiTileWidth*m_uiTileHeight);
InitTerrainHeight();
MemManager.Copy(m_pCombined, m_pTerrain, m_uiTileWidth * m_uiTileHeight * sizeof(float));
m_bInitialized = true;
return true;
}
catch (CException &ex)
{
m_bInitialized = false;
ex.Process(_T("COcclusionMap::Generate() - "), NO_THROW);
return true;
}
}
/*====================
COcclusionMap::OccludeRegion
====================*/
void COcclusionMap::OccludeRegion(const CVec3f &v3Pos, float fRadius, float fHeight)
{
int iBeginX(INT_FLOOR((v3Pos.x - fRadius) / m_fScale));
int iBeginY(INT_FLOOR((v3Pos.y - fRadius) / m_fScale));
int iEndX(INT_FLOOR((v3Pos.x + fRadius) / m_fScale) + 1);
int iEndY(INT_FLOOR((v3Pos.y + fRadius) / m_fScale) + 1);
iBeginX = CLAMP<int>(iBeginX, 0, m_uiTileWidth);
iBeginY = CLAMP<int>(iBeginY, 0, m_uiTileHeight);
iEndX = CLAMP<int>(iEndX, 0, m_uiTileWidth);
iEndY = CLAMP<int>(iEndY, 0, m_uiTileHeight);
float fTop(v3Pos.z + fHeight);
for (int iY(iBeginY); iY != iEndY; ++iY)
for (int iX(iBeginX); iX != iEndX; ++iX)
m_pCombined[GetCellIndex(iX, iY)] = MAX(m_pCombined[GetCellIndex(iX, iY)], fTop);
}
/*====================
COcclusionMap::AddOccludeRegion
====================*/
void COcclusionMap::AddOccludeRegion(const CVec3f &v3Pos, float fRadius)
{
m_bRebuildOcclusion = true;
}
/*====================
COcclusionMap::RemoveOccludeRegion
====================*/
void COcclusionMap::RemoveOccludeRegion(const CVec3f &v3Pos, float fRadius)
{
m_bRebuildOcclusion = true;
}
/*====================
COcclusionMap::GetRegion
====================*/
bool COcclusionMap::GetRegion(const CRecti &recArea, byte *pDst, float fHeight)
{
if (m_bRebuildOcclusion)
{
MemManager.Copy(m_pCombined, m_pTerrain, m_uiTileWidth * m_uiTileHeight * sizeof(float));
WorldEntList &vEntities(m_pWorld->GetEntityList());
for (WorldEntList_it it(vEntities.begin()), itEnd(vEntities.end()); it != itEnd; ++it)
{
CWorldEntity *pWorldEnt(m_pWorld->GetEntityByHandle(*it));
if (pWorldEnt == nullptr)
continue;
if (pWorldEnt->GetOcclusionRadius() > 0.0f && ~pWorldEnt->GetSurfFlags() & SURF_IGNORE)
OccludeRegion(pWorldEnt->GetPosition(), pWorldEnt->GetOcclusionRadius(), 250.0f);
}
m_bRebuildOcclusion = false;
}
CRecti recClippedArea(recArea);
recClippedArea.left = CLAMP<int>(recClippedArea.left, 0, m_uiTileWidth);
recClippedArea.right = CLAMP<int>(recClippedArea.right, 0, m_uiTileWidth);
recClippedArea.top = CLAMP<int>(recClippedArea.top, 0, m_uiTileHeight);
recClippedArea.bottom = CLAMP<int>(recClippedArea.bottom, 0, m_uiTileHeight);
float *pSrc(&m_pCombined[GetCellIndex(recClippedArea.left, recClippedArea.top)]);
pDst += (recClippedArea.top - recArea.top) * recArea.GetWidth() + (recClippedArea.left - recArea.left);
uint uiSrcSpan(m_uiTileWidth - recClippedArea.GetWidth());
uint uiDstSpan(recArea.GetWidth() - recClippedArea.GetWidth());
for (int iY(0); iY < recClippedArea.GetHeight(); ++iY, pSrc += uiSrcSpan, pDst += uiDstSpan)
{
for (int iX(0); iX < recClippedArea.GetWidth(); ++iX, ++pDst, ++pSrc)
{
*pDst = *pSrc > fHeight ? 255 : 0;
}
}
return true;
}
| 412 | 0.925571 | 1 | 0.925571 | game-dev | MEDIA | 0.896554 | game-dev | 0.992851 | 1 | 0.992851 |
microsoft/SeeingVRtoolkit | 3,907 | Assets/SteamVR/Editor/SteamVR_RenderModelEditor.cs | //======= Copyright (c) Valve Corporation, All rights reserved. ===============
//
// Purpose: Custom inspector display for SteamVR_RenderModel
//
//=============================================================================
using UnityEngine;
using UnityEditor;
using System.Text;
using System.Collections.Generic;
namespace Valve.VR
{
[CustomEditor(typeof(SteamVR_RenderModel)), CanEditMultipleObjects]
public class SteamVR_RenderModelEditor : Editor
{
SerializedProperty script, index, modelOverride, shader, verbose, createComponents, updateDynamically;
static string[] renderModelNames;
int renderModelIndex;
void OnEnable()
{
script = serializedObject.FindProperty("m_Script");
index = serializedObject.FindProperty("index");
modelOverride = serializedObject.FindProperty("modelOverride");
shader = serializedObject.FindProperty("shader");
verbose = serializedObject.FindProperty("verbose");
createComponents = serializedObject.FindProperty("createComponents");
updateDynamically = serializedObject.FindProperty("updateDynamically");
// Load render model names if necessary.
if (renderModelNames == null)
{
renderModelNames = LoadRenderModelNames();
}
// Update renderModelIndex based on current modelOverride value.
if (modelOverride.stringValue != "")
{
for (int i = 0; i < renderModelNames.Length; i++)
{
if (modelOverride.stringValue == renderModelNames[i])
{
renderModelIndex = i;
break;
}
}
}
}
static string[] LoadRenderModelNames()
{
var results = new List<string>();
results.Add("None");
using (var holder = new SteamVR_RenderModel.RenderModelInterfaceHolder())
{
var renderModels = holder.instance;
if (renderModels != null)
{
uint count = renderModels.GetRenderModelCount();
for (uint i = 0; i < count; i++)
{
var buffer = new StringBuilder();
var requiredSize = renderModels.GetRenderModelName(i, buffer, 0);
if (requiredSize == 0)
continue;
buffer.EnsureCapacity((int)requiredSize);
renderModels.GetRenderModelName(i, buffer, requiredSize);
results.Add(buffer.ToString());
}
}
}
return results.ToArray();
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(script);
EditorGUILayout.PropertyField(index);
//EditorGUILayout.PropertyField(modelOverride);
GUILayout.BeginHorizontal();
GUILayout.Label(new GUIContent("Model Override", SteamVR_RenderModel.modelOverrideWarning));
var selected = EditorGUILayout.Popup(renderModelIndex, renderModelNames);
if (selected != renderModelIndex)
{
renderModelIndex = selected;
modelOverride.stringValue = (selected > 0) ? renderModelNames[selected] : "";
}
GUILayout.EndHorizontal();
EditorGUILayout.PropertyField(shader);
EditorGUILayout.PropertyField(verbose);
EditorGUILayout.PropertyField(createComponents);
EditorGUILayout.PropertyField(updateDynamically);
serializedObject.ApplyModifiedProperties();
}
}
} | 412 | 0.776751 | 1 | 0.776751 | game-dev | MEDIA | 0.686163 | game-dev,graphics-rendering | 0.912661 | 1 | 0.912661 |
TastSong/GameProgrammerStudyNotes | 11,760 | GameProgrammingPatterns/Library/PackageCache/com.unity.ugui@1.0.0/Editor/UI/ImageEditor.cs | using System.Linq;
using UnityEngine;
using UnityEditor.AnimatedValues;
using UnityEngine.UI;
namespace UnityEditor.UI
{
/// <summary>
/// Editor class used to edit UI Sprites.
/// </summary>
[CustomEditor(typeof(Image), true)]
[CanEditMultipleObjects]
/// <summary>
/// Custom Editor for the Image Component.
/// Extend this class to write a custom editor for a component derived from Image.
/// </summary>
public class ImageEditor : GraphicEditor
{
SerializedProperty m_FillMethod;
SerializedProperty m_FillOrigin;
SerializedProperty m_FillAmount;
SerializedProperty m_FillClockwise;
SerializedProperty m_Type;
SerializedProperty m_FillCenter;
SerializedProperty m_Sprite;
SerializedProperty m_PreserveAspect;
SerializedProperty m_UseSpriteMesh;
SerializedProperty m_PixelsPerUnitMultiplier;
GUIContent m_SpriteContent;
GUIContent m_SpriteTypeContent;
GUIContent m_ClockwiseContent;
AnimBool m_ShowSlicedOrTiled;
AnimBool m_ShowSliced;
AnimBool m_ShowTiled;
AnimBool m_ShowFilled;
AnimBool m_ShowType;
protected override void OnEnable()
{
base.OnEnable();
m_SpriteContent = EditorGUIUtility.TrTextContent("Source Image");
m_SpriteTypeContent = EditorGUIUtility.TrTextContent("Image Type");
m_ClockwiseContent = EditorGUIUtility.TrTextContent("Clockwise");
m_Sprite = serializedObject.FindProperty("m_Sprite");
m_Type = serializedObject.FindProperty("m_Type");
m_FillCenter = serializedObject.FindProperty("m_FillCenter");
m_FillMethod = serializedObject.FindProperty("m_FillMethod");
m_FillOrigin = serializedObject.FindProperty("m_FillOrigin");
m_FillClockwise = serializedObject.FindProperty("m_FillClockwise");
m_FillAmount = serializedObject.FindProperty("m_FillAmount");
m_PreserveAspect = serializedObject.FindProperty("m_PreserveAspect");
m_UseSpriteMesh = serializedObject.FindProperty("m_UseSpriteMesh");
m_PixelsPerUnitMultiplier = serializedObject.FindProperty("m_PixelsPerUnitMultiplier");
m_ShowType = new AnimBool(m_Sprite.objectReferenceValue != null);
m_ShowType.valueChanged.AddListener(Repaint);
var typeEnum = (Image.Type)m_Type.enumValueIndex;
m_ShowSlicedOrTiled = new AnimBool(!m_Type.hasMultipleDifferentValues && typeEnum == Image.Type.Sliced);
m_ShowSliced = new AnimBool(!m_Type.hasMultipleDifferentValues && typeEnum == Image.Type.Sliced);
m_ShowTiled = new AnimBool(!m_Type.hasMultipleDifferentValues && typeEnum == Image.Type.Tiled);
m_ShowFilled = new AnimBool(!m_Type.hasMultipleDifferentValues && typeEnum == Image.Type.Filled);
m_ShowSlicedOrTiled.valueChanged.AddListener(Repaint);
m_ShowSliced.valueChanged.AddListener(Repaint);
m_ShowTiled.valueChanged.AddListener(Repaint);
m_ShowFilled.valueChanged.AddListener(Repaint);
SetShowNativeSize(true);
}
protected override void OnDisable()
{
m_ShowType.valueChanged.RemoveListener(Repaint);
m_ShowSlicedOrTiled.valueChanged.RemoveListener(Repaint);
m_ShowSliced.valueChanged.RemoveListener(Repaint);
m_ShowTiled.valueChanged.RemoveListener(Repaint);
m_ShowFilled.valueChanged.RemoveListener(Repaint);
}
public override void OnInspectorGUI()
{
serializedObject.Update();
SpriteGUI();
AppearanceControlsGUI();
RaycastControlsGUI();
MaskableControlsGUI();
m_ShowType.target = m_Sprite.objectReferenceValue != null;
if (EditorGUILayout.BeginFadeGroup(m_ShowType.faded))
TypeGUI();
EditorGUILayout.EndFadeGroup();
SetShowNativeSize(false);
if (EditorGUILayout.BeginFadeGroup(m_ShowNativeSize.faded))
{
EditorGUI.indentLevel++;
if ((Image.Type)m_Type.enumValueIndex == Image.Type.Simple)
EditorGUILayout.PropertyField(m_UseSpriteMesh);
EditorGUILayout.PropertyField(m_PreserveAspect);
EditorGUI.indentLevel--;
}
EditorGUILayout.EndFadeGroup();
NativeSizeButtonGUI();
serializedObject.ApplyModifiedProperties();
}
void SetShowNativeSize(bool instant)
{
Image.Type type = (Image.Type)m_Type.enumValueIndex;
bool showNativeSize = (type == Image.Type.Simple || type == Image.Type.Filled) && m_Sprite.objectReferenceValue != null;
base.SetShowNativeSize(showNativeSize, instant);
}
/// <summary>
/// Draw the atlas and Image selection fields.
/// </summary>
protected void SpriteGUI()
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_Sprite, m_SpriteContent);
if (EditorGUI.EndChangeCheck())
{
var newSprite = m_Sprite.objectReferenceValue as Sprite;
if (newSprite)
{
Image.Type oldType = (Image.Type)m_Type.enumValueIndex;
if (newSprite.border.SqrMagnitude() > 0)
{
m_Type.enumValueIndex = (int)Image.Type.Sliced;
}
else if (oldType == Image.Type.Sliced)
{
m_Type.enumValueIndex = (int)Image.Type.Simple;
}
}
(serializedObject.targetObject as Image).DisableSpriteOptimizations();
}
}
/// <summary>
/// Sprites's custom properties based on the type.
/// </summary>
protected void TypeGUI()
{
EditorGUILayout.PropertyField(m_Type, m_SpriteTypeContent);
++EditorGUI.indentLevel;
{
Image.Type typeEnum = (Image.Type)m_Type.enumValueIndex;
bool showSlicedOrTiled = (!m_Type.hasMultipleDifferentValues && (typeEnum == Image.Type.Sliced || typeEnum == Image.Type.Tiled));
if (showSlicedOrTiled && targets.Length > 1)
showSlicedOrTiled = targets.Select(obj => obj as Image).All(img => img.hasBorder);
m_ShowSlicedOrTiled.target = showSlicedOrTiled;
m_ShowSliced.target = (showSlicedOrTiled && !m_Type.hasMultipleDifferentValues && typeEnum == Image.Type.Sliced);
m_ShowTiled.target = (showSlicedOrTiled && !m_Type.hasMultipleDifferentValues && typeEnum == Image.Type.Tiled);
m_ShowFilled.target = (!m_Type.hasMultipleDifferentValues && typeEnum == Image.Type.Filled);
Image image = target as Image;
if (EditorGUILayout.BeginFadeGroup(m_ShowSlicedOrTiled.faded))
{
if (image.hasBorder)
EditorGUILayout.PropertyField(m_FillCenter);
EditorGUILayout.PropertyField(m_PixelsPerUnitMultiplier);
}
EditorGUILayout.EndFadeGroup();
if (EditorGUILayout.BeginFadeGroup(m_ShowSliced.faded))
{
if (image.sprite != null && !image.hasBorder)
EditorGUILayout.HelpBox("This Image doesn't have a border.", MessageType.Warning);
}
EditorGUILayout.EndFadeGroup();
if (EditorGUILayout.BeginFadeGroup(m_ShowTiled.faded))
{
if (image.sprite != null && !image.hasBorder && (image.sprite.texture.wrapMode != TextureWrapMode.Repeat || image.sprite.packed))
EditorGUILayout.HelpBox("It looks like you want to tile a sprite with no border. It would be more efficient to modify the Sprite properties, clear the Packing tag and set the Wrap mode to Repeat.", MessageType.Warning);
}
EditorGUILayout.EndFadeGroup();
if (EditorGUILayout.BeginFadeGroup(m_ShowFilled.faded))
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_FillMethod);
if (EditorGUI.EndChangeCheck())
{
m_FillOrigin.intValue = 0;
}
switch ((Image.FillMethod)m_FillMethod.enumValueIndex)
{
case Image.FillMethod.Horizontal:
m_FillOrigin.intValue = (int)(Image.OriginHorizontal)EditorGUILayout.EnumPopup("Fill Origin", (Image.OriginHorizontal)m_FillOrigin.intValue);
break;
case Image.FillMethod.Vertical:
m_FillOrigin.intValue = (int)(Image.OriginVertical)EditorGUILayout.EnumPopup("Fill Origin", (Image.OriginVertical)m_FillOrigin.intValue);
break;
case Image.FillMethod.Radial90:
m_FillOrigin.intValue = (int)(Image.Origin90)EditorGUILayout.EnumPopup("Fill Origin", (Image.Origin90)m_FillOrigin.intValue);
break;
case Image.FillMethod.Radial180:
m_FillOrigin.intValue = (int)(Image.Origin180)EditorGUILayout.EnumPopup("Fill Origin", (Image.Origin180)m_FillOrigin.intValue);
break;
case Image.FillMethod.Radial360:
m_FillOrigin.intValue = (int)(Image.Origin360)EditorGUILayout.EnumPopup("Fill Origin", (Image.Origin360)m_FillOrigin.intValue);
break;
}
EditorGUILayout.PropertyField(m_FillAmount);
if ((Image.FillMethod)m_FillMethod.enumValueIndex > Image.FillMethod.Vertical)
{
EditorGUILayout.PropertyField(m_FillClockwise, m_ClockwiseContent);
}
}
EditorGUILayout.EndFadeGroup();
}
--EditorGUI.indentLevel;
}
/// <summary>
/// All graphics have a preview.
/// </summary>
public override bool HasPreviewGUI() { return true; }
/// <summary>
/// Draw the Image preview.
/// </summary>
public override void OnPreviewGUI(Rect rect, GUIStyle background)
{
Image image = target as Image;
if (image == null) return;
Sprite sf = image.sprite;
if (sf == null) return;
SpriteDrawUtility.DrawSprite(sf, rect, image.canvasRenderer.GetColor());
}
/// <summary>
/// A string containing the Image details to be used as a overlay on the component Preview.
/// </summary>
/// <returns>
/// The Image details.
/// </returns>
public override string GetInfoString()
{
Image image = target as Image;
Sprite sprite = image.sprite;
int x = (sprite != null) ? Mathf.RoundToInt(sprite.rect.width) : 0;
int y = (sprite != null) ? Mathf.RoundToInt(sprite.rect.height) : 0;
return string.Format("Image Size: {0}x{1}", x, y);
}
}
}
| 412 | 0.949136 | 1 | 0.949136 | game-dev | MEDIA | 0.871453 | game-dev | 0.98885 | 1 | 0.98885 |
osgcc/ryzom | 25,986 | ryzom/client/src/client_sheets/item_sheet.cpp | // Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
// Copyright (C) 2010 Winch Gate Property Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/////////////
// INCLUDE //
/////////////
#include "stdpch.h" // First include for pre-compiled headers.
// Georges
#include "nel/georges/u_form_elm.h"
// Client.
#include "item_sheet.h"
#include "game_share/characteristics.h"
#include "game_share/scores.h"
#include "game_share/skills.h"
#include "game_share/people.h"
#include "game_share/protection_type.h"
#include "nel/misc/i18n.h"
///////////
// USING //
///////////
using namespace std;
using namespace NLMISC;
using namespace NLGEORGES;
// ***************************************************************************
// Easy Macro to translate .typ enum
#define TRANSLATE_ENUM( _Var_, _unknown_, _func_, _key_) \
_Var_ = _unknown_; \
if( !item.getValueByName(val, _key_)) \
debug( toString("Key '%s' not found.", _key_) ); \
else if( (_Var_ = _func_(val)) == _unknown_ ) \
debug(#_Var_ " Unknown: " + val);
// Same but no error if the result of enum is _unknown_
#define TRANSLATE_ENUM_NODB( _Var_, _unknown_, _func_, _key_) \
_Var_ = _unknown_; \
if( !item.getValueByName(val, _key_)) \
debug( toString("Key '%s' not found.", _key_) ); \
else \
_Var_ = _func_(val);
// Easy macro to translate value from georges
#define TRANSLATE_VAL( _Var_, _key_ ) \
if(!item.getValueByName(_Var_, _key_)) \
debug( toString("Key '%s' not found.", _key_) ); \
// ***************************************************************************
//-----------------------------------------------
// CItemSheet :
// Constructor.
//-----------------------------------------------
CItemSheet::CItemSheet()
{
IdShape = 0;
IdShapeFemale = 0;
MapVariant = 0;
ItemType = ITEM_TYPE::UNDEFINED;
Family = ITEMFAMILY::UNDEFINED;
SlotBF= 0;
IdIconBack = 0;
IdIconMain = 0;
IdIconOver = 0;
IdIconOver2 = 0;
IdIconText = 0;
IdAnimSet = 0;
Color = 0;
HasFx = false;
DropOrSell = false;
IsItemNoRent = false;
Stackable = 0;
IsConsumable = false;
IdEffect1 = 0;
IdEffect2 = 0;
IdEffect3 = 0;
IdEffect4 = 0;
Type = CEntitySheet::ITEM;
Bulk= 0.f;
EquipTime= 0;
NeverHideWhenEquiped = false;
RequiredCharac = CHARACTERISTICS::Unknown;
RequiredCharacLevel = 0;
RequiredSkill = SKILLS::unknown;
RequiredSkillLevel = 0;
IconColor= NLMISC::CRGBA::White;
IconBackColor= NLMISC::CRGBA::White;
IconOverColor= NLMISC::CRGBA::White;
IconOver2Color= NLMISC::CRGBA::White;
ItemOrigin = ITEM_ORIGIN::UNKNOWN;
Cosmetic.VPValue = 0;
Cosmetic.Gender = GSGENDER::unknown;
Armor.ArmorType = ARMORTYPE::UNKNOWN;
MeleeWeapon.WeaponType = WEAPONTYPE::UNKNOWN;
MeleeWeapon.Skill = SKILLS::unknown;
MeleeWeapon.DamageType = DMGTYPE::UNDEFINED;
MeleeWeapon.MeleeRange = 0;
RangeWeapon.WeaponType = WEAPONTYPE::UNKNOWN;
RangeWeapon.RangeWeaponType = RANGE_WEAPON_TYPE::Unknown;
RangeWeapon.Skill = SKILLS::unknown;
Ammo.Skill = SKILLS::unknown;
Ammo.DamageType = DMGTYPE::UNDEFINED;
Ammo.Magazine = 0;
Mp.Ecosystem = ECOSYSTEM::unknown;
Mp.MpCategory = MP_CATEGORY::Undefined;
Mp.HarvestSkill = SKILLS::unknown;
Mp.Family = RM_FAMILY::Unknown;
Mp.UsedAsCraftRequirement = false;
Mp.MpColor = 0;
Mp.StatEnergy = 0;
Mp.ItemPartBF = 0;
Shield.ShieldType = SHIELDTYPE::NONE;
Tool.Skill = SKILLS::unknown;
Tool.CraftingToolType = TOOL_TYPE::Unknown;
Tool.CommandRange = 0;
Tool.MaxDonkey = 0;
GuildOption.MoneyCost = 0;
GuildOption.XPCost = 0;
Pet.Slot = 0;
Teleport.Type = TELEPORT_TYPES::NONE;
}// CItemSheet //
//-----------------------------------------------
// build :
// Build the sheet from an external script.
//-----------------------------------------------
void CItemSheet::build(const NLGEORGES::UFormElm &item)
{
// Load the name.
string Shape;
if(!item.getValueByName(Shape, "3d.shape"))
debug("key '3d.shape' not found.");
IdShape = ClientSheetsStrings.add(Shape);
// Load the name.
string ShapeFemale;
if(!item.getValueByName(ShapeFemale, "3d.shape_female"))
debug("key '3d.shape_female' not found.");
IdShapeFemale = ClientSheetsStrings.add(ShapeFemale);
// Get the icon associated.
string IconMain;
if(!item.getValueByName (IconMain, "3d.icon"))
debug("key '3d.icon' not found.");
IconMain = strlwr (IconMain);
IdIconMain = ClientSheetsStrings.add(IconMain);
// Get the icon associated.
string IconBack;
if(!item.getValueByName (IconBack, "3d.icon background"))
debug("key '3d.icon background' not found.");
IconBack = strlwr (IconBack);
IdIconBack = ClientSheetsStrings.add(IconBack);
// Get the icon associated.
string IconOver;
if(!item.getValueByName (IconOver, "3d.icon overlay"))
debug("key '3d.icon overlay' not found.");
IconOver = strlwr (IconOver);
IdIconOver = ClientSheetsStrings.add(IconOver);
// Get the icon associated.
string IconOver2;
if(!item.getValueByName (IconOver2, "3d.icon overlay2"))
debug("key '3d.icon overlay2' not found.");
IconOver2 = strlwr (IconOver2);
IdIconOver2 = ClientSheetsStrings.add(IconOver2);
// Get Special modulate colors
item.getValueByName (IconColor, "3d.IconColor" );
item.getValueByName (IconBackColor, "3d.IconBackColor");
item.getValueByName (IconOverColor, "3d.IconOverColor");
item.getValueByName (IconOver2Color, "3d.IconOver2Color");
// Get the icon text associated.
string IconText;
if(!item.getValueByName (IconText, "3d.text overlay"))
debug("key '3d.text overlay' not found.");
IconText = strlwr (IconText);
IdIconText = ClientSheetsStrings.add(IconText);
// See if this item can be hiden when equiped
if(!item.getValueByName (NeverHideWhenEquiped, "3d.never hide when equiped"))
debug("key '3d.never hide when equiped.");
// Load the different slot in wicth the item can be equipped.
const UFormElm *pElt = 0;
// check uint32 is OK!
nlassert( SLOTTYPE::NB_SLOT_TYPE <= 32 );
SlotBF= 0;
if(item.getNodeByName(&pElt, "basics.EquipmentInfo.EquipmentSlots") && pElt)
{
// Get all slots.
uint size;
if(pElt->getArraySize(size))
{
for(uint i = 0; i < size; ++i)
{
string slotName;
if(pElt->getArrayValue(slotName, i))
{
// Check name.
if(slotName.empty())
debug(toString("The slot name %d is Empty.", i));
// Push the possible slots for the item in the list.
SlotBF|= SINT64_CONSTANT(1)<< (SLOTTYPE::stringToSlotType(NLMISC::toUpper(slotName)));
}
}
}
else
debug("The element 'basics.Equipment Slot' is not an array.");
}
else
debug("Cannot create the element from the name 'basics.Equipment Slot'.");
// Get the Item Family.
string family;
if(!item.getValueByName(family, "basics.family"))
{
debug("Key 'basics.family' not found.");
Family = ITEMFAMILY::UNDEFINED;
}
else
{
Family = (ITEMFAMILY::EItemFamily) ITEMFAMILY::stringToItemFamily(NLMISC::toUpper( family) );
if(Family == ITEMFAMILY::UNDEFINED)
debug("Item Family Undefined.");
}
// Get the Item Type.
string itemtype;
if(!item.getValueByName(itemtype, "basics.ItemType"))
{
debug("Key 'basics.ItemType' not found.");
ItemType = ITEM_TYPE::UNDEFINED;
}
else
{
ItemType = (ITEM_TYPE::TItemType) ITEM_TYPE::stringToItemType(NLMISC::toUpper(itemtype) );
if (ItemType == ITEM_TYPE::UNDEFINED)
debug("Item Type Undefined.");
}
// Get the DropOrSell property
if(!item.getValueByName (DropOrSell, "basics.Drop or Sell"))
debug("key 'basics.Drop or Sell' not found.");
// Get the IsItemNoRent property
if(!item.getValueByName (IsItemNoRent, "basics.No Rent"))
debug("key 'basics.No Rent' not found.");
// Get the stackable property
if(!item.getValueByName (Stackable, "basics.stackable"))
debug("key 'basics.stackable' not found.");
// Get the Consumable property
if(!item.getValueByName (IsConsumable, "basics.Consumable"))
debug("key 'basics.Consumable' not found.");
// Get the texture variante.
if(!item.getValueByName(MapVariant, "3d.map_variant"))
debug("Key '3d.map_variant' not found.");
// Load the name.
string AnimSet;
if(!item.getValueByName(AnimSet, "3d.anim_set"))
debug("key '3d.anim_set' not found.");
// Force the CASE in UPPER to not be CASE SENSITIVE.
else
NLMISC::strlwr(AnimSet);
IdAnimSet = ClientSheetsStrings.add(AnimSet);
// Get the Trail Shape
if(!item.getValueByName(Color, "3d.color"))
debug("key '3d.color' not found.");
// Get the Fx flag
if(!item.getValueByName(HasFx, "3d.has_fx"))
debug("key '3d.has_fx' not found.");
// Get special Effect1
string Effect1;
if(!item.getValueByName(Effect1, "Effects.Effect1"))
debug("key 'Effects.Effect1' not found.");
Effect1 = strlwr(Effect1);
IdEffect1 = ClientSheetsStrings.add(Effect1);
// Get special Effect2
string Effect2;
if(!item.getValueByName(Effect2, "Effects.Effect2"))
debug("key 'Effects.Effect2' not found.");
Effect2 = strlwr(Effect2);
IdEffect2 = ClientSheetsStrings.add(Effect2);
// Get special Effect3
string Effect3;
if(!item.getValueByName(Effect3, "Effects.Effect3"))
debug("key 'Effects.Effect3' not found.");
Effect3 = strlwr(Effect3);
IdEffect3 = ClientSheetsStrings.add(Effect3);
// Get special Effect4
string Effect4;
if(!item.getValueByName(Effect4, "Effects.Effect4"))
debug("key 'Effects.Effect4' not found.");
Effect4 = strlwr(Effect4);
IdEffect4 = ClientSheetsStrings.add(Effect4);
// Get its bulk
TRANSLATE_VAL( Bulk, "basics.Bulk" );
// Get its equip time
TRANSLATE_VAL( EquipTime, "basics.Time to Equip In Ticks" );
// build fx part
FX.build(item, "3d.fx.");
// **** Build Help Infos
string val;
TRANSLATE_ENUM( RequiredCharac, CHARACTERISTICS::Unknown, CHARACTERISTICS::toCharacteristic, "basics.RequiredCharac");
TRANSLATE_VAL( RequiredCharacLevel, "basics.MinRequiredCharacLevel");
TRANSLATE_ENUM( RequiredSkill, SKILLS::unknown, SKILLS::toSkill, "basics.RequiredSkill");
TRANSLATE_VAL( RequiredSkillLevel, "basics.MinRequiredSkillLevel");
// item Origin
TRANSLATE_ENUM ( ItemOrigin, ITEM_ORIGIN::UNKNOWN, ITEM_ORIGIN::stringToEnum, "basics.origin");
/// item craft plan
TRANSLATE_VAL( val, "basics.CraftPlan" );
if (!val.empty())
CraftPlan = CSheetId(val);
// Special according to Family;
switch(Family)
{
// COSMETIC
case ITEMFAMILY::COSMETIC :
{
string sheetName = Id.toString();
string::size_type pos = sheetName.find('.',0);
if (pos == string::npos)
nlwarning("<loadCosmetics> Can't load the VPValue from sheet name in sheet %s", Id.toString().c_str() );
else
{
sint i = (sint)pos - 1;
for(; i >= 0; i-- )
{
if ( !isdigit( sheetName[i] ) )
break;
}
if ( i >= -1 )
{
string val = sheetName.substr( i + 1, pos - i - 1);
NLMISC::fromString( val, Cosmetic.VPValue );
}
}
if ( sheetName.find( "hof" ) != string::npos )
Cosmetic.Gender = GSGENDER::female;
else
Cosmetic.Gender = GSGENDER::male;
}
break;
// ARMOR
case ITEMFAMILY::ARMOR :
{
// ArmorType
TRANSLATE_ENUM ( Armor.ArmorType, ARMORTYPE::UNKNOWN, ARMORTYPE::toArmorType, "armor.Armor category" );
}
break;
// MELEE_WEAPON
case ITEMFAMILY::MELEE_WEAPON :
{
// WeaponType
TRANSLATE_ENUM ( MeleeWeapon.WeaponType, WEAPONTYPE::UNKNOWN, WEAPONTYPE::stringToWeaponType, "melee weapon.category" );
// Skill
TRANSLATE_ENUM ( MeleeWeapon.Skill, SKILLS::unknown, SKILLS::toSkill, "melee weapon.skill" );
// DamageType
TRANSLATE_ENUM ( MeleeWeapon.DamageType, DMGTYPE::UNDEFINED, DMGTYPE::stringToDamageType, "melee weapon.damage type" );
// DamageType
TRANSLATE_VAL ( MeleeWeapon.MeleeRange, "melee weapon.melee range" );
}
break;
// RANGE_WEAPON
case ITEMFAMILY::RANGE_WEAPON :
{
// WeaponType
TRANSLATE_ENUM ( RangeWeapon.WeaponType, WEAPONTYPE::UNKNOWN, WEAPONTYPE::stringToWeaponType, "range weapon.category" );
// Range weapon type
TRANSLATE_ENUM ( RangeWeapon.RangeWeaponType, RANGE_WEAPON_TYPE::Generic, RANGE_WEAPON_TYPE::stringToRangeWeaponType, "range weapon.RangeWeaponType" );
// Skill
TRANSLATE_ENUM ( RangeWeapon.Skill, SKILLS::unknown, SKILLS::toSkill, "range weapon.skill" );
}
break;
// AMMO
case ITEMFAMILY::AMMO :
{
// Skill
TRANSLATE_ENUM ( Ammo.Skill, SKILLS::unknown, SKILLS::toSkill, "ammo.weapon type" );
// DamageType
TRANSLATE_ENUM ( Ammo.DamageType, DMGTYPE::UNDEFINED, DMGTYPE::stringToDamageType, "ammo.damage type" );
// Magazine
TRANSLATE_VAL( Ammo.Magazine, "ammo.magazine" );
}
break;
// RAW_MATERIAL
case ITEMFAMILY::RAW_MATERIAL :
{
// Ecosystem
TRANSLATE_ENUM( Mp.Ecosystem, ECOSYSTEM::unknown, ECOSYSTEM::stringToEcosystem, "mp.Ecosystem" );
// MpCategory
TRANSLATE_ENUM( Mp.MpCategory, MP_CATEGORY::Undefined, MP_CATEGORY::stringToMPCategory, "mp.Category" );
// Skill
TRANSLATE_ENUM( Mp.HarvestSkill, SKILLS::unknown, SKILLS::toSkill, "mp.HarvestSkill" );
// MP Family
TRANSLATE_VAL( Mp.Family, "mp.Family" );
// Faber Item Part
uint i;
char keyTmp[256];
// ensure that if you modify RM_FABER_TYPE, you have to rebuild the item sheets.
nlctassert(RM_FABER_TYPE::NUM_FABER_TYPE == 26);
// ensure that the bitfields are enough (nb: unknown can be stored)
nlctassert(ITEM_ORIGIN::NUM_ITEM_ORIGIN < 256);
// ensure that the bitfield for item part buildable for this MP is possible
nlctassert(RM_FABER_TYPE::NUM_FABER_TYPE <= 32);
// reset
Mp.ItemPartBF= 0;
MpItemParts.clear();
// check if ok for each
for(i=0;i<RM_FABER_TYPE::NUM_FABER_TYPE ;i++)
{
uint32 durability= 0;
string sheetEntry= RM_FABER_TYPE::faberTypeToSheetEntry((RM_FABER_TYPE::TRMFType)i);
// read the associated durablity of the MP faberType
sprintf(keyTmp, "mp.MpParam.%s.Durability", sheetEntry.c_str());
TRANSLATE_VAL(durability, keyTmp);
// If not null, ok this MP is associated to this faberType
if(durability)
{
Mp.ItemPartBF |= SINT64_CONSTANT(1)<<i;
MpItemParts.push_back(CMpItemPart());
CMpItemPart &itemPart= MpItemParts.back();
// read origin filter
sprintf(keyTmp, "mp.MpParam.%s.CraftCivSpec", sheetEntry.c_str());
TRANSLATE_ENUM( itemPart.OriginFilter, ITEM_ORIGIN::UNKNOWN, ITEM_ORIGIN::stringToEnum, keyTmp);
// read each stat
for(uint j=0;j<RM_FABER_STAT_TYPE::NumRMStatType;j++)
{
sprintf(keyTmp, "mp.MpParam.%s.%s", sheetEntry.c_str(), RM_FABER_STAT_TYPE::toString((RM_FABER_STAT_TYPE::TRMStatType)j).c_str());
TRANSLATE_VAL( itemPart.Stats[j], keyTmp);
}
}
}
// UsedAsCraftRequirement
TRANSLATE_VAL( Mp.UsedAsCraftRequirement, "mp.UsedAsCraftRequirement" );
// MpColor
TRANSLATE_VAL( Mp.MpColor, "mp.MpColor" );
// Mp Stat Energy
TRANSLATE_VAL( Mp.StatEnergy, "mp.StatEnergy");
}
break;
// SHIELD
case ITEMFAMILY::SHIELD :
{
// ShieldType
TRANSLATE_ENUM( Shield.ShieldType, SHIELDTYPE::NONE, SHIELDTYPE::stringToShieldType, "shield.Category" );
}
break;
// TOOL: different for any tool
case ITEMFAMILY::CRAFTING_TOOL :
{
// CraftingToolType
TRANSLATE_ENUM( Tool.CraftingToolType, TOOL_TYPE::Unknown, TOOL_TYPE::toToolType, "crafting tool.type");
}
break;
case ITEMFAMILY::HARVEST_TOOL :
{
// Skill
TRANSLATE_ENUM( Tool.Skill, SKILLS::unknown, SKILLS::toSkill, "harvest tool.skill" );
}
break;
case ITEMFAMILY::TAMING_TOOL :
{
// Skill
TRANSLATE_ENUM( Tool.Skill, SKILLS::unknown, SKILLS::toSkill, "taming tool.skill" );
// CommandRange
TRANSLATE_VAL( Tool.CommandRange, "taming tool.command range" );
// MaxDonkey
TRANSLATE_VAL( Tool.MaxDonkey, "taming tool.max donkey" );
}
break;
case ITEMFAMILY::GUILD_OPTION :
{
// Cost in money of the tool
TRANSLATE_VAL( GuildOption.MoneyCost, "guild option.Money Cost" );
// Cost in guild XP
TRANSLATE_VAL( GuildOption.XPCost, "guild option.Guild XP Cost" );
}
break;
case ITEMFAMILY::PET_ANIMAL_TICKET :
{
// Cost in money of the tool
TRANSLATE_VAL( Pet.Slot, "pet.Pet Slot" );
}
break;
case ITEMFAMILY::TELEPORT:
{
// Type of teleport
TRANSLATE_ENUM( Teleport.Type, TELEPORT_TYPES::NONE, TELEPORT_TYPES::getTpTypeFromString, "teleport.Type" );
}
break;
case ITEMFAMILY::SCROLL:
{
// Scroll texture
TRANSLATE_VAL( Scroll.Texture, "Scroll.Texture");
}
break;
case ITEMFAMILY::CONSUMABLE:
{
TRANSLATE_VAL( Consumable.ConsumptionTime, "Consumable.ConsumptionTime");
TRANSLATE_VAL( Consumable.OverdoseTimer, "Consumable.OverdoseTimer");
Consumable.Properties.clear();
for(uint i=0;i<4;i++)
{
string val;
item.getValueByName(val, toString("Consumable.Property %d", i).c_str() );
if(!val.empty() && val!="NULL")
{
Consumable.Properties.push_back(val);
}
}
}
break;
default:
break;
};
}// build //
//-----------------------------------------------
// serial :
// Serialize character sheet into binary data file.
//-----------------------------------------------
void CItemSheet::serial(class NLMISC::IStream &f) throw(NLMISC::EStream)
{
ClientSheetsStrings.serial(f, IdShape);
ClientSheetsStrings.serial(f, IdShapeFemale);
f.serial(SlotBF); // Serialize Slots used.
f.serial(MapVariant); // Serialize Map Variant.
f.serialEnum(Family); // Serialize Family.
f.serialEnum(ItemType); // Serialize ItemType.
ClientSheetsStrings.serial(f, IdIconMain);
ClientSheetsStrings.serial(f, IdIconBack);
ClientSheetsStrings.serial(f, IdIconOver);
ClientSheetsStrings.serial(f, IdIconOver2);
f.serial (IconColor);
f.serial (IconBackColor);
f.serial (IconOverColor);
f.serial (IconOver2Color);
ClientSheetsStrings.serial(f, IdIconText);
ClientSheetsStrings.serial(f, IdAnimSet);
f.serial(Color); // Serialize the item color.
f.serial(HasFx); // Serialize the has fx.
f.serial(DropOrSell);
f.serial(IsItemNoRent);
f.serial(NeverHideWhenEquiped);
f.serial(Stackable);
f.serial(IsConsumable);
f.serial(Bulk);
f.serial(EquipTime);
f.serial(FX);
ClientSheetsStrings.serial(f, IdEffect1);
ClientSheetsStrings.serial(f, IdEffect2);
ClientSheetsStrings.serial(f, IdEffect3);
ClientSheetsStrings.serial(f, IdEffect4);
f.serialCont(MpItemParts);
f.serial(CraftPlan);
f.serialEnum(RequiredCharac);
f.serial(RequiredCharacLevel);
f.serialEnum(RequiredSkill);
f.serial(RequiredSkillLevel);
// **** Serial Help Infos
f.serialEnum(ItemOrigin);
// Different Serial according to family
switch(Family)
{
case ITEMFAMILY::COSMETIC :
f.serial(Cosmetic);
break;
case ITEMFAMILY::ARMOR :
f.serial(Armor);
break;
case ITEMFAMILY::MELEE_WEAPON :
f.serial(MeleeWeapon);
break;
case ITEMFAMILY::RANGE_WEAPON :
f.serial(RangeWeapon);
break;
case ITEMFAMILY::AMMO :
f.serial(Ammo);
break;
case ITEMFAMILY::RAW_MATERIAL :
f.serial(Mp);
break;
case ITEMFAMILY::SHIELD :
f.serial(Shield);
break;
// Same for any tool
case ITEMFAMILY::CRAFTING_TOOL :
case ITEMFAMILY::HARVEST_TOOL :
case ITEMFAMILY::TAMING_TOOL :
f.serial(Tool);
break;
case ITEMFAMILY::GUILD_OPTION :
f.serial(GuildOption);
break;
case ITEMFAMILY::PET_ANIMAL_TICKET :
f.serial(Pet);
break;
case ITEMFAMILY::TELEPORT:
f.serial(Teleport);
break;
case ITEMFAMILY::SCROLL:
f.serial(Scroll);
break;
case ITEMFAMILY::CONSUMABLE:
f.serial(Consumable);
break;
default:
break;
};
}// serial //
// ***************************************************************************
bool CItemSheet::isFaberisable() const
{
// Only those family of item can be repaired/faber/refined.
return Family==ITEMFAMILY::AMMO ||
Family==ITEMFAMILY::ARMOR ||
Family==ITEMFAMILY::MELEE_WEAPON ||
Family==ITEMFAMILY::RANGE_WEAPON ||
Family==ITEMFAMILY::JEWELRY ||
Family==ITEMFAMILY::CRAFTING_TOOL ||
Family==ITEMFAMILY::HARVEST_TOOL ||
Family==ITEMFAMILY::TAMING_TOOL ||
Family==ITEMFAMILY::SHIELD;
}
// ***************************************************************************
SKILLS::ESkills CItemSheet::getRequiredSkill() const
{
switch(Family)
{
// case ITEMFAMILY::ARMOR: return Armor.Skill;
case ITEMFAMILY::MELEE_WEAPON: return MeleeWeapon.Skill;
case ITEMFAMILY::RANGE_WEAPON: return RangeWeapon.Skill;
case ITEMFAMILY::AMMO: return Ammo.Skill;
// case ITEMFAMILY::SHIELD: return SHIELDTYPE::shieldTypeToSkill(Shield.ShieldType);
case ITEMFAMILY::RAW_MATERIAL: return Mp.HarvestSkill;
//
case ITEMFAMILY::HARVEST_TOOL:
case ITEMFAMILY::TAMING_TOOL:
return Tool.Skill;
case ITEMFAMILY::CRAFTING_TOOL:
return SKILLS::SC;
default: return SKILLS::unknown;
}
}
// ***************************************************************************
bool CItemSheet::isUsedAsCraftRequirement() const
{
if(Family!=ITEMFAMILY::RAW_MATERIAL)
return false;
return Mp.UsedAsCraftRequirement;
}
// ***************************************************************************
bool CItemSheet::canBuildSomeItemPart() const
{
if(Family!=ITEMFAMILY::RAW_MATERIAL)
return false;
return Mp.ItemPartBF!=0;
}
// ***************************************************************************
bool CItemSheet::canBuildItemPart(RM_FABER_TYPE::TRMFType e) const
{
if(e<RM_FABER_TYPE::NUM_FABER_TYPE)
{
if(Mp.ItemPartBF&(SINT64_CONSTANT(1)<<e))
return true;
}
// all other cases: false
return false;
}
// ***************************************************************************
bool CItemSheet::canBuildItemPart(RM_FABER_TYPE::TRMFType e, ITEM_ORIGIN::EItemOrigin origin) const
{
if(e<RM_FABER_TYPE::NUM_FABER_TYPE)
{
if(Mp.ItemPartBF&(SINT64_CONSTANT(1)<<e))
{
const CMpItemPart &itemPart= getItemPart(e);
// If this MP can build all origin items, or if origin matchs
if( itemPart.OriginFilter == ITEM_ORIGIN::COMMON ||
itemPart.OriginFilter == origin ||
origin == ITEM_ORIGIN::COMMON )
return true;
}
}
// all other cases: false
return false;
}
// ***************************************************************************
const CItemSheet::CMpItemPart &CItemSheet::getItemPart(RM_FABER_TYPE::TRMFType e) const
{
nlassert(Mp.ItemPartBF&(SINT64_CONSTANT(1)<<e));
// count the number of bits set before reaching this item part
uint index= 0;
for(uint i=0;i<(uint)e;i++)
{
if(Mp.ItemPartBF&(SINT64_CONSTANT(1)<<i))
index++;
}
nlassert(index<MpItemParts.size());
return MpItemParts[index];
}
// ***************************************************************************
bool CItemSheet::hasCharacRequirement(uint itemLevel, CHARACTERISTICS::TCharacteristics &caracType, float &caracValue) const
{
switch( Family )
{
// **** ARMORS / BUCKLERS
case ITEMFAMILY::ARMOR:
case ITEMFAMILY::SHIELD:
switch( ItemType )
{
case ITEM_TYPE::LIGHT_BOOTS:
case ITEM_TYPE::LIGHT_GLOVES:
case ITEM_TYPE::LIGHT_PANTS:
case ITEM_TYPE::LIGHT_SLEEVES:
case ITEM_TYPE::LIGHT_VEST:
// No carac requirement
return false;
case ITEM_TYPE::MEDIUM_BOOTS:
case ITEM_TYPE::MEDIUM_GLOVES:
case ITEM_TYPE::MEDIUM_PANTS:
case ITEM_TYPE::MEDIUM_SLEEVES:
case ITEM_TYPE::MEDIUM_VEST:
case ITEM_TYPE::BUCKLER:
// Constitution requirement
caracType= CHARACTERISTICS::constitution;
caracValue= itemLevel / 1.5f;
return true;
case ITEM_TYPE::HEAVY_BOOTS:
case ITEM_TYPE::HEAVY_GLOVES:
case ITEM_TYPE::HEAVY_PANTS:
case ITEM_TYPE::HEAVY_SLEEVES:
case ITEM_TYPE::HEAVY_VEST:
case ITEM_TYPE::HEAVY_HELMET:
case ITEM_TYPE::SHIELD:
// Constitution requirement
caracType= CHARACTERISTICS::constitution;
caracValue= float((sint)itemLevel - 10);
caracValue= max(caracValue, 0.f);
return true;
default:
// No carac requirement
return false;
}
break;
// **** MELEE_WEAPONS
case ITEMFAMILY::MELEE_WEAPON:
switch( ItemType )
{
case ITEM_TYPE::MAGICIAN_STAFF:
// Intelligence requirement
caracType= CHARACTERISTICS::intelligence;
caracValue= float((sint)itemLevel - 10);
caracValue= max(caracValue, 0.f);
return true;
default:
// Strength requirement
caracType= CHARACTERISTICS::strength;
caracValue= float((sint)itemLevel - 10);
caracValue= max(caracValue, 0.f);
return true;
}
break;
// **** RANGE_WEAPON
case ITEMFAMILY::RANGE_WEAPON:
caracType= CHARACTERISTICS::well_balanced;
caracValue= float((sint)itemLevel - 10);
caracValue= max(caracValue, 0.f);
return true;
// **** OTHERS
default:
// No carac requirement
return false;
}
}
// ***************************************************************************
bool CItemSheet::canExchangeOrGive(bool botChatGift) const
{
// DropOrSell => ok
if(DropOrSell)
return true;
// still can give any item to bot chat
return botChatGift;
}
// ***************************************************************************
void CItemSheet::getItemPartListAsText(ucstring &ipList) const
{
bool all= true;
for(uint i=0;i<RM_FABER_TYPE::NUM_FABER_TYPE;i++)
{
RM_FABER_TYPE::TRMFType faberType= RM_FABER_TYPE::TRMFType(i);
if(canBuildItemPart(faberType))
{
if(!ipList.empty())
ipList+= ", ";
ipList+= RM_FABER_TYPE::toLocalString(faberType);
}
else
{
// Ignore Tools and CampFire
if( faberType!=RM_FABER_TYPE::MPBT &&
faberType!=RM_FABER_TYPE::MPPES &&
faberType!=RM_FABER_TYPE::MPSH &&
faberType!=RM_FABER_TYPE::MPTK &&
faberType!=RM_FABER_TYPE::MPJH &&
faberType!=RM_FABER_TYPE::MPCF )
all= false;
}
}
if(all)
{
ipList= CI18N::get("uihelpItemMPAllCraft");
}
}
| 412 | 0.926288 | 1 | 0.926288 | game-dev | MEDIA | 0.951281 | game-dev | 0.972253 | 1 | 0.972253 |
Dimbreath/AzurLaneData | 1,981 | en-US/view/activity/backhills/thirdanniversary/thirdanniversarysquaremediator.lua | slot0 = class("ThirdAnniversarySquareMediator", import("view.base.ContextMediator"))
slot0.MINI_GAME_OPERATOR = "MINI_GAME_OPERATOR"
slot0.GO_SCENE = "GO_SCENE"
slot0.GO_SUBLAYER = "GO_SUBLAYER"
slot0.MINIGAME_OPERATION = "MINIGAME_OPERATION"
slot0.ON_OPEN_TOWERCLIMBING_SIGNED = "ON_OPEN_TOWERCLIMBING_SIGNED"
slot0.ACTIVITY_OPERATION = "ACTIVITY_OPERATION"
function slot0.register(slot0)
slot0:BindEvent()
slot1 = getProxy(ActivityProxy):getActivityByType(ActivityConst.ACTIVITY_TYPE_BUILDING_BUFF)
slot0.activity = slot1
slot0.viewComponent:UpdateActivity(slot1)
end
function slot0.BindEvent(slot0)
slot0:bind(uv0.GO_SCENE, function (slot0, slot1, ...)
uv0:sendNotification(GAME.GO_SCENE, slot1, ...)
end)
slot0:bind(uv0.GO_SUBLAYER, function (slot0, slot1, slot2)
uv0:addSubLayers(slot1, nil, slot2)
end)
slot0:bind(uv0.MINI_GAME_OPERATOR, function (slot0, ...)
uv0:sendNotification(GAME.SEND_MINI_GAME_OP, ...)
end)
slot0:bind(uv0.ON_OPEN_TOWERCLIMBING_SIGNED, function ()
uv0:sendNotification(GAME.GO_SCENE, SCENE.ACTIVITY, {
id = ActivityConst.TOWERCLIMBING_SIGN
})
end)
slot0:bind(uv0.ACTIVITY_OPERATION, function (slot0, slot1)
slot1.activity_id = uv0.activity.id
uv0:sendNotification(GAME.ACTIVITY_OPERATION, slot1)
end)
end
function slot0.listNotificationInterests(slot0)
return {
GAME.SEND_MINI_GAME_OP_DONE,
ActivityProxy.ACTIVITY_UPDATED
}
end
function slot0.handleNotification(slot0, slot1)
slot3 = slot1:getBody()
if slot1:getName() == GAME.SEND_MINI_GAME_OP_DONE then
seriesAsync({
function (slot0)
if #uv0.awards > 0 then
uv1.viewComponent:emit(BaseUI.ON_ACHIEVE, slot1, slot0)
else
slot0()
end
end,
function (slot0)
uv0.viewComponent:UpdateView()
end
})
elseif slot2 == ActivityProxy.ACTIVITY_UPDATED and slot3:getConfig("type") == ActivityConst.ACTIVITY_TYPE_BUILDING_BUFF then
slot0.activity = slot3
slot0.viewComponent:UpdateActivity(slot3)
end
end
return slot0
| 412 | 0.637517 | 1 | 0.637517 | game-dev | MEDIA | 0.930026 | game-dev | 0.87269 | 1 | 0.87269 |
SagaciousG/ETPlugins | 1,478 | Unity/Assets/Scripts/Codes/Hotfix/Server/A/Scenes/Robot/RobotManagerComponentSystem.cs | using System;
using System.Linq;
namespace ET.Server
{
public static class RobotManagerComponentSystem
{
public static async ETTask<Scene> NewRobot(this RobotManagerComponent self, int zone)
{
Scene clientScene = null;
try
{
clientScene = await Client.SceneFactory.CreateClientScene(zone, "Robot");
await Client.LoginHelper.Login(clientScene, zone.ToString(), zone.ToString());
await Client.EnterMapHelper.EnterMapAsync(clientScene);
Log.Debug($"create robot ok: {zone}");
return clientScene;
}
catch (Exception e)
{
clientScene?.Dispose();
throw new Exception($"RobotSceneManagerComponent create robot fail, zone: {zone}", e);
}
}
public static void RemoveAll(this RobotManagerComponent self)
{
foreach (Entity robot in self.Children.Values.ToArray())
{
robot.Dispose();
}
}
public static void Remove(this RobotManagerComponent self, long id)
{
self.GetChild<Scene>(id)?.Dispose();
}
public static void Clear(this RobotManagerComponent self)
{
foreach (Entity entity in self.Children.Values.ToArray())
{
entity.Dispose();
}
}
}
} | 412 | 0.752739 | 1 | 0.752739 | game-dev | MEDIA | 0.661731 | game-dev | 0.912744 | 1 | 0.912744 |
open-goal/jak-project | 35,563 | test/decompiler/reference/jak2/levels/city/kiddogescort/kidesc-states_REF.gc | ;;-*-Lisp-*-
(in-package goal)
;; failed to figure out what this is:
(defstate waiting-idle (kid-escort)
:virtual #t
:event enemy-event-handler
:enter (behavior ()
(set-time! (-> self state-time))
(let ((v1-2 self))
(set! (-> v1-2 enemy-flags) (the-as enemy-flag (logclear (-> v1-2 enemy-flags) (enemy-flag enemy-flag36))))
(set! (-> v1-2 nav callback-info) *nav-enemy-null-callback-info*)
)
0
(nav-enemy-method-167 self)
(let ((v1-7 self))
(set! (-> v1-7 enemy-flags) (the-as enemy-flag (logclear (-> v1-7 enemy-flags) (enemy-flag enemy-flag37))))
)
0
(vector-reset! (-> self root transv))
(look-at-target! self (enemy-flag look-at-focus))
(set! (-> self travel-anim-interp) 0.0)
)
:trans (behavior ()
(bot-method-223 self #f)
(b!
(not (and (-> self focus-info fproc) (>= (fabs (-> self focus-info ry-diff)) 9102.223)))
cfg-6
:delay (empty-form)
)
(go-waiting-turn self)
(b! #t cfg-15 :delay (nop!))
(label cfg-6)
(if (the-as process (as-type (handle->process (-> self arrestor-handle)) process-focusable))
(go-virtual arrested)
)
(label cfg-15)
(when (not (focus-test? self grabbed))
(cond
((logtest? (-> self bot-flags) (bot-flags bf15))
(go-virtual move-to-vehicle)
)
((not (outside-spot-radius? self (the-as bot-spot #f) (the-as vector #f) #f))
(go-virtual traveling)
)
)
)
)
:code (behavior ()
(let ((v1-2 (ja-group)))
(cond
((and v1-2 (= v1-2 kid-escort-idle0-ja))
(ja-no-eval :num! (seek! max 0.1))
(while (not (ja-done? 0))
(suspend)
(ja-eval)
)
)
(else
(ja-channel-push! 1 (seconds 0.2))
)
)
)
(until #f
(ja-no-eval :group! kid-escort-idle0-ja :num! (seek! max 0.1) :frame-num 0.0)
(until (ja-done? 0)
(suspend)
(ja :num! (seek! max 0.1))
)
)
#f
)
:post nav-enemy-simple-post
)
;; failed to figure out what this is:
(defstate waiting-turn (kid-escort)
:virtual #t
:event enemy-event-handler
:enter (behavior ()
(set-time! (-> self state-time))
(let ((v1-2 self))
(set! (-> v1-2 enemy-flags) (the-as enemy-flag (logclear (-> v1-2 enemy-flags) (enemy-flag enemy-flag36))))
(set! (-> v1-2 nav callback-info) *nav-enemy-null-callback-info*)
)
0
(nav-enemy-method-167 self)
(let ((v1-7 self))
(set! (-> v1-7 enemy-flags) (the-as enemy-flag (logclear (-> v1-7 enemy-flags) (enemy-flag enemy-flag37))))
)
0
(look-at-target! self (enemy-flag look-at-focus))
(set! (-> self travel-anim-interp) 0.0)
)
:trans (behavior ()
(bot-method-223 self #f)
(when (not (focus-test? self grabbed))
(if (and (not (outside-spot-radius? self (the-as bot-spot #f) (the-as vector #f) #f))
(and (not (the-as process (as-type (handle->process (-> self arrestor-handle)) process-focusable)))
(not (logtest? (-> self bot-flags) (bot-flags bf15)))
)
)
(go-virtual traveling)
)
)
)
:code (behavior ()
(ja-channel-push! 1 (seconds 0.1))
(ja-no-eval :group! kid-escort-turn0-ja :num! (seek!) :frame-num 0.0)
(until (ja-done? 0)
(suspend)
(ja :num! (seek!))
)
(check-arrest self)
)
:post (behavior ()
(seek-toward-heading-vec! (-> self root) (-> self focus-info bullseye-xz-dir) 49152.0 (seconds 0.05))
(nav-enemy-simple-post)
)
)
;; failed to figure out what this is:
(defstate traveling (kid-escort)
:virtual #t
:event enemy-event-handler
:enter (behavior ()
(set-time! (-> self state-time))
(let ((v1-2 self))
(if (not (logtest? (enemy-flag enemy-flag36) (-> v1-2 enemy-flags)))
(set! (-> v1-2 enemy-flags) (the-as enemy-flag (logior (enemy-flag enemy-flag38) (-> v1-2 enemy-flags))))
)
(set! (-> v1-2 enemy-flags) (the-as enemy-flag (logior (enemy-flag enemy-flag36) (-> v1-2 enemy-flags))))
(set! (-> v1-2 nav callback-info) (-> v1-2 enemy-info callback-info))
)
0
(let ((v1-5 self))
(set! (-> v1-5 enemy-flags) (the-as enemy-flag (logior (enemy-flag enemy-flag37) (-> v1-5 enemy-flags))))
)
0
(stop-looking-at-target! self)
(nav-enemy-method-166 self)
(set! (-> self player-blocking) 0.0)
)
:trans (behavior ()
(bot-method-223 self #f)
(cond
((the-as process (as-type (handle->process (-> self arrestor-handle)) process-focusable))
(go-virtual arrested)
)
((logtest? (-> self bot-flags) (bot-flags bf15))
(go-virtual move-to-vehicle)
)
((outside-spot-radius? self (the-as bot-spot #f) (the-as vector #f) #t)
(check-arrest self)
)
((and (time-elapsed? (-> self state-time) (seconds 0.5)) (bot-method-208 self))
(go-virtual traveling-blocked)
)
((and (nav-enemy-method-163 self) (time-elapsed? (-> self state-time) (-> self reaction-time)))
(go-stare2 self)
)
)
0
)
:code (behavior ()
(until #f
(play-walk-anim self)
(suspend)
)
#f
)
:post (behavior ()
(let ((a0-0 (-> self nav state))
(v1-1 (-> self spot))
)
(logclear! (-> a0-0 flags) (nav-state-flag directional-mode))
(logior! (-> a0-0 flags) (nav-state-flag target-poly-dirty))
(set! (-> a0-0 target-post quad) (-> v1-1 center quad))
)
0
(nav-enemy-travel-post)
)
)
;; failed to figure out what this is:
(defstate move-to-vehicle (kid-escort)
:virtual #t
:event enemy-event-handler
:enter (behavior ()
(set-time! (-> self state-time))
(let ((v1-2 self))
(if (not (logtest? (enemy-flag enemy-flag36) (-> v1-2 enemy-flags)))
(set! (-> v1-2 enemy-flags) (the-as enemy-flag (logior (enemy-flag enemy-flag38) (-> v1-2 enemy-flags))))
)
(set! (-> v1-2 enemy-flags) (the-as enemy-flag (logior (enemy-flag enemy-flag36) (-> v1-2 enemy-flags))))
(set! (-> v1-2 nav callback-info) (-> v1-2 enemy-info callback-info))
)
0
(let ((v1-5 self))
(set! (-> v1-5 enemy-flags) (the-as enemy-flag (logior (enemy-flag enemy-flag37) (-> v1-5 enemy-flags))))
)
0
(stop-looking-at-target! self)
(nav-enemy-method-166 self)
(set! (-> self player-blocking) 0.0)
(logclear! (-> self focus-status) (focus-status arrestable))
)
:trans (behavior ()
(bot-method-223 self #f)
(let ((gp-0 (handle->process (-> self vehicle-handle))))
(cond
((the-as process (as-type (handle->process (-> self arrestor-handle)) process-focusable))
(go-virtual arrested)
)
((or (not gp-0)
(logtest? (-> (the-as vehicle gp-0) flags) (rigid-body-object-flag dead))
(not (logtest? (-> self bot-flags) (bot-flags bf15)))
(< (-> self vehicle-seat-index) 0)
)
(logclear! (-> self bot-flags) (bot-flags bf15))
(check-arrest self)
)
((and (time-elapsed? (-> self state-time) (seconds 0.5)) (bot-method-208 self))
(go-virtual traveling-blocked)
)
((and (nav-enemy-method-163 self) (time-elapsed? (-> self state-time) (-> self reaction-time)))
(go-stare2 self)
)
)
(let ((s5-1 (new 'stack-no-clear 'inline-array 'matrix 2)))
(compute-seat-position (the-as vehicle gp-0) (the-as vector (-> s5-1 0)) (-> self vehicle-seat-index))
(set! (-> s5-1 0 vector 1 quad) (-> self root trans quad))
(set! (-> s5-1 0 trans quad) (-> s5-1 0 quad 0))
(vector-! (the-as vector (-> s5-1 1)) (the-as vector (-> s5-1 0)) (-> (the-as vehicle gp-0) root trans))
(vector-z-quaternion! (-> s5-1 0 vector 2) (-> self root quat))
(let ((f30-1 (* 0.5 (vector-vector-xz-distance (-> s5-1 0 vector 1) (-> s5-1 0 trans)))))
(vector-normalize! (-> s5-1 0 vector 2) (* 2.0 f30-1))
(vector-normalize! (the-as vector (-> s5-1 1)) (* 4.0 f30-1))
)
(bot-method-181
self
(-> s5-1 1 vector 1)
(-> s5-1 0 vector 1)
(-> s5-1 0 vector 2)
(-> s5-1 0 trans)
(the-as vector (-> s5-1 1))
0.8
)
(let ((a0-30 (-> self nav state))
(v1-55 (-> s5-1 1 vector 1))
)
(logclear! (-> a0-30 flags) (nav-state-flag directional-mode))
(logior! (-> a0-30 flags) (nav-state-flag target-poly-dirty))
(set! (-> a0-30 target-post quad) (-> v1-55 quad))
)
0
(if (and (< (vector-vector-xz-distance (the-as vector (-> s5-1 0)) (-> self root trans)) 17203.2)
(< (fabs (- (-> s5-1 0 vector 0 y) (-> self root trans y))) 20480.0)
)
(go-virtual board-vehicle)
)
)
)
)
:code (behavior ()
(until #f
(play-walk-anim self)
(suspend)
)
#f
)
:post nav-enemy-travel-post
)
;; failed to figure out what this is:
(defstate board-vehicle (kid-escort)
:virtual #t
:event enemy-event-handler
:enter (behavior ()
(set-time! (-> self state-time))
(let ((v1-2 self))
(set! (-> v1-2 enemy-flags) (the-as enemy-flag (logclear (-> v1-2 enemy-flags) (enemy-flag enemy-flag36))))
(set! (-> v1-2 nav callback-info) *nav-enemy-null-callback-info*)
)
0
(let ((v1-5 self))
(set! (-> v1-5 enemy-flags) (the-as enemy-flag (logclear (-> v1-5 enemy-flags) (enemy-flag enemy-flag37))))
)
0
(let ((gp-0 (handle->process (-> self vehicle-handle))))
(when (or (not (logtest? (-> self bot-flags) (bot-flags bf15))) (< (-> self vehicle-seat-index) 0))
(logclear! (-> self bot-flags) (bot-flags bf15))
(check-arrest self)
)
(put-rider-in-seat (the-as vehicle gp-0) (-> self vehicle-seat-index) self)
)
(logior! (-> self focus-status) (focus-status pilot))
(logclear! (-> self enemy-flags) (enemy-flag vulnerable))
(logior! (-> self focus-status) (focus-status disable))
(logclear! (-> self focus-status) (focus-status arrestable))
(logclear! (-> self bot-flags) (bot-flags bf15))
)
:exit (behavior ()
(local-vars (v1-6 enemy-flag))
(logior! (-> self root nav-flags) (nav-flags has-root-sphere))
(logclear! (-> self focus-status) (focus-status disable))
(let ((v1-5 (-> self enemy-flags)))
(if (logtest? v1-5 (enemy-flag vulnerable-backup))
(set! v1-6 (logior v1-5 (enemy-flag vulnerable)))
(set! v1-6 (logclear v1-5 (enemy-flag vulnerable)))
)
)
(set! (-> self enemy-flags) v1-6)
(logclear! (-> self bot-flags) (bot-flags bf15))
)
:trans (behavior ()
(check-vehicle-exit self)
)
:code (behavior ()
(local-vars (sv-112 float))
(ja-channel-push! 1 (seconds 0.1))
(let ((gp-0 (new 'stack-no-clear 'matrix)))
(quaternion-copy! (the-as quaternion (-> gp-0 vector)) (-> self root quat))
(ja-no-eval :group! kid-escort-jump-in-vehicle-ja
:num! (seek! (ja-aframe 1.0 0) 0.25)
:frame-num (ja-aframe 0.0 0)
)
(until (ja-done? 0)
(let ((s5-1 (handle->process (-> self vehicle-handle)))
(f30-0 (lerp-scale 0.0 1.0 (ja-aframe-num 0) (ja-aframe 0.0 0) (ja-aframe 1.0 0)))
)
(compute-seat-position (the-as vehicle s5-1) (-> gp-0 trans) (-> self vehicle-seat-index))
(vector-! (-> gp-0 trans) (-> gp-0 trans) (-> self root trans))
(quaternion<-rotate-y-vector (the-as quaternion (-> gp-0 vector 1)) (-> gp-0 trans))
(quaternion-slerp!
(-> self root quat)
(the-as quaternion (-> gp-0 vector))
(the-as quaternion (-> gp-0 vector 1))
f30-0
)
)
(suspend)
(ja :num! (seek! (ja-aframe 1.0 0) 0.25))
)
(let ((s5-3 (new 'stack-no-clear 'vector)))
(set! (-> s5-3 quad) (-> self root trans quad))
(quaternion-copy! (the-as quaternion (-> gp-0 vector)) (-> self root quat))
(ja-no-eval :group! kid-escort-jump-in-vehicle-ja
:num! (seek! (ja-aframe 8.0 0))
:frame-num (ja-aframe 1.0 0)
)
(until (ja-done? 0)
(let ((s4-2 (handle->process (-> self vehicle-handle))))
(compute-seat-position (the-as vehicle s4-2) (-> gp-0 vector 2) (-> self vehicle-seat-index))
(vector-! (-> gp-0 trans) (-> gp-0 vector 2) s5-3)
(let ((s3-1 lerp-scale)
(s2-1 0.0)
(s1-1 1.0)
(s0-1 (ja-aframe-num 0))
)
(set! sv-112 (ja-aframe 1.0 0))
(let* ((t0-1 (ja-aframe 8.0 0))
(f30-1 (s3-1 s2-1 s1-1 s0-1 sv-112 t0-1))
)
(quaternion-rotate-local-y!
(the-as quaternion (-> gp-0 vector 1))
(-> (the-as vehicle s4-2) root quat)
(* f30-1 (if (zero? (-> self vehicle-seat-index))
-16384.0
16384.0
)
)
)
(quaternion-slerp!
(-> self root quat)
(the-as quaternion (-> gp-0 vector))
(the-as quaternion (-> gp-0 vector 1))
f30-1
)
(vector+float*! (-> self root trans) s5-3 (-> gp-0 trans) f30-1)
)
)
)
(suspend)
(ja :num! (seek! (ja-aframe 8.0 0)))
)
)
(logclear! (-> self root nav-flags) (nav-flags has-root-sphere))
(let ((v1-49 (-> self nav)))
(logclear! (-> v1-49 shape nav-flags) (nav-flags has-extra-sphere))
)
0
(quaternion-copy! (new 'stack-no-clear 'quaternion) (-> self root quat))
(ja-no-eval :group! kid-escort-jump-in-vehicle-ja
:num! (seek! (ja-aframe 12.0 0) 0.25)
:frame-num (ja-aframe 8.0 0)
)
(until (ja-done? 0)
(let ((s5-5 (handle->process (-> self vehicle-handle))))
(quaternion-copy! (the-as quaternion (-> gp-0 vector 1)) (-> (the-as vehicle s5-5) root quat))
(compute-seat-position (the-as vehicle s5-5) (-> self root trans) (-> self vehicle-seat-index))
)
(let ((f0-16 (lerp-scale 0.0 1.0 (ja-aframe-num 0) (ja-aframe 8.0 0) (ja-aframe 11.0 0))))
(quaternion-rotate-local-y!
(-> self root quat)
(the-as quaternion (-> gp-0 vector 1))
(* (- 1.0 f0-16) (if (zero? (-> self vehicle-seat-index))
-16384.0
16384.0
)
)
)
)
(suspend)
(ja :num! (seek! (ja-aframe 12.0 0) 0.25))
)
)
(logior! (-> self focus-status) (focus-status pilot-riding pilot))
(go-virtual ride-vehicle)
)
:post nav-enemy-simple-post
)
;; failed to figure out what this is:
(defstate ride-vehicle (kid-escort)
:virtual #t
:event enemy-event-handler
:enter (behavior ()
(set-time! (-> self state-time))
(let ((v1-2 self))
(set! (-> v1-2 enemy-flags) (the-as enemy-flag (logclear (-> v1-2 enemy-flags) (enemy-flag enemy-flag36))))
(set! (-> v1-2 nav callback-info) *nav-enemy-null-callback-info*)
)
0
(let ((v1-5 self))
(set! (-> v1-5 enemy-flags) (the-as enemy-flag (logclear (-> v1-5 enemy-flags) (enemy-flag enemy-flag37))))
)
0
(logclear! (-> self enemy-flags) (enemy-flag vulnerable))
(logclear! (-> self root nav-flags) (nav-flags has-root-sphere))
(let ((v1-11 (-> self nav)))
(logclear! (-> v1-11 shape nav-flags) (nav-flags has-extra-sphere))
)
0
(logior! (-> self focus-status) (focus-status disable pilot-riding pilot))
(logclear! (-> self focus-status) (focus-status arrestable))
)
:exit (behavior ()
(local-vars (v1-4 enemy-flag))
(logior! (-> self root nav-flags) (nav-flags has-root-sphere))
(let ((v1-3 (-> self enemy-flags)))
(if (logtest? v1-3 (enemy-flag vulnerable-backup))
(set! v1-4 (logior v1-3 (enemy-flag vulnerable)))
(set! v1-4 (logclear v1-3 (enemy-flag vulnerable)))
)
)
(set! (-> self enemy-flags) v1-4)
(logclear! (-> self bot-flags) (bot-flags bf15))
)
:trans (behavior ()
(check-vehicle-exit self)
(if (and (logtest? (bot-flags bf16) (-> self bot-flags)) (want-exit-vehicle? self (-> self exit-vehicle-dest)))
(go-virtual exit-vehicle)
)
0
)
:code (behavior ()
(ja-channel-push! 2 (seconds 0.2))
(ja :group! kid-escort-vehicle-lean-x-ja)
(ja :chan 1 :group! kid-escort-vehicle-lean-z-ja)
(let ((f30-0 0.5)
(f28-0 0.5)
(f26-0 0.5)
)
(until #f
(let ((gp-0 (-> *target* pilot)))
(when (and (nonzero? gp-0) gp-0)
(let ((f20-0 (lerp-scale 0.0 1.0 (-> gp-0 left-right-interp) 1.0 -1.0))
(f24-0 (lerp-scale 0.0 1.0 (-> gp-0 front-back-interp) -1.0 1.0))
(f0-4 (+ (fabs (-> gp-0 left-right-interp)) (fabs (-> gp-0 front-back-interp))))
(f22-0 0.5)
)
(if (< 0.0 f0-4)
(set! f22-0 (/ (fabs (-> gp-0 front-back-interp)) f0-4))
)
(set! f30-0 (seek f30-0 f20-0 (* 4.0 (seconds-per-frame))))
(set! f28-0 (seek f28-0 f24-0 (* 4.0 (seconds-per-frame))))
(set! f26-0 (seek f26-0 f22-0 (* 4.0 (seconds-per-frame))))
)
)
)
(ja :num-func num-func-identity :frame-num (ja-aframe f30-0 0))
(ja :chan 1
:frame-interp0 f26-0
:frame-interp1 f26-0
:num-func num-func-identity
:frame-num (ja-aframe f28-0 0)
)
(suspend)
)
)
#f
)
:post nav-enemy-simple-post
)
;; failed to figure out what this is:
(defstate exit-vehicle (kid-escort)
:virtual #t
:event enemy-event-handler
:enter (behavior ()
(set-time! (-> self state-time))
(let ((v1-2 self))
(set! (-> v1-2 enemy-flags) (the-as enemy-flag (logclear (-> v1-2 enemy-flags) (enemy-flag enemy-flag36))))
(set! (-> v1-2 nav callback-info) *nav-enemy-null-callback-info*)
)
0
(let ((v1-5 self))
(set! (-> v1-5 enemy-flags) (the-as enemy-flag (logclear (-> v1-5 enemy-flags) (enemy-flag enemy-flag37))))
)
0
(logclear! (-> self enemy-flags) (enemy-flag vulnerable))
(logior! (-> self root nav-flags) (nav-flags has-root-sphere))
(logior! (-> self focus-status) (focus-status disable))
(logclear! (-> self focus-status) (focus-status arrestable))
)
:exit (behavior ()
(local-vars (v1-17 enemy-flag))
(let ((a0-1 (handle->process (-> self vehicle-handle))))
(if a0-1
(remove-rider (the-as vehicle a0-1) self)
)
)
(set! (-> self vehicle-seat-index) -1)
(set! (-> self vehicle-handle) (the-as handle #f))
(logclear! (-> self bot-flags) (bot-flags bf16))
(logclear! (-> self focus-status) (focus-status pilot-riding pilot))
(let ((v1-11 (-> self nav)))
(logclear! (-> v1-11 shape nav-flags) (nav-flags has-extra-sphere))
)
0
(logclear! (-> self focus-status) (focus-status disable))
(let ((v1-16 (-> self enemy-flags)))
(if (logtest? v1-16 (enemy-flag vulnerable-backup))
(set! v1-17 (logior v1-16 (enemy-flag vulnerable)))
(set! v1-17 (logclear v1-16 (enemy-flag vulnerable)))
)
)
(set! (-> self enemy-flags) v1-17)
(logclear! (-> self bot-flags) (bot-flags bf15))
)
:trans (behavior ()
(check-vehicle-exit self)
)
:code (behavior ()
(local-vars (sv-80 float) (sv-96 float))
(ja-channel-push! 1 (seconds 0.1))
(ja-no-eval :group! kid-escort-jump-in-vehicle-ja
:num! (seek! (ja-aframe 8.0 0) 0.25)
:frame-num (ja-aframe 12.0 0)
)
(until (ja-done? 0)
(let ((gp-1 (handle->process (-> self vehicle-handle))))
(quaternion-copy! (-> self root quat) (-> (the-as vehicle gp-1) root quat))
(compute-seat-position (the-as vehicle gp-1) (-> self root trans) (-> self vehicle-seat-index))
)
(let ((f0-3 (lerp-scale 0.0 1.0 (ja-aframe-num 0) (ja-aframe 11.0 0) (ja-aframe 8.0 0))))
(quaternion-rotate-local-y!
(-> self root quat)
(-> self root quat)
(* f0-3 (if (zero? (-> self vehicle-seat-index))
-16384.0
16384.0
)
)
)
)
(suspend)
(ja :num! (seek! (ja-aframe 8.0 0) 0.25))
)
(logclear! (-> self focus-status) (focus-status pilot-riding))
(let ((gp-4 (new 'stack-no-clear 'vector))
(s5-1 (new 'stack-no-clear 'quaternion))
)
(set! (-> gp-4 quad) (-> self root trans quad))
(ja-no-eval :group! kid-escort-jump-in-vehicle-ja
:num! (seek! (ja-aframe 0.0 0))
:frame-num (ja-aframe 8.0 0)
)
(until (ja-done? 0)
(let ((s4-2 (handle->process (-> self vehicle-handle))))
(compute-seat-position (the-as vehicle s4-2) gp-4 (-> self vehicle-seat-index))
(quaternion-rotate-local-y!
s5-1
(-> (the-as vehicle s4-2) root quat)
(if (zero? (-> self vehicle-seat-index))
-16384.0
16384.0
)
)
)
(let ((s4-3 (-> self root quat)))
(let ((f30-0 (quaternion-y-angle s5-1)))
(quaternion-identity! s4-3)
(quaternion-rotate-y! s4-3 s4-3 f30-0)
)
(let ((s3-1 lerp-scale)
(s2-1 0.0)
(s1-0 1.0)
(s0-0 (ja-aframe-num 0))
)
(set! sv-80 (ja-aframe 8.0 0))
(let* ((t0-1 (ja-aframe 1.0 0))
(f0-11 (s3-1 s2-1 s1-0 s0-0 sv-80 t0-1))
)
(quaternion-slerp! s4-3 s5-1 s4-3 f0-11)
)
)
)
(want-exit-vehicle? self (-> self exit-vehicle-dest))
(let* ((v1-44 (-> self nav))
(a1-25 (-> self exit-vehicle-dest))
(f0-12 (-> v1-44 extra-nav-sphere w))
)
(set! (-> v1-44 extra-nav-sphere quad) (-> a1-25 quad))
(set! (-> v1-44 extra-nav-sphere w) f0-12)
)
0
(let ((v1-47 (-> self nav)))
(set! (-> v1-47 extra-nav-sphere w) (-> self nav-radius-backup))
)
0
(let ((v1-49 (-> self nav)))
(logior! (-> v1-49 shape nav-flags) (nav-flags has-extra-sphere))
)
0
(new 'stack-no-clear 'vector)
(let ((s4-4 (new 'stack-no-clear 'vector)))
(vector-! s4-4 gp-4 (-> self exit-vehicle-dest))
(let ((s3-2 lerp-scale)
(s2-2 0.0)
(s1-1 1.0)
(s0-1 (ja-aframe-num 0))
)
(set! sv-96 (ja-aframe 1.0 0))
(let* ((t0-2 (ja-aframe 8.0 0))
(f0-15 (s3-2 s2-2 s1-1 s0-1 sv-96 t0-2))
)
(vector+float*! (-> self root trans) (-> self exit-vehicle-dest) s4-4 f0-15)
)
)
)
(suspend)
(ja :num! (seek! (ja-aframe 0.0 0)))
)
)
(react-to-focus self)
)
:post nav-enemy-simple-post
)
;; failed to figure out what this is:
(defstate traveling-blocked (kid-escort)
:virtual #t
:event enemy-event-handler
:enter (behavior ()
(set-time! (-> self state-time))
(let ((v1-2 self))
(set! (-> v1-2 enemy-flags) (the-as enemy-flag (logclear (-> v1-2 enemy-flags) (enemy-flag enemy-flag36))))
(set! (-> v1-2 nav callback-info) *nav-enemy-null-callback-info*)
)
0
(nav-enemy-method-167 self)
(let ((v1-7 self))
(set! (-> v1-7 enemy-flags) (the-as enemy-flag (logclear (-> v1-7 enemy-flags) (enemy-flag enemy-flag37))))
)
0
(vector-reset! (-> self root transv))
(look-at-target! self (enemy-flag look-at-focus))
(set! (-> self travel-anim-interp) 0.0)
)
:trans (behavior ()
(bot-method-223 self #f)
(cond
((the-as process (as-type (handle->process (-> self arrestor-handle)) process-focusable))
(go-virtual arrested)
)
((and (time-elapsed? (-> self state-time) (seconds 1)) (not (bot-method-208 self)))
(if (logtest? (-> self bot-flags) (bot-flags bf15))
(go-virtual move-to-vehicle)
(go-virtual traveling)
)
)
)
)
:code (-> (method-of-type kid-escort waiting-idle) code)
:post nav-enemy-simple-post
)
;; failed to figure out what this is:
(defstate stare (kid-escort)
:virtual #t
:enter (behavior ()
(let ((t9-0 (-> (method-of-type bot stare) enter)))
(if t9-0
(t9-0)
)
)
(let ((v1-4 self))
(set! (-> v1-4 enemy-flags) (the-as enemy-flag (logclear (-> v1-4 enemy-flags) (enemy-flag enemy-flag37))))
)
0
(set! (-> self travel-anim-interp) 0.0)
)
:trans (behavior ()
(bot-method-223 self #f)
(if (the-as process (as-type (handle->process (-> self arrestor-handle)) process-focusable))
(go-virtual arrested)
)
(when (time-elapsed? (-> self state-time) (seconds 0.1))
(when (not (nav-enemy-method-163 self))
(if (logtest? (-> self bot-flags) (bot-flags bf15))
(go-virtual move-to-vehicle)
(go-virtual traveling)
)
)
)
)
:code (-> (method-of-type kid-escort waiting-idle) code)
)
;; failed to figure out what this is:
(defstate hit (kid-escort)
:virtual #t
:enter (behavior ()
(let ((t9-0 (-> (method-of-type bot hit) enter)))
(if t9-0
(t9-0)
)
)
(set! (-> self travel-anim-interp) 0.0)
)
:code (behavior ()
(local-vars (v1-7 enemy-flag) (v1-15 enemy-flag))
(if (logtest? (-> self enemy-flags) (enemy-flag dangerous-backup))
(logior! (-> self focus-status) (focus-status dangerous))
(logclear! (-> self focus-status) (focus-status dangerous))
)
(let ((v1-6 (-> self enemy-flags)))
(if (logtest? v1-6 (enemy-flag vulnerable-backup))
(set! v1-7 (logior v1-6 (enemy-flag vulnerable)))
(set! v1-7 (logclear v1-6 (enemy-flag vulnerable)))
)
)
(set! (-> self enemy-flags) v1-7)
(if (logtest? (-> self enemy-flags) (enemy-flag attackable-backup))
(logior! (-> self mask) (process-mask collectable))
(logclear! (-> self mask) (process-mask collectable))
)
(let ((v1-14 (-> self enemy-flags)))
(if (logtest? (enemy-flag trackable-backup) v1-14)
(set! v1-15 (logior (enemy-flag trackable) v1-14))
(set! v1-15 (logclear v1-14 (enemy-flag trackable)))
)
)
(set! (-> self enemy-flags) v1-15)
(logclear! (-> self enemy-flags) (enemy-flag lock-focus))
(logclear! (-> self focus-status) (focus-status hit))
(react-to-focus self)
)
)
;; failed to figure out what this is:
(defstate knocked (kid-escort)
:virtual #t
:enter (behavior ()
(let ((t9-0 (-> (method-of-type bot knocked) enter)))
(if t9-0
(t9-0)
)
)
(set! (-> self travel-anim-interp) 0.0)
)
)
;; failed to figure out what this is:
(defstate arrested (kid-escort)
:virtual #t
:event enemy-event-handler
:enter (behavior ()
(set-time! (-> self state-time))
(let ((v1-2 self))
(set! (-> v1-2 enemy-flags) (the-as enemy-flag (logclear (-> v1-2 enemy-flags) (enemy-flag enemy-flag36))))
(set! (-> v1-2 nav callback-info) *nav-enemy-null-callback-info*)
)
0
(nav-enemy-method-167 self)
(let ((v1-7 self))
(set! (-> v1-7 enemy-flags) (the-as enemy-flag (logclear (-> v1-7 enemy-flags) (enemy-flag enemy-flag37))))
)
0
(vector-reset! (-> self root transv))
(stop-looking-at-target! self)
(set! (-> self travel-anim-interp) 0.0)
(logior! (-> self focus-status) (focus-status arrestable))
(logclear! (-> self focus-status) (focus-status disable))
(if (logtest? (bot-flags bf19) (-> self bot-flags))
(logclear! (-> self enemy-flags) (enemy-flag vulnerable vulnerable-backup))
)
)
:trans (behavior ()
(cond
((logtest? (-> self bot-flags) (bot-flags bf09))
(fail-falling self)
)
(else
(bot-method-223 self #f)
(when (not (logtest? (bot-flags bf19) (-> self bot-flags)))
(if (and (-> self focus-info fproc) (>= (fabs (-> self focus-info ry-diff)) 9102.223))
(go-waiting-turn self)
)
(when (not (focus-test? self grabbed))
(if (not (the-as process (as-type (handle->process (-> self arrestor-handle)) process-focusable)))
(react-to-focus self)
)
)
)
)
)
)
:code (behavior ()
(cond
((logtest? (bot-flags bf19) (-> self bot-flags))
(fail-mission! self)
(let ((v1-7 (the-as process (as-type (handle->process (-> self arrestor-handle)) process-focusable))))
(if v1-7
(logclear! (-> (the-as crimson-guard v1-7) enemy-flags) (enemy-flag vulnerable vulnerable-backup))
)
)
)
(else
(ja-channel-push! 1 (seconds 0.1))
(ja-no-eval :group! kid-escort-arrest-start-ja :num! (seek! max 0.143) :frame-num 0.0)
(until (ja-done? 0)
(suspend)
(ja :num! (seek! max 0.143))
)
)
)
(let ((v1-34 (ja-group)))
(if (not (and v1-34 (= v1-34 kid-escort-arrest-start-ja)))
(ja-channel-push! 1 (seconds 0.1))
)
)
(ja-no-eval :group! kid-escort-arrest-idle0-ja :num! (seek! max 0.1) :frame-num 0.0)
(when (not (logtest? (bot-flags bf19) (-> self bot-flags)))
(until #f
(until (ja-done? 0)
(if (time-elapsed? (-> self state-time) (seconds 2.5))
(goto cfg-27)
)
(suspend)
(ja :num! (seek! max 0.1))
)
(ja-no-eval :group! kid-escort-arrest-idle0-ja :num! (seek! max 0.1) :frame-num 0.0)
)
#f
(label cfg-27)
(fail-mission! self)
(let ((v1-93 (the-as process (as-type (handle->process (-> self arrestor-handle)) process-focusable))))
(if v1-93
(logclear! (-> (the-as crimson-guard v1-93) enemy-flags) (enemy-flag vulnerable vulnerable-backup))
)
)
)
(set-time! (-> self state-time))
(until #f
(until (ja-done? 0)
(if (and (logtest? (-> self bot-flags) (bot-flags failed))
(time-elapsed? (-> self state-time) (seconds 3))
(reset? *fail-mission-control*)
)
(reset! *fail-mission-control*)
)
(suspend)
(ja :num! (seek! max 0.1))
)
(ja-no-eval :group! kid-escort-arrest-idle0-ja :num! (seek! max 0.1) :frame-num 0.0)
)
#f
)
:post nav-enemy-simple-post
)
;; failed to figure out what this is:
(defstate die-falling (kid-escort)
:virtual #t
:enter (behavior ()
(let ((t9-0 (-> (method-of-type bot die-falling) enter)))
(if t9-0
(t9-0)
)
)
(set! (-> self travel-anim-interp) 0.0)
(logior! (-> self focus-status) (focus-status arrestable))
(logclear! (-> self focus-status) (focus-status disable))
)
:code (behavior ()
(ja-channel-push! 1 (seconds 0.1))
(ja-no-eval :group! kid-escort-arrest-start-ja :num! (seek! max 0.143) :frame-num 0.0)
(until (ja-done? 0)
(suspend)
(ja :num! (seek! max 0.143))
)
(ja-no-eval :group! kid-escort-arrest-idle0-ja :num! (seek! max 0.1) :frame-num 0.0)
(until #f
(until (ja-done? 0)
(if (and (logtest? (-> self bot-flags) (bot-flags failed))
(time-elapsed? (-> self state-time) (seconds 3))
(reset? *fail-mission-control*)
)
(reset! *fail-mission-control*)
)
(suspend)
(ja :num! (seek! max 0.1))
)
(ja-no-eval :group! kid-escort-arrest-idle0-ja :num! (seek! max 0.1) :frame-num 0.0)
)
#f
)
)
;; failed to figure out what this is:
(defstate failed (kid-escort)
:virtual #t
:enter (behavior ()
(let ((t9-0 (-> (method-of-type bot failed) enter)))
(if t9-0
(t9-0)
)
)
(set! (-> self travel-anim-interp) 0.0)
(logior! (-> self focus-status) (focus-status arrestable))
(logclear! (-> self focus-status) (focus-status disable))
)
:code (-> (method-of-type kid-escort die-falling) code)
)
;; failed to figure out what this is:
(defstate knocked-off-vehicle (kid-escort)
:virtual #t
:event enemy-event-handler
:enter (behavior ()
(set-time! (-> self state-time))
(let ((v1-2 self))
(set! (-> v1-2 enemy-flags) (the-as enemy-flag (logclear (-> v1-2 enemy-flags) (enemy-flag enemy-flag36))))
(set! (-> v1-2 nav callback-info) *nav-enemy-null-callback-info*)
)
0
(nav-enemy-method-167 self)
(let ((v1-7 self))
(set! (-> v1-7 enemy-flags) (the-as enemy-flag (logclear (-> v1-7 enemy-flags) (enemy-flag enemy-flag37))))
)
0
(vector-reset! (-> self root transv))
(stop-looking-at-target! self)
(logior! (-> self bot-flags) (bot-flags bf09))
(logclear! (-> self enemy-flags) (enemy-flag vulnerable vulnerable-backup))
(logclear! (-> self focus-status) (focus-status dangerous))
(logclear! (-> self enemy-flags) (enemy-flag dangerous-backup))
(logclear! (-> self mask) (process-mask collectable))
(logclear! (-> self enemy-flags) (enemy-flag attackable-backup))
(logclear! (-> self mask) (process-mask actor-pause))
(logclear! (-> self enemy-flags) (enemy-flag actor-pause-backup))
(logior! (-> self focus-status) (focus-status arrestable))
(logior! (-> self focus-status) (focus-status disable))
(set! (-> self travel-anim-interp) 0.0)
)
:code (behavior ()
(ja-channel-push! 1 (seconds 0.2))
(dotimes (gp-0 3)
(ja-no-eval :group! kid-escort-idle0-ja :num! (seek! max 0.1) :frame-num 0.0)
(until (ja-done? 0)
(suspend)
(ja :num! (seek! max 0.1))
)
)
(ja-channel-push! 1 (seconds 0.1))
(ja-no-eval :group! kid-escort-arrest-start-ja :num! (seek! max 0.143) :frame-num 0.0)
(until (ja-done? 0)
(suspend)
(ja :num! (seek! max 0.143))
)
(until #f
(ja-no-eval :group! kid-escort-arrest-idle0-ja :num! (seek! max 0.1) :frame-num 0.0)
(until (ja-done? 0)
(suspend)
(ja :num! (seek! max 0.1))
)
)
#f
)
:post nav-enemy-simple-post
)
| 412 | 0.737543 | 1 | 0.737543 | game-dev | MEDIA | 0.922281 | game-dev | 0.829636 | 1 | 0.829636 |
aipack-ai/aipack | 1,305 | src/types/md_block.rs | use mlua::IntoLua;
use serde::Serialize;
/// Represents a Markdown block with optional language and content.
#[derive(Debug)]
pub struct MdBlock {
pub lang: Option<String>,
pub content: String,
}
impl MdBlock {
/// Creates a new `MdBlock` with the specified language and content.
#[allow(unused)]
pub fn new(lang: Option<String>, content: impl Into<String>) -> Self {
MdBlock {
lang,
content: content.into(),
}
}
}
// region: --- Serde Serializer
impl Serialize for MdBlock {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeStruct;
let mut state = serializer.serialize_struct("MdBlock", 3)?;
state.serialize_field("_type", "MdBlock")?;
if let Some(lang) = &self.lang {
state.serialize_field("lang", lang)?;
}
state.serialize_field("content", &self.content)?;
state.end()
}
}
// endregion: --- Serde Serializer
// region: --- Lua
impl IntoLua for MdBlock {
/// Converts the `MdBlock` instance into a Lua Value
fn into_lua(self, lua: &mlua::Lua) -> mlua::Result<mlua::Value> {
let table = lua.create_table()?;
table.set("_type", "MdBlock")?;
table.set("lang", self.lang)?;
table.set("content", self.content)?;
Ok(mlua::Value::Table(table))
}
}
// endregion: --- Lua
| 412 | 0.693676 | 1 | 0.693676 | game-dev | MEDIA | 0.192612 | game-dev | 0.665058 | 1 | 0.665058 |
JGameEngine/JGameEngineServer | 12,372 | game-server-rpg/src/main/java/info/xiaomo/server/rpg/system/move/MoveManager.java | package info.xiaomo.server.rpg.system.move;
import info.xiaomo.gengine.map.AbstractGameMap;
import info.xiaomo.gengine.map.IMove;
import info.xiaomo.gengine.map.MapPoint;
import info.xiaomo.gengine.map.constant.MapConst.Dir;
import info.xiaomo.gengine.map.constant.MapConst.Speed;
import info.xiaomo.gengine.map.obj.Performer;
import info.xiaomo.gengine.map.util.GeomUtil;
import info.xiaomo.server.rpg.map.GameMap;
import info.xiaomo.server.rpg.map.MapManager;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class MoveManager implements IMove {
private static final MoveManager INSTANCE = new MoveManager();
public static MoveManager getInstance() {
return INSTANCE;
}
public void playerWalk(Performer player, int x, int y) {
// 检查一些buff不能移动的情况
GameMap map = MapManager.getInstance().getMap(player.getMapId(), player.getLine());
if (map == null) {
return;
}
MapPoint point = player.getPoint();
MapPoint targetPoint = map.getPoint(x, y);
if (targetPoint == null) {
log.info("{}|{}步行目标点为空[{},{}]", player.getId(), player.getName(), x, y);
return;
}
if (player.getMovingPoint() != point) {
// 移动失败,通知客户端拉回玩家
// ResChangePosMessage res = new ResChangePosMessage();
// res.setX(point.x);
// res.setY(point.y);
// res.setLid(player.getId());
// MessageUtil.sendMsg(res, player.getId());
log.info("{}|{}步行速度过快", player.getId(), player.getName());
return; // 步子太大
}
Dir dir = GeomUtil.getDir(point, targetPoint);
if (GeomUtil.distance(point, targetPoint) > 1) {
// 移动失败,通知客户端拉回玩家
// ResChangePosMessage res = new ResChangePosMessage();
// res.setX(point.x);
// res.setY(point.y);
// res.setLid(player.getId());
// MessageUtil.sendMsg(res, player.getId());
log.info("{}|{}步行步子太大", player.getId(), player.getName());
return;
}
MapPoint next = GeomUtil.nextDirPoint(point, dir);
if (next == null) {
// 移动失败,通知客户端拉回玩家
// ResChangePosMessage res = new ResChangePosMessage();
// res.setX(point.x);
// res.setY(point.y);
// res.setLid(player.getId());
// MessageUtil.sendMsg(res, player.getId());
log.info("{}|{}步行路径中格子为空", player.getId(), player.getName());
return;
}
if (moveToPoint(map, player, next)) {
player.setLastPoint(point);
player.setLastMoveSpeed(Speed.WALK);
player.setLastMoveTime(System.currentTimeMillis());
// ResWalkMessage res = new ResWalkMessage();
// res.setX(next.x);
// res.setY(next.y);
// res.setLid(player.getId());
// MessageUtil.sendRoundMessage(res, player);
map.getAoi().updateObject(player, point, next);
map.getAoi().updateWatcher(player, point, next);
} else {
// 移动失败,通知客户端拉回玩家
// ResChangePosMessage res = new ResChangePosMessage();
// res.setX(point.x);
// res.setY(point.y);
// res.setLid(player.getId());
// MessageUtil.sendMsg(res, player.getId());
}
}
public void playerRun(Performer player, int x, int y) {
// 检查一些buff不能移动的情况
// LOGGER.info(player.getName() + " 移动:" + x + "," + y);
GameMap map = MapManager.getInstance().getMap(player.getMapId(), player.getLine());
if (map == null) {
return;
}
MapPoint targetPoint = map.getPoint(x, y);
if (targetPoint == null) {
log.info("{}|{}跑步目标点为空[{},{}]", player.getId(), player.getName(), x, y);
return;
}
MapPoint point = player.getPoint();
if (player.getMovingPoint() != point) {
// 移动失败,通知客户端拉回玩家
// ResChangePosMessage res = new ResChangePosMessage();
// res.setX(point.x);
// res.setY(point.y);
// res.setLid(player.getId());
// MessageUtil.sendMsg(res, player.getId());
log.info(
"{}|{}跑步速度过快, time:{}, speed:{}",
player.getId(),
player.getName(),
System.currentTimeMillis() - player.getLastMoveTime(),
player.getLastMoveSpeed());
return; // 步子太大
}
Dir dir = GeomUtil.getDir(point, targetPoint);
if (GeomUtil.distance(point, targetPoint) > 2) {
// ResChangePosMessage res = new ResChangePosMessage();
// res.setX(point.x);
// res.setY(point.y);
// res.setLid(player.getId());
// MessageUtil.sendMsg(res, player.getId());
log.info("{}|{}跑步步子太大", player.getId(), player.getName());
return;
}
MapPoint next = GeomUtil.nextDirPoint(point, dir);
if (moveToPoint(map, player, next)) {
next = GeomUtil.nextDirPoint(next, dir);
if (moveToPoint(map, player, next)) {
player.setLastPoint(point);
player.setLastMoveSpeed(Speed.RUN);
player.setLastMoveTime(System.currentTimeMillis());
// ResRunMessage res = new ResRunMessage();
// res.setX(next.x);
// res.setY(next.y);
// res.setLid(player.getId());
// MessageUtil.sendRoundMessage(res, player);
} else {
player.setLastPoint(point);
player.setLastMoveSpeed(Speed.WALK);
player.setLastMoveTime(System.currentTimeMillis());
// ResWalkMessage res = new ResWalkMessage();
// res.setX(next.x);
// res.setY(next.y);
// res.setLid(player.getId());
// MessageUtil.sendRoundMessage(res, player);
}
map.getAoi().updateObject(player, point, next);
map.getAoi().updateWatcher(player, point, next);
} else {
// 移动失败,通知客户端拉回玩家
// ResChangePosMessage res = new ResChangePosMessage();
// res.setX(point.x);
// res.setY(point.y);
// res.setLid(player.getId());
// MessageUtil.sendMsg(res, player.getId());
}
}
public void playerHorse(Performer player, int x, int y) {
// 检查一些buff不能移动的情况
GameMap map = MapManager.getInstance().getMap(player.getMapId(), player.getLine());
if (map == null) {
return;
}
MapPoint targetPoint = map.getPoint(x, y);
if (targetPoint == null) {
log.info("{}|{}骑马目标点为空[{},{}]", player.getId(), player.getName(), x, y);
return;
}
MapPoint point = player.getPoint();
if (player.getMovingPoint() != point) {
// 移动失败,通知客户端拉回玩家
// ResChangePosMessage res = new ResChangePosMessage();
// res.setX(point.x);
// res.setY(point.y);
// res.setLid(player.getId());
// MessageUtil.sendMsg(res, player.getId());
log.info(
"{}|{}骑马速度过快, time:{}, speed:{}",
player.getId(),
player.getName(),
System.currentTimeMillis() - player.getLastMoveTime(),
player.getLastMoveSpeed());
return; // 步子太大
}
Dir dir = GeomUtil.getDir(point, targetPoint);
if (GeomUtil.distance(point, targetPoint) > 3) {
// ResChangePosMessage res = new ResChangePosMessage();
// res.setX(point.x);
// res.setY(point.y);
// res.setLid(player.getId());
// MessageUtil.sendMsg(res, player.getId());
log.info("{}|{}骑马步子太大", player.getId(), player.getName());
return;
}
MapPoint next = GeomUtil.nextDirPoint(point, dir);
if (moveToPoint(map, player, next)) { // 1步
next = GeomUtil.nextDirPoint(next, dir);
if (moveToPoint(map, player, next)) { // 2步
next = GeomUtil.nextDirPoint(next, dir);
if (moveToPoint(map, player, next)) { // 3步
player.setLastPoint(point);
player.setLastMoveSpeed(Speed.HORSE);
player.setLastMoveTime(System.currentTimeMillis());
// ResHorseMessage res = new ResHorseMessage();
// res.setX(next.x);
// res.setY(next.y);
// res.setLid(player.getId());
// MessageUtil.sendRoundMessage(res, player);
} else {
player.setLastPoint(point);
player.setLastMoveSpeed(Speed.RUN);
player.setLastMoveTime(System.currentTimeMillis());
// ResRunMessage res = new ResRunMessage();
// res.setX(next.x);
// res.setY(next.y);
// res.setLid(player.getId());
// MessageUtil.sendRoundMessage(res, player);
}
} else {
player.setLastPoint(point);
player.setLastMoveSpeed(Speed.WALK);
player.setLastMoveTime(System.currentTimeMillis());
// ResWalkMessage res = new ResWalkMessage();
// res.setX(next.x);
// res.setY(next.y);
// res.setLid(player.getId());
// MessageUtil.sendRoundMessage(res, player);
}
map.getAoi().updateObject(player, point, next);
map.getAoi().updateWatcher(player, point, next);
} else {
// 移动失败,通知客户端拉回玩家
// ResChangePosMessage res = new ResChangePosMessage();
// res.setX(point.x);
// res.setY(point.y);
// MessageUtil.sendMsg(res, player.getId());
}
}
/**
* 这个主要用来给AI用的移动,玩家不允许调用该方法
*
* @param map
* @param performer
* @param point
*/
public void performerMove(AbstractGameMap map, Performer performer, MapPoint point) {
MapPoint oldPoint = performer.getPoint();
map.stand(performer, point);
map.getAoi().updateObject(performer, oldPoint, point);
// Message msg = buildMoveMsg(performer, oldPoint, point);
// MessageUtil.sendRoundMessage(msg, performer);
}
public void changeDir(Performer player, byte dir) {
Dir enumDir = Dir.getByIndex(dir);
if (enumDir != null && enumDir != Dir.NONE) {
player.setDir(dir);
// ResChangeDirMessage res = new ResChangeDirMessage();
// res.setDir(dir);
// res.setLid(player.getId());
// MessageUtil.sendMsg(res, player.getId());
}
}
private boolean moveToPoint(GameMap map, Performer player, MapPoint point) {
if (point == null) {
log.info("{}|{}移动中路径中格子为空", player.getId(), player.getName());
return false;
}
if (point.canWalk(player, false)) {
map.stand(player, point);
if (point.isHasEvent()) {
player.setMoved(true);
}
return true;
} else {
log.info("{}|{}移动中路径中格子不能站立->{}", player.getId(), player.getName(), point);
}
return false;
}
}
| 412 | 0.683397 | 1 | 0.683397 | game-dev | MEDIA | 0.842883 | game-dev | 0.832127 | 1 | 0.832127 |
cally72jhb/vector-addon | 3,292 | src/main/java/cally72jhb/addon/modules/movement/TickShift.java | package cally72jhb.addon.modules.movement;
import meteordevelopment.meteorclient.events.entity.player.PlayerMoveEvent;
import meteordevelopment.meteorclient.events.world.TickEvent;
import meteordevelopment.meteorclient.settings.*;
import meteordevelopment.meteorclient.systems.modules.Categories;
import meteordevelopment.meteorclient.systems.modules.Module;
import meteordevelopment.meteorclient.systems.modules.Modules;
import meteordevelopment.meteorclient.systems.modules.world.Timer;
import meteordevelopment.orbit.EventHandler;
public class TickShift extends Module {
private final SettingGroup sgGeneral = settings.getDefaultGroup();
public final Setting<SmoothMode> smooth = sgGeneral.add(new EnumSetting.Builder<SmoothMode>()
.name("Smoothness")
.description(".")
.defaultValue(SmoothMode.Exponent)
.build()
);
public final Setting<Integer> packets = sgGeneral.add(new IntSetting.Builder()
.name("Packets")
.description("How many packets to store for later use.")
.defaultValue(50)
.min(0)
.sliderRange(0, 100)
.build()
);
private final Setting<Double> timer = sgGeneral.add(new DoubleSetting.Builder()
.name("Timer")
.description("How many packets to send every movement tick.")
.defaultValue(2)
.min(1)
.sliderRange(0, 10)
.build()
);
public TickShift() {
super(Categories.Movement, "tick-shift", "Stores packets when standing still and uses them when you start moving.");
}
public int unSent = 0;
private boolean lastTimer = false;
private boolean lastMoving = false;
private final Timer timerModule = Modules.get().get(Timer.class);
@Override
public void onActivate() {
super.onActivate();
unSent = 0;
}
@Override
public void onDeactivate() {
super.onDeactivate();
if (lastTimer) {
lastTimer = false;
timerModule.setOverride(Timer.OFF);
}
}
@Override
public String getInfoString() {
return String.valueOf(unSent);
}
@EventHandler
private void onTick(TickEvent.Pre event) {
if (unSent > 0 && lastMoving) {
lastMoving = false;
lastTimer = true;
timerModule.setOverride(getTimer());
} else if (lastTimer) {
lastTimer = false;
timerModule.setOverride(Timer.OFF);
}
}
@EventHandler
private void onMove(PlayerMoveEvent event) {
if (event.movement.length() > 0 && !(event.movement.length() > 0.0784 && event.movement.length() < 0.0785)) {
unSent = Math.max(0, unSent - 1);
lastMoving = true;
}
}
private double getTimer() {
if (smooth.get() == SmoothMode.Disabled) {
return timer.get();
}
double progress = 1 - (unSent / (float) packets.get());
if (smooth.get() == SmoothMode.Exponent) {
progress *= progress * progress * progress * progress;
}
return 1 + (timer.get() - 1) * (1 - progress);
}
public enum SmoothMode {
Disabled,
Normal,
Exponent
}
}
| 412 | 0.926434 | 1 | 0.926434 | game-dev | MEDIA | 0.620994 | game-dev | 0.981386 | 1 | 0.981386 |
SinlessDevil/VisionFieldMesh | 5,519 | Assets/Plugins/UniTask/Runtime/Linq/Publish.cs | using Cysharp.Threading.Tasks.Internal;
using System;
using System.Threading;
namespace Cysharp.Threading.Tasks.Linq
{
public static partial class UniTaskAsyncEnumerable
{
public static IConnectableUniTaskAsyncEnumerable<TSource> Publish<TSource>(this IUniTaskAsyncEnumerable<TSource> source)
{
Error.ThrowArgumentNullException(source, nameof(source));
return new Publish<TSource>(source);
}
}
internal sealed class Publish<TSource> : IConnectableUniTaskAsyncEnumerable<TSource>
{
readonly IUniTaskAsyncEnumerable<TSource> source;
readonly CancellationTokenSource cancellationTokenSource;
TriggerEvent<TSource> trigger;
IUniTaskAsyncEnumerator<TSource> enumerator;
IDisposable connectedDisposable;
bool isCompleted;
public Publish(IUniTaskAsyncEnumerable<TSource> source)
{
this.source = source;
this.cancellationTokenSource = new CancellationTokenSource();
}
public IDisposable Connect()
{
if (connectedDisposable != null) return connectedDisposable;
if (enumerator == null)
{
enumerator = source.GetAsyncEnumerator(cancellationTokenSource.Token);
}
ConsumeEnumerator().Forget();
connectedDisposable = new ConnectDisposable(cancellationTokenSource);
return connectedDisposable;
}
async UniTaskVoid ConsumeEnumerator()
{
try
{
try
{
while (await enumerator.MoveNextAsync())
{
trigger.SetResult(enumerator.Current);
}
trigger.SetCompleted();
}
catch (Exception ex)
{
trigger.SetError(ex);
}
}
finally
{
isCompleted = true;
await enumerator.DisposeAsync();
}
}
public IUniTaskAsyncEnumerator<TSource> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
return new _Publish(this, cancellationToken);
}
sealed class ConnectDisposable : IDisposable
{
readonly CancellationTokenSource cancellationTokenSource;
public ConnectDisposable(CancellationTokenSource cancellationTokenSource)
{
this.cancellationTokenSource = cancellationTokenSource;
}
public void Dispose()
{
this.cancellationTokenSource.Cancel();
}
}
sealed class _Publish : MoveNextSource, IUniTaskAsyncEnumerator<TSource>, ITriggerHandler<TSource>
{
static readonly Action<object> CancelDelegate = OnCanceled;
readonly Publish<TSource> parent;
CancellationToken cancellationToken;
CancellationTokenRegistration cancellationTokenRegistration;
bool isDisposed;
public _Publish(Publish<TSource> parent, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested) return;
this.parent = parent;
this.cancellationToken = cancellationToken;
if (cancellationToken.CanBeCanceled)
{
this.cancellationTokenRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(CancelDelegate, this);
}
parent.trigger.Add(this);
TaskTracker.TrackActiveTask(this, 3);
}
public TSource Current { get; private set; }
ITriggerHandler<TSource> ITriggerHandler<TSource>.Prev { get; set; }
ITriggerHandler<TSource> ITriggerHandler<TSource>.Next { get; set; }
public UniTask<bool> MoveNextAsync()
{
cancellationToken.ThrowIfCancellationRequested();
if (parent.isCompleted) return CompletedTasks.False;
completionSource.Reset();
return new UniTask<bool>(this, completionSource.Version);
}
static void OnCanceled(object state)
{
var self = (_Publish)state;
self.completionSource.TrySetCanceled(self.cancellationToken);
self.DisposeAsync().Forget();
}
public UniTask DisposeAsync()
{
if (!isDisposed)
{
isDisposed = true;
TaskTracker.RemoveTracking(this);
cancellationTokenRegistration.Dispose();
parent.trigger.Remove(this);
}
return default;
}
public void OnNext(TSource value)
{
Current = value;
completionSource.TrySetResult(true);
}
public void OnCanceled(CancellationToken cancellationToken)
{
completionSource.TrySetCanceled(cancellationToken);
}
public void OnCompleted()
{
completionSource.TrySetResult(false);
}
public void OnError(Exception ex)
{
completionSource.TrySetException(ex);
}
}
}
} | 412 | 0.878433 | 1 | 0.878433 | game-dev | MEDIA | 0.38927 | game-dev | 0.834174 | 1 | 0.834174 |
theoo-h/FunkinModchart | 2,700 | modchart/engine/modifiers/Modifier.hx | package modchart.engine.modifiers;
import flixel.FlxG;
import flixel.math.FlxMath;
import modchart.Manager;
import modchart.backend.core.ArrowData;
import modchart.backend.core.ModifierParameters;
import modchart.backend.core.VisualParameters;
import modchart.engine.PlayField;
using StringTools;
#if !openfl_debug
@:fileXml('tags="haxe,release"')
@:noDebug
#end
class Modifier {
private var pf:PlayField;
public function new(pf:PlayField) {
this.pf = pf;
}
public function render(curPos:Vector3, params:ModifierParameters) {
return curPos;
}
public function visuals(data:VisualParameters, params:ModifierParameters):VisualParameters {
return data;
}
public function shouldRun(params:ModifierParameters):Bool
return false;
public inline function findID(name:String):Int {
@:privateAccess return pf.modifiers.percents.__hashKey(name.toLowerCase());
}
public inline function getUnsafe(id:Int, player:Int)
return @:privateAccess pf.modifiers.__getUnsafe(id, player);
public inline function setUnsafe(id:Int, value:Float, player:Int = -1)
return @:privateAccess pf.modifiers.__setUnsafe(id, value, player);
public inline function setPercent(name:String, value:Float, player:Int = -1) {
pf.setPercent(name, value, player);
}
public inline function getPercent(name:String, player:Int):Float {
return pf.getPercent(name, player);
}
private inline function getKeyCount(player:Int = 0):Int {
return Adapter.instance.getKeyCount();
}
private inline function getPlayerCount():Int {
return Adapter.instance.getPlayerCount();
}
// Helpers Functions
private inline function getScrollSpeed():Float
return Adapter.instance.getCurrentScrollSpeed();
public inline function getReceptorY(lane:Int, player:Int)
return Adapter.instance.getDefaultReceptorY(lane, player);
public inline function getReceptorX(lane:Int, player:Int)
return Adapter.instance.getDefaultReceptorX(lane, player);
private var WIDTH:Float = FlxG.width;
private var HEIGHT:Float = FlxG.height;
private var ARROW_SIZE(get, never):Float;
private var ARROW_SIZEDIV2(get, never):Float;
private inline function get_ARROW_SIZE():Float
return Manager.ARROW_SIZE;
private inline function get_ARROW_SIZEDIV2():Float
return Manager.ARROW_SIZEDIV2;
private inline function sin(rad:Float):Float
return ModchartUtil.sin(rad);
private inline function cos(rad:Float):Float
return ModchartUtil.cos(rad);
private inline function tan(rad:Float):Float
return ModchartUtil.tan(rad);
public function toString():String {
var classn:String = Type.getClassName(Type.getClass(this));
classn = classn.substring(classn.lastIndexOf('.') + 1);
return 'Modifier[$classn]';
}
}
| 412 | 0.895246 | 1 | 0.895246 | game-dev | MEDIA | 0.756977 | game-dev | 0.886427 | 1 | 0.886427 |
apoguita/Py4GW | 6,136 | Py4GWCoreLib/Builds/KeiranThackerayEOTN.py |
from Py4GWCoreLib import GLOBAL_CACHE
from Py4GWCoreLib import Routines
from Py4GWCoreLib import BuildMgr
from Py4GWCoreLib import ActionQueueManager
from Py4GWCoreLib import Range
from .AutoCombat import AutoCombat
class KeiranThackerayEOTN(BuildMgr):
def __init__(self):
super().__init__(name="AutoCombat Build") # minimal init
self.auto_combat_handler:BuildMgr = AutoCombat()
self.natures_blessing = GLOBAL_CACHE.Skill.GetID("Natures_Blessing")
self.relentless_assaunlt = GLOBAL_CACHE.Skill.GetID("Relentless_Assault")
self.keiran_sniper_shot = GLOBAL_CACHE.Skill.GetID("Keirans_Sniper_Shot_Hearts_of_the_North") # or 3235
self.terminal_velocity = GLOBAL_CACHE.Skill.GetID("Terminal_Velocity")
self.gravestone_marker = GLOBAL_CACHE.Skill.GetID("Gravestone_Marker")
self.rain_of_arrows = GLOBAL_CACHE.Skill.GetID("Rain_of_Arrows")
self.auto_combat_handler.auto_combat_handler.SetSkillEnabled(1, False)
self.auto_combat_handler.auto_combat_handler.SetSkillEnabled(2, False)
self.auto_combat_handler.auto_combat_handler.SetSkillEnabled(3, False)
self.auto_combat_handler.auto_combat_handler.SetSkillEnabled(4, False)
self.auto_combat_handler.auto_combat_handler.SetSkillEnabled(5, False)
self.auto_combat_handler.auto_combat_handler.SetSkillEnabled(6, False)
def ProcessSkillCasting(self):
def _CastSkill(target, skill_id, aftercast=750):
if Routines.Checks.Map.IsExplorable():
yield from Routines.Yield.Agents.ChangeTarget(target)
if Routines.Checks.Map.IsExplorable():
yield from Routines.Yield.Skills.CastSkillID(skill_id, aftercast_delay=aftercast)
yield
aftercast = 750 # ms
if not (Routines.Checks.Map.IsExplorable() and
Routines.Checks.Player.CanAct() and
Routines.Checks.Map.IsExplorable() and
Routines.Checks.Skills.CanCast()):
ActionQueueManager().ResetAllQueues()
yield from Routines.Yield.wait(1000)
return
life_threshold = 0.70
if (yield from Routines.Yield.Skills.IsSkillIDUsable(self.natures_blessing)):
player_life = GLOBAL_CACHE.Agent.GetHealth(GLOBAL_CACHE.Player.GetAgentID())
low_on_life = player_life < life_threshold
nearest_npc = Routines.Agents.GetNearestNPC(Range.Spirit.value)
npc_low_on_life = False
if nearest_npc != 0:
npc_life = GLOBAL_CACHE.Agent.GetHealth(nearest_npc)
npc_low_on_life = npc_life < life_threshold
if low_on_life or npc_low_on_life:
yield from Routines.Yield.Skills.CastSkillID(self.natures_blessing, aftercast_delay=100)
return
if Routines.Checks.Agents.InDanger():
if (yield from Routines.Yield.Skills.IsSkillIDUsable(self.keiran_sniper_shot)):
hexed_enemy = Routines.Targeting.GetEnemyHexed(Range.Earshot.value)
if hexed_enemy != 0:
yield from _CastSkill(hexed_enemy, self.keiran_sniper_shot, aftercast)
return
if (yield from Routines.Yield.Skills.IsSkillIDUsable(self.relentless_assaunlt)):
if (GLOBAL_CACHE.Agent.IsDegenHexed(GLOBAL_CACHE.Player.GetAgentID()) or
#GLOBAL_CACHE.Agent.IsConditioned(GLOBAL_CACHE.Player.GetAgentID()) or
GLOBAL_CACHE.Agent.IsBleeding(GLOBAL_CACHE.Player.GetAgentID()) or
GLOBAL_CACHE.Agent.IsPoisoned(GLOBAL_CACHE.Player.GetAgentID()) or
Routines.Checks.Agents.HasEffect(GLOBAL_CACHE.Player.GetAgentID(), GLOBAL_CACHE.Skill.GetID("Deep_Wound")) or
Routines.Checks.Agents.HasEffect(GLOBAL_CACHE.Player.GetAgentID(), GLOBAL_CACHE.Skill.GetID("Cracked_Armor")) or
Routines.Checks.Agents.HasEffect(GLOBAL_CACHE.Player.GetAgentID(), GLOBAL_CACHE.Skill.GetID("Burning"))):
enemy = Routines.Targeting.GetEnemyInjured(Range.Earshot.value)
if enemy != 0:
yield from _CastSkill(enemy, self.relentless_assaunlt, aftercast)
return
if (yield from Routines.Yield.Skills.IsSkillIDUsable(self.terminal_velocity)):
casting_enemy = Routines.Targeting.GetEnemyCasting(Range.Earshot.value)
if casting_enemy != 0:
yield from _CastSkill(casting_enemy, self.terminal_velocity, aftercast)
return
bleeding_enemy = Routines.Targeting.GetEnemyBleeding(Range.Earshot.value)
if bleeding_enemy != 0:
yield from _CastSkill(bleeding_enemy, self.terminal_velocity, aftercast)
if (yield from Routines.Yield.Skills.IsSkillIDUsable(self.gravestone_marker)):
spirit_enemy = Routines.Targeting.GetNearestSpirit(Range.Earshot.value)
if spirit_enemy != 0:
yield from _CastSkill(spirit_enemy, self.gravestone_marker, aftercast)
return
gravestone_enemy = Routines.Targeting.GetEnemyHealthy(Range.Earshot.value)
if gravestone_enemy != 0:
yield from _CastSkill(gravestone_enemy, self.gravestone_marker, aftercast)
if (yield from Routines.Yield.Skills.IsSkillIDUsable(self.rain_of_arrows)):
spirit_enemy = Routines.Targeting.GetNearestSpirit(Range.Earshot.value)
if spirit_enemy != 0:
yield from _CastSkill(spirit_enemy, self.rain_of_arrows, aftercast)
return
enemy = Routines.Targeting.TargetClusteredEnemy(Range.Earshot.value)
if enemy != 0:
yield from _CastSkill(enemy, self.rain_of_arrows, aftercast)
return
yield from self.auto_combat_handler.ProcessSkillCasting() | 412 | 0.907053 | 1 | 0.907053 | game-dev | MEDIA | 0.980304 | game-dev | 0.94042 | 1 | 0.94042 |
worldforge/cyphesis | 2,564 | src/rules/ai/MemEntity.cpp | // Cyphesis Online RPG Server and AI Engine
// Copyright (C) 2000,2001 Alistair Riddoch
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include <rules/BBoxProperty.h>
#include <rules/ScaleProperty.h>
#include "MemEntity.h"
#include "rules/SolidProperty.h"
#include "common/TypeNode.h"
#include "common/PropertyManager.h"
static const bool debug_flag = false;
MemEntity::MemEntity(RouterId id) :
LocatedEntity(id),
m_lastSeen(0.),
m_lastUpdated(0)
{
}
std::unique_ptr<PropertyBase> MemEntity::createProperty(const std::string& propertyName) const
{
// if (propertyName == ReadPositionProperty::property_name) {
// return std::make_unique<ReadPositionProperty>(const_cast<WFMath::Point<3>&>(m_transform.pos));
// }
// if (propertyName == ReadBboxProperty::property_name) {
// return std::make_unique<ReadBboxProperty>(const_cast<WFMath::AxisBox<3>&>(m_bbox));
// }
// if (propertyName == ReadOrientationProperty::property_name) {
// return std::make_unique<ReadOrientationProperty>(const_cast<WFMath::Quaternion&>(m_transform.orientation));
// }
// if (propertyName == ReadVelocityProperty::property_name) {
// return std::make_unique<ReadVelocityProperty>(const_cast<MemEntity&>(*this));
// }
// if (propertyName == ReadAngularProperty::property_name) {
// return std::make_unique<ReadAngularProperty>(const_cast<MemEntity&>(*this));
// }
return PropertyManager::instance().addProperty(propertyName);
}
void MemEntity::externalOperation(const Operation& op, Link&)
{
}
void MemEntity::operation(const Operation&, OpVector&)
{
}
void MemEntity::destroy()
{
LocatedEntity::destroy();
if (m_contains) {
auto containsCopy = *m_contains;
for (auto& child_ent : containsCopy) {
child_ent->destroy();
}
}
m_flags.addFlags(entity_destroyed);
}
| 412 | 0.858655 | 1 | 0.858655 | game-dev | MEDIA | 0.767741 | game-dev | 0.796196 | 1 | 0.796196 |
TheWalruzz/godot-questify | 1,792 | addons/questify/scripts/components/variant_input.gd | @tool
class_name VariantInput extends HBoxContainer
signal value_changed(value: Variant)
@export var type_select: OptionButton
@export var inputs_container: Control
func _ready() -> void:
type_select.set_item_icon(0, get_theme_icon("bool", "EditorIcons"))
type_select.set_item_icon(1, get_theme_icon("String", "EditorIcons"))
type_select.set_item_icon(2, get_theme_icon("Object", "EditorIcons"))
type_select.set_item_icon(3, get_theme_icon("Vector2", "EditorIcons"))
type_select.set_item_icon(4, get_theme_icon("Vector3", "EditorIcons"))
type_select.set_item_icon(5, get_theme_icon("int", "EditorIcons"))
type_select.set_item_icon(6, get_theme_icon("float", "EditorIcons"))
func select_type(index: int) -> void:
for child in inputs_container.get_children():
child.visible = false
inputs_container.get_child(index).visible = true
func set_value(value: Variant) -> void:
var index: int
if value is bool:
index = 0
if value is String:
if value.begins_with("res://"):
index = 2
else:
index = 1
if value is Vector2:
index = 3
if value is Vector3:
index = 4
if value is int:
index = 5
if value is float:
index = 6
type_select.select(index)
select_type(index)
var input = inputs_container.get_child(index)
match index:
0: #bool
input.button_pressed = value
1: #String
input.text = value
2: #Resource
input.set_value(value)
3: #Vector2
input.set_value(value)
4: #Vector3
input.set_value(value)
5, 6: #int, float
input.value = value
func _on_type_selected(index: int) -> void:
select_type(index)
func _on_value_changed(value: Variant) -> void:
# special case for int, since SpinBox always handles floats
if type_select.get_selected_id() == 4:
value_changed.emit(int(value))
return
value_changed.emit(value)
| 412 | 0.785526 | 1 | 0.785526 | game-dev | MEDIA | 0.57473 | game-dev | 0.8761 | 1 | 0.8761 |
Patbox/polymer | 1,798 | polymer-core/src/main/java/eu/pb4/polymer/core/impl/client/debug/LookingAtPolymerEntityDebugHudEntry.java | package eu.pb4.polymer.core.impl.client.debug;
import eu.pb4.polymer.core.api.client.ClientPolymerBlock;
import eu.pb4.polymer.core.api.client.PolymerClientUtils;
import eu.pb4.polymer.core.impl.client.InternalClientRegistry;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.hud.debug.DebugHudEntry;
import net.minecraft.client.gui.hud.debug.DebugHudLines;
import net.minecraft.entity.Entity;
import net.minecraft.registry.Registries;
import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.hit.HitResult;
import net.minecraft.world.World;
import net.minecraft.world.chunk.WorldChunk;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class LookingAtPolymerEntityDebugHudEntry implements DebugHudEntry {
private static final Identifier SECTION_ID = Identifier.ofVanilla("looking_at_entity");
@Override
public void render(DebugHudLines lines, @Nullable World world, @Nullable WorldChunk clientChunk, @Nullable WorldChunk chunk) {
if (!InternalClientRegistry.enabled) {
return;
}
MinecraftClient minecraftClient = MinecraftClient.getInstance();
var type = PolymerClientUtils.getEntityType(minecraftClient.targetedEntity);
List<String> list = new ArrayList<>();
if (type != null) {
list.add(Formatting.UNDERLINE + "Targeted Client Entity");
list.add(String.valueOf(type.identifier()));
}
lines.addLinesToSection(SECTION_ID, list);
}
@Override
public boolean canShow(boolean reducedDebugInfo) {
return DebugHudEntry.super.canShow(reducedDebugInfo) && InternalClientRegistry.enabled;
}
}
| 412 | 0.698658 | 1 | 0.698658 | game-dev | MEDIA | 0.950234 | game-dev | 0.601734 | 1 | 0.601734 |
folgerwang/UnrealEngine | 6,936 | Engine/Source/Runtime/IOS/IOSRuntimeSettings/Private/IOSRuntimeSettings.cpp | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#include "IOSRuntimeSettings.h"
#include "HAL/FileManager.h"
#include "Misc/Paths.h"
#include "Misc/EngineBuildSettings.h"
#include "HAL/IConsoleManager.h"
#include "HAL/PlatformApplicationMisc.h"
UIOSRuntimeSettings::UIOSRuntimeSettings(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
bEnableGameCenterSupport = true;
bEnableCloudKitSupport = false;
bSupportsPortraitOrientation = true;
bSupportsITunesFileSharing = false;
BundleDisplayName = TEXT("UE4 Game");
BundleName = TEXT("MyUE4Game");
BundleIdentifier = TEXT("com.YourCompany.GameNameNoSpaces");
VersionInfo = TEXT("1.0.0");
FrameRateLock = EPowerUsageFrameRateLock::PUFRL_30;
bSupportsIPad = true;
bSupportsIPhone = true;
MinimumiOSVersion = EIOSVersion::IOS_10;
EnableRemoteShaderCompile = false;
bGeneratedSYMFile = false;
bGeneratedSYMBundle = false;
bGenerateXCArchive = false;
bDevForArmV7 = false;
bDevForArm64 = true;
bDevForArmV7S = false;
bShipForArmV7 = false;
bShipForArm64 = true;
bShipForArmV7S = false;
bShipForBitcode = true;
bUseRSync = true;
AdditionalPlistData = TEXT("");
AdditionalLinkerFlags = TEXT("");
AdditionalShippingLinkerFlags = TEXT("");
bTreatRemoteAsSeparateController = false;
bAllowRemoteRotation = true;
bUseRemoteAsVirtualJoystick = true;
bUseRemoteAbsoluteDpadValues = false;
bEnableRemoteNotificationsSupport = false;
bEnableBackgroundFetch = false;
bSupportsOpenGLES2 = false;
bSupportsMetal = true;
bSupportsMetalMRT = false;
bDisableHTTPS = false;
}
void UIOSRuntimeSettings::PostReloadConfig(class UProperty* PropertyThatWasLoaded)
{
Super::PostReloadConfig(PropertyThatWasLoaded);
#if PLATFORM_IOS
FPlatformApplicationMisc::SetGamepadsAllowed(bAllowControllers);
#endif //PLATFORM_IOS
}
#if WITH_EDITOR
void UIOSRuntimeSettings::PostEditChangeProperty(struct FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
// Ensure that at least one orientation is supported
if (!bSupportsPortraitOrientation && !bSupportsUpsideDownOrientation && !bSupportsLandscapeLeftOrientation && !bSupportsLandscapeRightOrientation)
{
bSupportsPortraitOrientation = true;
UpdateSinglePropertyInConfigFile(GetClass()->FindPropertyByName(GET_MEMBER_NAME_CHECKED(UIOSRuntimeSettings, bSupportsPortraitOrientation)), GetDefaultConfigFilename());
}
// Ensure that at least one API is supported
if (!bSupportsMetal && !bSupportsMetalMRT)
{
bSupportsMetal = true;
UpdateSinglePropertyInConfigFile(GetClass()->FindPropertyByName(GET_MEMBER_NAME_CHECKED(UIOSRuntimeSettings, bSupportsMetal)), GetDefaultConfigFilename());
}
if (bSupportsOpenGLES2)
{
bSupportsOpenGLES2 = false;
UpdateSinglePropertyInConfigFile(GetClass()->FindPropertyByName(GET_MEMBER_NAME_CHECKED(UIOSRuntimeSettings, bSupportsOpenGLES2)), GetDefaultConfigFilename());
}
// Ensure that at least arm64 is selected for shipping and dev
if (!bDevForArm64)
{
bDevForArm64 = true;
UpdateSinglePropertyInConfigFile(GetClass()->FindPropertyByName(GET_MEMBER_NAME_CHECKED(UIOSRuntimeSettings, bDevForArm64)), GetDefaultConfigFilename());
}
if (bDevForArmV7)
{
bDevForArmV7 = false;
UpdateSinglePropertyInConfigFile(GetClass()->FindPropertyByName(GET_MEMBER_NAME_CHECKED(UIOSRuntimeSettings, bDevForArmV7)), GetDefaultConfigFilename());
}
if (bDevForArmV7S)
{
bDevForArmV7S = false;
UpdateSinglePropertyInConfigFile(GetClass()->FindPropertyByName(GET_MEMBER_NAME_CHECKED(UIOSRuntimeSettings, bDevForArmV7S)), GetDefaultConfigFilename());
}
if (!bShipForArm64)
{
bShipForArm64 = true;
UpdateSinglePropertyInConfigFile(GetClass()->FindPropertyByName(GET_MEMBER_NAME_CHECKED(UIOSRuntimeSettings, bShipForArm64)), GetDefaultConfigFilename());
}
if (bShipForArmV7)
{
bShipForArmV7 = false;
UpdateSinglePropertyInConfigFile(GetClass()->FindPropertyByName(GET_MEMBER_NAME_CHECKED(UIOSRuntimeSettings, bShipForArmV7)), GetDefaultConfigFilename());
}
if (bShipForArmV7S)
{
bShipForArmV7S = false;
UpdateSinglePropertyInConfigFile(GetClass()->FindPropertyByName(GET_MEMBER_NAME_CHECKED(UIOSRuntimeSettings, bShipForArmV7S)), GetDefaultConfigFilename());
}
}
void UIOSRuntimeSettings::PostInitProperties()
{
Super::PostInitProperties();
// We can have a look for potential keys
if (!RemoteServerName.IsEmpty() && !RSyncUsername.IsEmpty())
{
SSHPrivateKeyLocation = TEXT("");
const FString DefaultKeyFilename = TEXT("RemoteToolChainPrivate.key");
const FString RelativeFilePathLocation = FPaths::Combine(TEXT("SSHKeys"), *RemoteServerName, *RSyncUsername, *DefaultKeyFilename);
FString Path = FPlatformMisc::GetEnvironmentVariable(TEXT("APPDATA"));
TArray<FString> PossibleKeyLocations;
PossibleKeyLocations.Add(FPaths::Combine(*FPaths::ProjectDir(), TEXT("Build"), TEXT("NotForLicensees"), *RelativeFilePathLocation));
PossibleKeyLocations.Add(FPaths::Combine(*FPaths::ProjectDir(), TEXT("Build"), TEXT("NoRedist"), *RelativeFilePathLocation));
PossibleKeyLocations.Add(FPaths::Combine(*FPaths::ProjectDir(), TEXT("Build"), *RelativeFilePathLocation));
PossibleKeyLocations.Add(FPaths::Combine(*FPaths::EngineDir(), TEXT("Build"), TEXT("NotForLicensees"), *RelativeFilePathLocation));
PossibleKeyLocations.Add(FPaths::Combine(*FPaths::EngineDir(), TEXT("Build"), TEXT("NoRedist"), *RelativeFilePathLocation));
PossibleKeyLocations.Add(FPaths::Combine(*FPaths::EngineDir(), TEXT("Build"), *RelativeFilePathLocation));
PossibleKeyLocations.Add(FPaths::Combine(*Path, TEXT("Unreal Engine"), TEXT("UnrealBuildTool"), *RelativeFilePathLocation));
// Find a potential path that we will use if the user hasn't overridden.
// For information purposes only
for (const FString& NextLocation : PossibleKeyLocations)
{
if (IFileManager::Get().FileSize(*NextLocation) > 0)
{
SSHPrivateKeyLocation = NextLocation;
break;
}
}
}
// switch IOS_6.1, IOS_7, IOS_8, and IOS_9 to IOS_10
if (MinimumiOSVersion < EIOSVersion::IOS_10)
{
MinimumiOSVersion = EIOSVersion::IOS_10;
}
if (bSupportsOpenGLES2)
{
bSupportsOpenGLES2 = false;
}
if (bDevForArmV7)
{
bDevForArmV7 = false;
}
if (bDevForArmV7S)
{
bDevForArmV7S = false;
}
if (bShipForArmV7)
{
bShipForArmV7 = false;
}
if (bShipForArmV7S)
{
bShipForArmV7S = false;
}
if (!bSupportsMetal && !bSupportsMetalMRT)
{
bSupportsMetal = true;
}
if (!bDevForArm64)
{
bDevForArm64 = true;
}
if (!bShipForArm64)
{
bShipForArm64 = true;
}
// Due to a driver bug on A8 devices running iOS 9 we can only support the global clip-plane when running iOS 10+
static IConsoleVariable* ClipPlaneCVar = IConsoleManager::Get().FindConsoleVariable(TEXT("r.AllowGlobalClipPlane"));
if (ClipPlaneCVar && ClipPlaneCVar->GetInt() != 0 && MinimumiOSVersion < EIOSVersion::IOS_10)
{
MinimumiOSVersion = EIOSVersion::IOS_10;
}
}
#endif
| 412 | 0.895403 | 1 | 0.895403 | game-dev | MEDIA | 0.25718 | game-dev | 0.90199 | 1 | 0.90199 |
Apress/pro-html5-games-17 | 6,976 | 9781484229095/9781484229095_Ch12/client/js/sidebar.js | var sidebar = {
init: function() {
this.cash = document.getElementById("cash");
let buttons = document.getElementById("sidebarbuttons").getElementsByTagName("input");
Array.prototype.forEach.call(buttons, function(button) {
button.addEventListener("click", function() {
// The input button id is the name of the object that needs to be constructed
let name = this.id;
let details = sidebar.constructables[name];
if (details.type === "buildings") {
sidebar.constructBuilding(details);
} else {
sidebar.constructInStarport(details);
}
});
});
},
animate: function() {
// Display the current cash balance value
this.updateCash(game.cash[game.team]);
// Enable buttons if player has sufficient cash and has the correct building selected
this.enableSidebarButtons();
// If sidebar is in deployBuilding mode, check whether building can be placed
if (this.deployBuilding) {
this.checkBuildingPlacement();
}
},
// Cache the value to avoid unnecessary DOM updates
_cash: undefined,
updateCash: function(cash) {
// Only update the DOM value if it is different from cached value
if (this._cash !== cash) {
this._cash = cash;
// Display the cash amount with commas
this.cash.innerHTML = cash.toLocaleString();
}
},
constructables: undefined,
initRequirementsForLevel: function() {
this.constructables = {};
let constructableTypes = ["buildings", "vehicles", "aircraft"];
constructableTypes.forEach(function(type) {
for (let name in window[type].list) {
let details = window[type].list[name];
let isInRequirements = game.currentLevel.requirements[type].indexOf(name) > -1;
if (details.canConstruct) {
sidebar.constructables[name] = {
name: name,
type: type,
permitted: isInRequirements,
cost: details.cost,
constructedIn: (type === "buildings") ? "base" : "starport"
};
}
}
});
},
enableSidebarButtons: function() {
let cashBalance = game.cash[game.team];
// Check if player has a base or starport selected
let baseSelected = false;
let starportSelected = false;
game.selectedItems.forEach(function(item) {
if (item.team === game.team && item.lifeCode === "healthy" && item.action === "stand") {
if (item.name === "base") {
baseSelected = true;
} else if (item.name === "starport") {
starportSelected = true;
}
}
});
for (let name in this.constructables) {
let item = this.constructables[name];
let button = document.getElementById(name);
// Does player have sufficient money to buy item
let sufficientMoney = cashBalance >= item.cost;
// Does the player have the appropriate building selected?
let correctBuilding = (baseSelected && item.constructedIn === "base")
|| (starportSelected && item.constructedIn === "starport");
button.disabled = !(item.permitted && sufficientMoney && correctBuilding);
}
},
constructInStarport: function(details) {
// Search for a selected starport which can construct the unit
let starport;
for (let i = game.selectedItems.length - 1; i >= 0; i--) {
let item = game.selectedItems[i];
if (item.name === "starport" && item.team === game.team
&& item.lifeCode === "healthy" && item.action === "stand") {
starport = item;
break;
}
}
// If an eligible starport is found, tell it to make the unit
if (starport) {
game.sendCommand([starport.uid], { type: "construct-unit", details: details });
}
},
constructBuilding: function(details) {
sidebar.deployBuilding = details;
},
checkBuildingPlacement: function() {
let name = sidebar.deployBuilding.name;
let details = buildings.list[name];
// Create a buildable grid to identify where building can be placed
game.rebuildBuildableGrid();
// Use buildableGrid to identify whether we can place the building
let canDeployBuilding = true;
let placementGrid = game.makeArrayCopy(details.buildableGrid);
for (let y = placementGrid.length - 1; y >= 0; y--) {
for (let x = placementGrid[y].length - 1; x >= 0; x--) {
// If a tile needs to be buildable for the building
if (placementGrid[y][x] === 1) {
// Check whether the tile is inside the map and buildable
if (mouse.gridY + y >= game.currentMap.mapGridHeight
|| mouse.gridX + x >= game.currentMap.mapGridWidth
|| fog.grid[game.team][mouse.gridY + y][mouse.gridX + x]
|| game.currentMapBuildableGrid[mouse.gridY + y][mouse.gridX + x]) {
// Otherwise mark tile as unbuildable
canDeployBuilding = false;
placementGrid[y][x] = 2;
}
}
}
}
sidebar.placementGrid = placementGrid;
sidebar.canDeployBuilding = canDeployBuilding;
},
cancelDeployingBuilding: function() {
sidebar.deployBuilding = undefined;
sidebar.placementGrid = undefined;
sidebar.canDeployBuilding = false;
},
finishDeployingBuilding: function() {
// Search for a selected base which can construct the unit
let base;
for (let i = game.selectedItems.length - 1; i >= 0; i--) {
let item = game.selectedItems[i];
if (item.name === "base" && item.team === game.team
&& item.lifeCode === "healthy" && item.action === "stand") {
base = item;
break;
}
}
// If an eligible base is found, tell it to make the unit
if (base) {
let name = sidebar.deployBuilding.name;
let details = {
name: name,
type: "buildings",
x: mouse.gridX,
y: mouse.gridY
};
game.sendCommand([base.uid], { type: "construct-building", details: details });
}
// Clear deploy building variables
sidebar.cancelDeployingBuilding();
},
}; | 412 | 0.853161 | 1 | 0.853161 | game-dev | MEDIA | 0.8876 | game-dev,web-frontend | 0.92079 | 1 | 0.92079 |
Team-Immersive-Intelligence/ImmersiveIntelligence | 3,328 | src/main/java/pl/pabilo8/immersiveintelligence/common/item/tools/ItemIITripodPeriscope.java | package pl.pabilo8.immersiveintelligence.common.item.tools;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.ItemMonsterPlacer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import pl.pabilo8.immersiveintelligence.common.entity.EntityTripodPeriscope;
import pl.pabilo8.immersiveintelligence.common.util.item.IICategory;
import pl.pabilo8.immersiveintelligence.common.util.item.IIItemEnum.IIItemProperties;
import pl.pabilo8.immersiveintelligence.common.util.item.ItemIIBase;
import java.util.List;
/**
* @author Pabilo8 (pabilo@iiteam.net)
* @since 23.01.2021
*/
@IIItemProperties(category = IICategory.WARFARE)
public class ItemIITripodPeriscope extends ItemIIBase
{
public ItemIITripodPeriscope()
{
super("tripod_periscope", 1);
}
/**
* Called when a Block is right-clicked with this Item
*/
public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ)
{
if(facing==EnumFacing.DOWN)
{
return EnumActionResult.FAIL;
}
else
{
boolean flag = worldIn.getBlockState(pos).getBlock().isReplaceable(worldIn, pos);
BlockPos blockpos = flag?pos: pos.offset(facing);
ItemStack itemstack = player.getHeldItem(hand);
if(!player.canPlayerEdit(blockpos, facing, itemstack))
{
return EnumActionResult.FAIL;
}
else
{
BlockPos blockpos1 = blockpos.up();
boolean flag1 = !worldIn.isAirBlock(blockpos)&&!worldIn.getBlockState(blockpos).getBlock().isReplaceable(worldIn, blockpos);
flag1 = flag1|(!worldIn.isAirBlock(blockpos1)&&!worldIn.getBlockState(blockpos1).getBlock().isReplaceable(worldIn, blockpos1));
if(flag1)
{
return EnumActionResult.FAIL;
}
else
{
double d0 = blockpos.getX();
double d1 = blockpos.getY();
double d2 = blockpos.getZ();
List<Entity> list = worldIn.getEntitiesWithinAABBExcludingEntity(null, new AxisAlignedBB(d0, d1, d2, d0+1.0D, d1+2.0D, d2+1.0D));
if(!list.isEmpty())
{
return EnumActionResult.FAIL;
}
else
{
if(!worldIn.isRemote)
{
worldIn.setBlockToAir(blockpos);
worldIn.setBlockToAir(blockpos1);
EntityTripodPeriscope periscope = new EntityTripodPeriscope(worldIn);
periscope.setPosition(d0+0.5D, d1, d2+0.5D);
float f = (float)MathHelper.floor((MathHelper.wrapDegrees(player.rotationYaw-180.0F)+22.5F)/45.0F)*45.0F;
periscope.setLocationAndAngles(d0+0.5D, d1, d2+0.5D, f, 0.0F);
periscope.periscopeYaw = f;
ItemMonsterPlacer.applyItemEntityDataToEntity(worldIn, player, itemstack, periscope);
worldIn.spawnEntity(periscope);
worldIn.playSound(null, periscope.posX, periscope.posY, periscope.posZ, SoundEvents.ENTITY_ARMORSTAND_PLACE, SoundCategory.BLOCKS, 0.75F, 0.8F);
}
itemstack.shrink(1);
return EnumActionResult.SUCCESS;
}
}
}
}
}
}
| 412 | 0.856758 | 1 | 0.856758 | game-dev | MEDIA | 0.996009 | game-dev | 0.942579 | 1 | 0.942579 |
Hoto-Mocha/New-Blue-Archive-Pixel-Dungeon | 2,694 | core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/sprites/DM201Sprite.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2025 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.sprites;
import com.shatteredpixel.shatteredpixeldungeon.Assets;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.DM201;
import com.shatteredpixel.shatteredpixeldungeon.effects.MagicMissile;
import com.shatteredpixel.shatteredpixeldungeon.effects.Speck;
import com.shatteredpixel.shatteredpixeldungeon.messages.Messages;
import com.shatteredpixel.shatteredpixeldungeon.utils.GLog;
import com.watabou.noosa.TextureFilm;
import com.watabou.noosa.audio.Sample;
import com.watabou.utils.Callback;
public class DM201Sprite extends MobSprite {
public DM201Sprite () {
super();
texture( Assets.Sprites.DM200 );
TextureFilm frames = new TextureFilm( texture, 21, 18 );
int c = 12;
idle = new Animation( 2, true );
idle.frames( frames, c+0, c+1 );
run = idle.clone();
attack = new Animation( 15, false );
attack.frames( frames, c+4, c+5, c+6 );
zap = new Animation( 15, false );
zap.frames( frames, c+7, c+8, c+8, c+7 );
die = new Animation( 8, false );
die.frames( frames, c+9, c+10, c+11 );
play( idle );
}
@Override
public void place(int cell) {
if (parent != null) parent.bringToFront(this);
super.place(cell);
}
@Override
public void die() {
emitter().burst( Speck.factory( Speck.WOOL ), 8 );
super.die();
}
public void zap( int cell ) {
super.zap( cell );
MagicMissile.boltFromChar( parent,
MagicMissile.CORROSION,
this,
cell,
new Callback() {
@Override
public void call() {
Sample.INSTANCE.play( Assets.Sounds.GAS );
((DM201)ch).onZapComplete();
}
} );
Sample.INSTANCE.play( Assets.Sounds.MISS, 1f, 1.5f );
GLog.w(Messages.get(DM201.class, "vent"));
}
@Override
public void onComplete( Animation anim ) {
if (anim == zap) {
idle();
}
super.onComplete( anim );
}
@Override
public int blood() {
return 0xFFFFFF88;
}
}
| 412 | 0.909735 | 1 | 0.909735 | game-dev | MEDIA | 0.981073 | game-dev | 0.928517 | 1 | 0.928517 |
Project-PLATEAU/PLATEAU-VIEW-4.0 | 1,628 | cms/server/pkg/model/builder.go | package model
import (
"time"
"github.com/reearth/reearth-cms/server/pkg/id"
)
type Builder struct {
model *Model
k id.Key
}
func New() *Builder {
return &Builder{model: &Model{}}
}
func (b *Builder) Build() (*Model, error) {
if b.model.id.IsNil() {
return nil, ErrInvalidID
}
if b.model.schema.IsNil() {
return nil, ErrInvalidID
}
if err := b.model.SetKey(b.k); err != nil {
return nil, err
}
if b.model.updatedAt.IsZero() {
b.model.updatedAt = b.model.CreatedAt()
}
return b.model, nil
}
func (b *Builder) MustBuild() *Model {
r, err := b.Build()
if err != nil {
panic(err)
}
return r
}
func (b *Builder) ID(id ID) *Builder {
b.model.id = id
return b
}
func (b *Builder) NewID() *Builder {
b.model.id = NewID()
return b
}
func (b *Builder) Project(p id.ProjectID) *Builder {
b.model.project = p
return b
}
func (b *Builder) Schema(s id.SchemaID) *Builder {
b.model.schema = s
return b
}
func (b *Builder) Metadata(m *id.SchemaID) *Builder {
b.model.metadata = m
return b
}
func (b *Builder) Name(name string) *Builder {
b.model.name = name
return b
}
func (b *Builder) Description(description string) *Builder {
b.model.description = description
return b
}
func (b *Builder) Key(key id.Key) *Builder {
b.k = key
return b
}
func (b *Builder) RandomKey() *Builder {
b.k = id.RandomKey()
return b
}
func (b *Builder) Public(public bool) *Builder {
b.model.public = public
return b
}
func (b *Builder) UpdatedAt(updatedAt time.Time) *Builder {
b.model.updatedAt = updatedAt
return b
}
func (b *Builder) Order(o int) *Builder {
b.model.order = o
return b
}
| 412 | 0.556354 | 1 | 0.556354 | game-dev | MEDIA | 0.243114 | game-dev | 0.73432 | 1 | 0.73432 |
DarkstarProject/darkstar | 1,089 | scripts/zones/Lower_Jeuno/npcs/Sutarara.lua | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Sutarara
-- Involved in Quests: Tenshodo Menbership (before accepting)
-- !pos 30 0.1 -2 245
-----------------------------------
require("scripts/globals/quests");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local TenshodoMembership = player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.TENSHODO_MEMBERSHIP);
local WildcatJeuno = player:getCharVar("WildcatJeuno");
if (player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.LURE_OF_THE_WILDCAT) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,10) == false) then
player:startEvent(10055);
elseif (TenshodoMembership ~= QUEST_COMPLETED) then
player:startEvent(208);
elseif (TenshodoMembership == QUEST_COMPLETED) then
player:startEvent(211);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 10055) then
player:setMaskBit(player:getCharVar("WildcatJeuno"),"WildcatJeuno",10,true);
end
end; | 412 | 0.853882 | 1 | 0.853882 | game-dev | MEDIA | 0.985112 | game-dev | 0.992095 | 1 | 0.992095 |
magefree/mage | 3,145 | Mage.Sets/src/mage/cards/i/IvoraInsatiableHeir.java | package mage.cards.i;
import mage.MageInt;
import mage.abilities.TriggeredAbilityImpl;
import mage.abilities.effects.common.CreateTokenEffect;
import mage.abilities.effects.common.DiscardCardControllerTriggeredAbility;
import mage.abilities.effects.common.counter.AddCountersSourceEffect;
import mage.abilities.keyword.TrampleAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.SuperType;
import mage.constants.Zone;
import mage.counters.CounterType;
import mage.game.Game;
import mage.game.events.DamagedEvent;
import mage.game.events.GameEvent;
import mage.game.permanent.token.BloodToken;
import java.util.UUID;
/**
* @author notgreat
*/
public final class IvoraInsatiableHeir extends CardImpl {
public IvoraInsatiableHeir(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{R}");
this.supertype.add(SuperType.LEGENDARY);
this.subtype.add(SubType.VAMPIRE);
this.subtype.add(SubType.WARRIOR);
this.power = new MageInt(1);
this.toughness = new MageInt(1);
// Trample
this.addAbility(TrampleAbility.getInstance());
// When Ivora, Insatiable Heir enters and whenever it deals combat damage to a player, create a Blood token.
this.addAbility(new IvoraInsatiableHeirTriggeredAbility());
// Whenever you discard a card, put a +1/+1 counter on Ivora.
this.addAbility(new DiscardCardControllerTriggeredAbility(
new AddCountersSourceEffect(CounterType.P1P1.createInstance()), false));
}
private IvoraInsatiableHeir(final IvoraInsatiableHeir card) {
super(card);
}
@Override
public IvoraInsatiableHeir copy() {
return new IvoraInsatiableHeir(this);
}
}
class IvoraInsatiableHeirTriggeredAbility extends TriggeredAbilityImpl {
IvoraInsatiableHeirTriggeredAbility() {
super(Zone.ALL, new CreateTokenEffect(new BloodToken()), false);
setTriggerPhrase("When {this} enters and whenever it deals combat damage to a player, ");
}
private IvoraInsatiableHeirTriggeredAbility(final IvoraInsatiableHeirTriggeredAbility ability) {
super(ability);
}
@Override
public IvoraInsatiableHeirTriggeredAbility copy() {
return new IvoraInsatiableHeirTriggeredAbility(this);
}
@Override
public boolean checkEventType(GameEvent event, Game game) {
switch (event.getType()) {
case ENTERS_THE_BATTLEFIELD:
case DAMAGED_PLAYER:
return true;
default:
return false;
}
}
@Override
public boolean checkTrigger(GameEvent event, Game game) {
switch (event.getType()) {
case ENTERS_THE_BATTLEFIELD:
return event.getTargetId().equals(getSourceId());
case DAMAGED_PLAYER:
return event.getSourceId().equals(getSourceId()) && ((DamagedEvent) event).isCombatDamage();
default:
return false;
}
}
}
| 412 | 0.982287 | 1 | 0.982287 | game-dev | MEDIA | 0.971378 | game-dev | 0.998449 | 1 | 0.998449 |
iPortalTeam/ImmersivePortalsMod | 11,766 | src/main/java/qouteall/imm_ptl/core/portal/nether_portal/NetherPortalGeneration.java | package qouteall.imm_ptl.core.portal.nether_portal;
import com.mojang.logging.LogUtils;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.Vec3;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import qouteall.imm_ptl.core.McHelper;
import qouteall.imm_ptl.core.chunk_loading.ChunkLoader;
import qouteall.imm_ptl.core.chunk_loading.DimensionalChunkPos;
import qouteall.imm_ptl.core.chunk_loading.ImmPtlChunkTracking;
import qouteall.imm_ptl.core.mc_utils.ServerTaskList;
import qouteall.imm_ptl.core.platform_specific.O_O;
import qouteall.imm_ptl.core.portal.LoadingIndicatorEntity;
import qouteall.imm_ptl.core.portal.PortalPlaceholderBlock;
import qouteall.imm_ptl.core.portal.custom_portal_gen.PortalGenInfo;
import qouteall.q_misc_util.Helper;
import qouteall.q_misc_util.my_util.IntBox;
import qouteall.q_misc_util.my_util.LimitedLogger;
import java.util.Arrays;
import java.util.Objects;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class NetherPortalGeneration {
private static final Logger LOGGER = LogUtils.getLogger();
@Nullable
public static IntBox findAirCubePlacement(
ServerLevel toWorld,
BlockPos mappedPosInOtherDimension,
Direction.Axis axis,
BlockPos neededAreaSize,
boolean allowForcePlacement
) {
BlockPos randomShift = new BlockPos(
toWorld.getRandom().nextBoolean() ? 1 : -1,
0,
toWorld.getRandom().nextBoolean() ? 1 : -1
);
IntBox foundAirCube =
axis == Direction.Axis.Y ?
NetherPortalMatcher.findHorizontalPortalPlacement(
neededAreaSize, toWorld, mappedPosInOtherDimension.offset(randomShift)
) :
NetherPortalMatcher.findVerticalPortalPlacement(
neededAreaSize, toWorld, mappedPosInOtherDimension.offset(randomShift)
);
if (foundAirCube == null) {
LOGGER.info("Cannot find normal portal placement");
foundAirCube = NetherPortalMatcher.findCubeAirAreaAtAnywhere(
neededAreaSize, toWorld, mappedPosInOtherDimension, 32
);
if (foundAirCube != null) {
if (isFloating(toWorld, foundAirCube)) {
foundAirCube = NetherPortalMatcher.levitateBox(toWorld, foundAirCube, 50);
}
}
}
if (foundAirCube == null) {
if (allowForcePlacement) {
Helper.err("Cannot find air cube within 32 blocks? " +
"Force placed portal. It will occupy normal blocks.");
return IntBox.fromBasePointAndSize(mappedPosInOtherDimension, neededAreaSize);
}
else {
return null;
}
}
return foundAirCube;
}
private static boolean isFloating(ServerLevel toWorld, IntBox foundAirCube) {
return foundAirCube.getSurfaceLayer(Direction.DOWN).stream().noneMatch(
blockPos -> toWorld.getBlockState(blockPos.below()).isSolid()
);
}
public static void setPortalContentBlock(
ServerLevel world,
BlockPos pos,
Direction.Axis normalAxis
) {
world.setBlockAndUpdate(
pos,
PortalPlaceholderBlock.instance.defaultBlockState().setValue(
PortalPlaceholderBlock.AXIS, normalAxis
)
);
}
public static void startGeneratingPortal(
ServerLevel fromWorld, ServerLevel toWorld,
BlockPortalShape fromShape,
BlockPos toPos,
int existingFrameSearchingRadius,
Predicate<BlockState> otherSideFramePredicate,
Consumer<BlockPortalShape> newFrameGenerateFunc,
Consumer<PortalGenInfo> portalEntityGeneratingFunc,
//return null for not generate new frame
Supplier<PortalGenInfo> newFramePlacer,
BooleanSupplier portalIntegrityChecker,
FrameSearching.FrameSearchingFunc<PortalGenInfo> matchShapeByFramePos
) {
ResourceKey<Level> fromDimension = fromWorld.dimension();
ResourceKey<Level> toDimension = toWorld.dimension();
MinecraftServer server = fromWorld.getServer();
Vec3 indicatorPos = fromShape.innerAreaBox.getCenterVec();
LoadingIndicatorEntity indicatorEntity =
LoadingIndicatorEntity.entityType.create(fromWorld);
indicatorEntity.isValid = true;
indicatorEntity.setPos(
indicatorPos.x, indicatorPos.y, indicatorPos.z
);
indicatorEntity.setBox(fromShape.innerAreaBox);
fromWorld.addFreshEntity(indicatorEntity);
Runnable onGenerateNewFrame = () -> {
indicatorEntity.inform(Component.translatable(
"imm_ptl.generating_new_frame"
));
PortalGenInfo info = newFramePlacer.get();
if (info != null) {
newFrameGenerateFunc.accept(info.toShape);
portalEntityGeneratingFunc.accept(info);
O_O.postPortalSpawnEventForge(info);
}
};
boolean otherSideChunkAlreadyGenerated = McHelper.getDoesRegionFileExist(toDimension, toPos);
int frameSearchingRadius = Math.floorDiv(existingFrameSearchingRadius, 16) + 1;
/**
* if the other side chunk is already generated, generate 128 range for searching the frame
* if the other side chunk is not yet generated, generate 1 or 2 chunk range for searching the frame placing position
* when generating chunks by getBlockState, subsequent setBlockState may leave lighting issues
* {@link net.minecraft.server.world.ServerLightingProvider#light(Chunk, boolean)}
* may get invoked twice for a chunk.
* Maybe related to https://bugs.mojang.com/browse/MC-170010
* Rough experiments shows that the lighting issue won't possibly manifest when manipulating blocks
* after the chunk has been fully generated.
*/
int loaderRadius = otherSideChunkAlreadyGenerated ?
frameSearchingRadius :
(fromShape.getShapeInnerLength() < 16 ? 1 : 2);
ChunkLoader chunkLoader = new ChunkLoader(
new DimensionalChunkPos(toDimension, new ChunkPos(toPos)), loaderRadius
);
ImmPtlChunkTracking.addGlobalAdditionalChunkLoader(server, chunkLoader);
Runnable finalizer = () -> {
indicatorEntity.remove(Entity.RemovalReason.KILLED);
ImmPtlChunkTracking.removeGlobalAdditionalChunkLoader(server, chunkLoader);
};
ServerTaskList.of(server).addTask(() -> {
boolean isPortalIntact = portalIntegrityChecker.getAsBoolean();
if (!isPortalIntact) {
finalizer.run();
return true;
}
int loadedChunks = chunkLoader.getLoadedChunkNum(server);
int allChunksNeedsLoading = chunkLoader.getChunkNum();
if (loadedChunks < allChunksNeedsLoading) {
indicatorEntity.inform(Component.translatable(
"imm_ptl.loading_chunks", loadedChunks, allChunksNeedsLoading
));
return false;
}
if (!otherSideChunkAlreadyGenerated) {
onGenerateNewFrame.run();
finalizer.run();
return true;
}
ChunkLoader chunkLoader1 = new ChunkLoader(
chunkLoader.getCenter(), frameSearchingRadius
);
ServerLevel world = McHelper.getServerWorld(server, chunkLoader1.dimension());
FastBlockAccess chunkRegion = chunkLoader1.createFastBlockAccess(world);
indicatorEntity.inform(Component.translatable("imm_ptl.searching_for_frame"));
FrameSearching.startSearchingPortalFrameAsync(
chunkRegion,
frameSearchingRadius, toPos,
otherSideFramePredicate,
matchShapeByFramePos,
(info) -> {
portalEntityGeneratingFunc.accept(info);
finalizer.run();
O_O.postPortalSpawnEventForge(info);
}, () -> {
onGenerateNewFrame.run();
finalizer.run();
});
return true;
});
}
public static boolean isOtherGenerationRunning(ServerLevel fromWorld, Vec3 indicatorPos) {
boolean isOtherGenerationRunning = McHelper.getEntitiesNearby(
fromWorld, indicatorPos, LoadingIndicatorEntity.class, 1
).stream().findAny().isPresent();
if (isOtherGenerationRunning) {
Helper.log(
"Aborted Portal Generation Because Another Generation is Running Nearby"
);
return true;
}
return false;
}
private static final LimitedLogger limitedLogger = new LimitedLogger(50);
public static boolean checkPortalGeneration(ServerLevel fromWorld, BlockPos startingPos) {
if (!fromWorld.hasChunkAt(startingPos)) {
Helper.log("Cancel Portal Generation Because Chunk Not Loaded");
return false;
}
limitedLogger.log(String.format("Portal Generation Attempted %s %s %s %s",
fromWorld.dimension().location(), startingPos.getX(), startingPos.getY(), startingPos.getZ()
));
return true;
}
public static BlockPortalShape findFrameShape(
ServerLevel fromWorld, BlockPos startingPos,
Predicate<BlockState> thisSideAreaPredicate,
Predicate<BlockState> thisSideFramePredicate
) {
return Arrays.stream(Direction.Axis.values())
.map(
axis -> {
return BlockPortalShape.findShapeWithoutRegardingStartingPos(
startingPos,
axis,
(pos) -> thisSideAreaPredicate.test(fromWorld.getBlockState(pos)),
(pos) -> thisSideFramePredicate.test(fromWorld.getBlockState(pos))
);
}
).filter(
Objects::nonNull
).findFirst().orElse(null);
}
public static void embodyNewFrame(
ServerLevel toWorld,
BlockPortalShape toShape,
BlockState frameBlockState
) {
toShape.frameAreaWithCorner.forEach(blockPos ->
toWorld.setBlockAndUpdate(blockPos, frameBlockState)
);
}
public static void fillInPlaceHolderBlocks(
ServerLevel world,
BlockPortalShape blockPortalShape
) {
blockPortalShape.area.forEach(
blockPos -> setPortalContentBlock(
world, blockPos, blockPortalShape.axis
)
);
}
}
| 412 | 0.866293 | 1 | 0.866293 | game-dev | MEDIA | 0.983804 | game-dev | 0.954257 | 1 | 0.954257 |
Baystation12/Baystation12 | 3,223 | code/game/antagonist/antagonist_helpers.dm | /** Checks if the given player is able to become an antagonist or not.
* Will return 'FALSE' if they can become an antagonist, or a string value describing why they cannot become one.
* Use strict type comparisons for truthiness values.
* `ignore_role` will skip restriced job, player age, and player status flag checks.
*/
/datum/antagonist/proc/can_become_antag_detailed(datum/mind/player, ignore_role)
if(player.current)
if(jobban_isbanned(player.current, id))
return "Player is banned from this antagonist role."
if(is_type_in_list(player.assigned_job, blacklisted_jobs) && !isghostmind(player))
return "Player's assigned job ([player.assigned_job]) is blacklisted from this antagonist role."
if(!ignore_role)
if(player.current && player.current.client)
var/client/C = player.current.client
// Limits antag status to clients above player age, if the age system is being used.
if(C && config.use_age_restriction_for_jobs && isnum(C.player_age) && isnum(min_player_age) && (C.player_age < min_player_age))
return "Player's server age ([C.player_age]) is below the minimum player age ([min_player_age])."
if(is_type_in_list(player.assigned_job, restricted_jobs) && !isghostmind(player))
return "Player's assigned job ([player.assigned_job]) is restricted from this antagonist role."
if(player.current && (player.current.status_flags & NO_ANTAG) && !isghostmind(player))
return "Player's mob has the NO_ANTAG flag set."
return FALSE
/// Checks if the given player is able to become an antagonist or not. Simplified version of `can_become_antag_detailed()`.
/datum/antagonist/proc/can_become_antag(datum/mind/player, ignore_role)
return !can_become_antag_detailed(player, ignore_role)
/datum/antagonist/proc/antags_are_dead()
for(var/datum/mind/antag in current_antagonists)
if(mob_path && !istype(antag.current,mob_path))
continue
if(antag.current.stat==2)
continue
return 0
return 1
/datum/antagonist/proc/get_antag_count()
return current_antagonists ? length(current_antagonists) : 0
/datum/antagonist/proc/get_active_antag_count()
var/active_antags = 0
for(var/datum/mind/player in current_antagonists)
var/mob/living/L = player.current
if(!L || L.is_real_dead())
continue //no mob or dead
if(!L.client && !L.teleop)
continue //SSD
active_antags++
return active_antags
/datum/antagonist/proc/is_antagonist(datum/mind/player)
if(player in current_antagonists)
return 1
/datum/antagonist/proc/is_type(antag_type)
if(antag_type == id || antag_type == role_text)
return 1
return 0
/datum/antagonist/proc/is_votable()
return (flags & ANTAG_VOTABLE)
/datum/antagonist/proc/can_late_spawn()
if(!SSticker.mode)
return 0
if(!(id in SSticker.mode.latejoin_antag_tags))
return 0
return 1
/datum/antagonist/proc/is_latejoin_template()
return (flags & (ANTAG_OVERRIDE_MOB|ANTAG_OVERRIDE_JOB))
/proc/all_random_antag_types()
RETURN_TYPE(/list)
// No caching as the ANTAG_RANDOM_EXCEPTED flag can be added/removed mid-round.
var/list/antag_candidates = GLOB.all_antag_types_.Copy()
for(var/datum/antagonist/antag in antag_candidates)
if(antag.flags & ANTAG_RANDOM_EXCEPTED)
antag_candidates -= antag
return antag_candidates
| 412 | 0.77534 | 1 | 0.77534 | game-dev | MEDIA | 0.915362 | game-dev | 0.938629 | 1 | 0.938629 |
revolucas/CoC-Xray | 2,927 | src/xrGame/enemy_manager.h | ////////////////////////////////////////////////////////////////////////////
// Module : enemy_manager.h
// Created : 30.12.2003
// Modified : 30.12.2003
// Author : Dmitriy Iassenev
// Description : Enemy manager
////////////////////////////////////////////////////////////////////////////
#pragma once
#include "object_manager.h"
#include "entity_alive.h"
#include "custommonster.h"
#include "script_callback_ex.h"
class CAI_Stalker;
class CEnemyManager : public CObjectManager<const CEntityAlive> {
public:
typedef CObjectManager<const CEntityAlive> inherited;
typedef OBJECTS ENEMIES;
typedef CScriptCallbackEx<bool> USEFULE_CALLBACK;
private:
CCustomMonster *m_object;
CAI_Stalker *m_stalker;
float m_ignore_monster_threshold;
float m_max_ignore_distance;
mutable bool m_ready_to_save;
u32 m_last_enemy_time;
const CEntityAlive *m_last_enemy;
USEFULE_CALLBACK m_useful_callback;
bool m_enable_enemy_change;
CEntityAlive const *m_smart_cover_enemy;
private:
u32 m_last_enemy_change;
private:
IC bool enemy_inertia (const CEntityAlive *previous_enemy) const;
bool need_update (const bool &only_wounded) const;
void process_wounded (bool &only_wounded);
bool change_from_wounded (const CEntityAlive *current, const CEntityAlive *previous) const;
void remove_wounded ();
void try_change_enemy ();
protected:
void on_enemy_change (const CEntityAlive *previous_enemy);
bool expedient (const CEntityAlive *object) const;
public:
CEnemyManager (CCustomMonster *object);
virtual void reload (LPCSTR section);
virtual bool useful (const CEntityAlive *object) const;
virtual bool is_useful (const CEntityAlive *object) const;
virtual float evaluate (const CEntityAlive *object) const;
virtual float do_evaluate (const CEntityAlive *object) const;
virtual void update ();
virtual void set_ready_to_save ();
IC u32 last_enemy_time () const;
IC const CEntityAlive *last_enemy () const;
IC USEFULE_CALLBACK &useful_callback ();
void remove_links (CObject *object);
public:
void ignore_monster_threshold (const float &ignore_monster_threshold);
void restore_ignore_monster_threshold ();
float ignore_monster_threshold () const;
void max_ignore_monster_distance (const float &max_ignore_monster_distance);
void restore_max_ignore_monster_distance ();
float max_ignore_monster_distance () const;
public:
void wounded (const CEntityAlive *wounded_enemy);
IC const CEntityAlive *wounded () const;
IC CEntityAlive const *selected () const;
IC void set_enemy (CEntityAlive const *enemy);
IC void invalidate_enemy ();
public:
IC void enable_enemy_change (const bool &value);
IC bool enable_enemy_change () const;
};
#include "enemy_manager_inline.h" | 412 | 0.926605 | 1 | 0.926605 | game-dev | MEDIA | 0.977572 | game-dev | 0.59321 | 1 | 0.59321 |
shagu/pfUI | 5,534 | libs/libtooltip.lua | -- load pfUI environment
setfenv(1, pfUI:GetEnvironment())
--[[ libtooltip ]]--
-- A pfUI library that provides additional GameTooltip information.
--
-- libtooltip:GetItemID()
-- returns the itemID of the current GameTooltip
-- `nil` when no item is displayed
--
-- libtooltip:GetItemLink()
-- returns the itemLink of the current GameTooltip
-- `nil` when no item is displayed
--
-- libtooltip:GetItemCount()
-- returns the item count (bags) of the current GameTooltip
-- `nil` when no item is displayed
-- return instantly when another libtooltip is already active
if pfUI.api.libtooltip then return end
local _
local libtooltip = CreateFrame("Frame" , "pfLibTooltip", GameTooltip)
libtooltip:SetScript("OnHide", function()
this.itemID = nil
this.itemLink = nil
this.itemCount = nil
end)
-- core functions
libtooltip.GetItemID = function(self)
if not libtooltip.itemLink then return end
if not libtooltip.itemID then
local _, _, itemID = string.find(libtooltip.itemLink, "item:(%d+):%d+:%d+:%d+")
libtooltip.itemID = tonumber(itemID)
end
return libtooltip.itemID
end
libtooltip.GetItemLink = function(self)
return libtooltip.itemLink
end
libtooltip.GetItemCount = function(self)
return libtooltip.itemCount
end
pfUI.api.libtooltip = libtooltip
-- setup item hooks
local pfHookSetHyperlink = GameTooltip.SetHyperlink
function GameTooltip.SetHyperlink(self, arg1)
if arg1 then
local _, _, linktype = string.find(arg1, "^(.-):(.+)$")
if linktype == "item" then
libtooltip.itemLink = arg1
end
end
return pfHookSetHyperlink(self, arg1)
end
local pfHookSetBagItem = GameTooltip.SetBagItem
function GameTooltip.SetBagItem(self, container, slot)
-- skip special/invalid calls to the function
if not container or not slot then
return pfHookSetBagItem(self, container, slot)
end
libtooltip.itemLink = GetContainerItemLink(container, slot)
_, libtooltip.itemCount = GetContainerItemInfo(container, slot)
return pfHookSetBagItem(self, container, slot)
end
local pfHookSetQuestLogItem = GameTooltip.SetQuestLogItem
function GameTooltip.SetQuestLogItem(self, itemType, index)
libtooltip.itemLink = GetQuestLogItemLink(itemType, index)
if not libtooltip.itemLink then return end
return pfHookSetQuestLogItem(self, itemType, index)
end
local pfHookSetQuestItem = GameTooltip.SetQuestItem
function GameTooltip.SetQuestItem(self, itemType, index)
libtooltip.itemLink = GetQuestItemLink(itemType, index)
return pfHookSetQuestItem(self, itemType, index)
end
local pfHookSetLootItem = GameTooltip.SetLootItem
function GameTooltip.SetLootItem(self, slot)
libtooltip.itemLink = GetLootSlotLink(slot)
pfHookSetLootItem(self, slot)
end
local pfHookSetInboxItem = GameTooltip.SetInboxItem
function GameTooltip.SetInboxItem(self, mailID, attachmentIndex)
local itemName, itemTexture, inboxItemCount, inboxItemQuality = GetInboxItem(mailID)
libtooltip.itemLink = GetItemLinkByName(itemName)
return pfHookSetInboxItem(self, mailID, attachmentIndex)
end
local pfHookSetInventoryItem = GameTooltip.SetInventoryItem
function GameTooltip.SetInventoryItem(self, unit, slot)
libtooltip.itemLink = GetInventoryItemLink(unit, slot)
return pfHookSetInventoryItem(self, unit, slot)
end
local pfHookSetLootRollItem = GameTooltip.SetLootRollItem
function GameTooltip.SetLootRollItem(self, id)
libtooltip.itemLink = GetLootRollItemLink(id)
return pfHookSetLootRollItem(self, id)
end
local pfHookSetMerchantItem = GameTooltip.SetMerchantItem
function GameTooltip.SetMerchantItem(self, merchantIndex)
libtooltip.itemLink = GetMerchantItemLink(merchantIndex)
return pfHookSetMerchantItem(self, merchantIndex)
end
local pfHookSetCraftItem = GameTooltip.SetCraftItem
function GameTooltip.SetCraftItem(self, skill, slot)
libtooltip.itemLink = GetCraftReagentItemLink(skill, slot)
return pfHookSetCraftItem(self, skill, slot)
end
local pfHookSetCraftSpell = GameTooltip.SetCraftSpell
function GameTooltip.SetCraftSpell(self, slot)
libtooltip.itemLink = GetCraftItemLink(slot)
return pfHookSetCraftSpell(self, slot)
end
local pfHookSetTradeSkillItem = GameTooltip.SetTradeSkillItem
function GameTooltip.SetTradeSkillItem(self, skillIndex, reagentIndex)
if reagentIndex then
libtooltip.itemLink = GetTradeSkillReagentItemLink(skillIndex, reagentIndex)
else
libtooltip.itemLink = GetTradeSkillItemLink(skillIndex)
end
return pfHookSetTradeSkillItem(self, skillIndex, reagentIndex)
end
local pfHookSetAuctionItem = GameTooltip.SetAuctionItem
function GameTooltip.SetAuctionItem(self, atype, index)
_, _, libtooltip.itemCount = GetAuctionItemInfo(atype, index)
libtooltip.itemLink = GetAuctionItemLink(atype, index)
return pfHookSetAuctionItem(self, atype, index)
end
local pfHookSetAuctionSellItem = GameTooltip.SetAuctionSellItem
function GameTooltip.SetAuctionSellItem(self)
local itemName, _, itemCount = GetAuctionSellItemInfo()
libtooltip.itemCount = itemCount
libtooltip.itemLink = GetItemLinkByName(itemName)
return pfHookSetAuctionSellItem(self)
end
local pfHookSetTradePlayerItem = GameTooltip.SetTradePlayerItem
function GameTooltip.SetTradePlayerItem(self, index)
libtooltip.itemLink = GetTradePlayerItemLink(index)
return pfHookSetTradePlayerItem(self, index)
end
local pfHookSetTradeTargetItem = GameTooltip.SetTradeTargetItem
function GameTooltip.SetTradeTargetItem(self, index)
libtooltip.itemLink = GetTradeTargetItemLink(index)
return pfHookSetTradeTargetItem(self, index)
end
| 412 | 0.923138 | 1 | 0.923138 | game-dev | MEDIA | 0.951488 | game-dev | 0.706924 | 1 | 0.706924 |
gitzhzhg/SeismicPackage | 4,466 | CPSeis/spws_home/include/geom/fg_helper.hh | /*<license>
-------------------------------------------------------------------------------
Copyright (c) 2007 ConocoPhillips Company
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.
-------------------------------------------------------------------------------
</license>*/
//---------------------- fg_helper.hh ---------------------//
//---------------------- fg_helper.hh ---------------------//
//---------------------- fg_helper.hh ---------------------//
// header file for the FgHelper class
// not derived from any class
// subdirectory geom
// This class functions as a helper to the FieldGeometry class.
#ifndef _FG_HELPER_HH_
#define _FG_HELPER_HH_
class FgHelper
{
//----------------------- data ------------------------------//
//----------------------- data ------------------------------//
//----------------------- data ------------------------------//
private:
int _data_needs_saving; // whether data has changed (since last saved).
int _frozen; // whether updates of dependent values are frozen.
int _out_of_date; // whether dependent values are out-of-date.
int _major; // whether major operations are in progress.
int _data_changing; // whether data is in the process of changing.
int _lock; // to what extent data changes are locked.
class FieldGeometry *_fg;
class FgInformer *_informer;
class FgGathers *_gathers;
//----------------------- functions -------------------------//
//----------------------- functions -------------------------//
//----------------------- functions -------------------------//
public:
FgHelper (FieldGeometry *fg, FgInformer *informer, FgGathers *gathers);
virtual ~FgHelper();
int isLocked (int lowest_lock);
void notifyDataWillChange(int grid, int chng);
void notifyDataHasChanged(int grid, int chng);
int dataNeedsSaving () const { return _data_needs_saving; }
int dependentUpdatesFrozen () const { return _frozen; }
int dependentValuesOutOfDate () const { return _out_of_date; }
void turnOffDataNeedsSavingFlag ();
int getDataLock () const { return _lock; }
void setDataLock (int lock);
int allowDeletingData () const;
int allowModifyingLdCards () const;
int allowModifyingPpCards () const;
int allowModifyingRpCards () const;
int allowModifyingZt1Cards () const;
int allowModifyingZt2Cards () const;
int allowModifyingZt3Cards () const;
int allowModifyingZt4Cards () const;
int allowModifyingGridTransform () const;
void preMajorChanges ();
void postMajorChanges ();
void freezeDependentUpdates ();
void preResumeDependentUpdates ();
void postResumeDependentUpdates ();
void preUpdateGathers (int which);
void postUpdateGathers (int which);
//---------------------- end of functions -----------------------//
//---------------------- end of functions -----------------------//
//---------------------- end of functions -----------------------//
} ;
#endif
//---------------------------- end --------------------------------//
//---------------------------- end --------------------------------//
//---------------------------- end --------------------------------//
| 412 | 0.94145 | 1 | 0.94145 | game-dev | MEDIA | 0.582445 | game-dev | 0.699345 | 1 | 0.699345 |
geru-scotland/echoes-of-gaia | 3,301 | biome/systems/managers/entity_manager.py | """
# =============================================================================
# #
# ✦ ECHOES OF GAIA ✦ #
# #
# Trabajo Fin de Grado (TFG) #
# Facultad de Ingeniería Informática - Donostia #
# UPV/EHU - Euskal Herriko Unibertsitatea #
# #
# Área de Computación e Inteligencia Artificial #
# #
# Autor: Aingeru García Blas #
# GitHub: https://github.com/geru-scotland #
# Repo: https://github.com/geru-scotland/echoes-of-gaia #
# #
# =============================================================================
"""
"""
Entity data access provider for biome system interactions.
Provides filtered entity collections based on type and lifecycle status;
connects systems to the entity registry through a consistent interface.
Abstracts entity access and retrieval logic from world map implementation.
"""
from typing import Tuple
from biome.entities.entity import Entity
from biome.systems.maps.worldmap import WorldMap
from shared.enums.enums import EntityType
from shared.types import EntityList, EntityRegistry
class EntityProvider:
def __init__(self, world_map: WorldMap):
self._world_map: WorldMap = world_map
self._entities: EntityList = self._world_map.get_entities()
def get_entities(self, only_alive: bool = False) -> Tuple[EntityList, EntityList]:
entities: EntityList = self._world_map.get_entities(only_alive)
flora: EntityList = self.get_entities_by_type(entities, EntityType.FLORA)
fauna: EntityList = self.get_entities_by_type(entities, EntityType.FAUNA)
return flora, fauna
def get_entities_by_type(self, entities: EntityList, entity_type: EntityType,
only_alive: bool = False) -> EntityList:
if only_alive:
return [entity for entity in entities if entity.get_type() == entity_type and entity.is_alive()]
return [entity for entity in entities if entity.get_type() == entity_type]
def get_flora(self, only_alive: bool = False) -> EntityList:
entities: EntityList = self._world_map.get_entities(only_alive)
return self.get_entities_by_type(entities, EntityType.FLORA, only_alive)
def get_fauna(self, only_alive: bool = False) -> EntityList:
entities: EntityList = self._world_map.get_entities(only_alive)
return self.get_entities_by_type(entities, EntityType.FAUNA, only_alive)
def get_entity_by_id(self, id: int) -> Entity:
if self._world_map:
entity_registry: EntityRegistry = self._world_map.entity_registry
if entity_registry:
return entity_registry.get(id)
| 412 | 0.801634 | 1 | 0.801634 | game-dev | MEDIA | 0.648272 | game-dev | 0.833892 | 1 | 0.833892 |
tgstation/TerraGov-Marine-Corps | 7,842 | code/game/objects/structures/mineral_doors.dm | //NOT using the existing /obj/machinery/door type, since that has some complications on its own, mainly based on its
//machineryness
/obj/structure/mineral_door
name = "mineral door"
density = TRUE
opacity = TRUE
allow_pass_flags = NONE
icon = 'icons/obj/doors/mineral_doors.dmi'
icon_state = "metal"
///Are we open or not
var/open = FALSE
///Are we currently opening/closing
var/switching_states = FALSE
///The sound that gets played when opening/closing this door
var/trigger_sound = 'sound/effects/stonedoor_openclose.ogg'
///The type of material we're made from and what we drop when destroyed
var/material_type
/obj/structure/mineral_door/Initialize(mapload)
if((locate(/mob/living) in loc) && !open) //If we build a door below ourselves, it starts open.
toggle_state()
/*
We are calling parent later because if we toggle state, the opacity changes only to change to
non opaque after the parent procs do their thing, this is an issue because this changes the
directional opacity of the turf below to be opaque from all sides, which screws with
line of sight because the turf below the door is considered opaque, when it shouldn't be.
*/
return ..()
/obj/structure/mineral_door/Bumped(atom/user)
. = ..()
if(!open)
return try_toggle_state(user)
/obj/structure/mineral_door/attack_hand(mob/living/user)
. = ..()
if(.)
return
return try_toggle_state(user)
/obj/structure/mineral_door/CanAllowThrough(atom/movable/mover, turf/target)
if(istype(mover, /obj/effect/beam))
return !opacity
return ..()
/*
* Checks all the requirements for opening/closing a door before opening/closing it
*
* atom/user - the mob trying to open/close this door
*/
/obj/structure/mineral_door/proc/try_toggle_state(atom/user)
if(switching_states || !ismob(user) || locate(/mob/living) in get_turf(src))
return
var/mob/M = user
if(!M.client)
return
if(iscarbon(M))
var/mob/living/carbon/C = M
if(C.handcuffed)
return
toggle_state()
///The proc that actually does the door closing. Plays the sound, the animation, etc.
/obj/structure/mineral_door/proc/toggle_state()
switching_states = TRUE
open = !open
playsound(get_turf(src), trigger_sound, 25, 1)
flick("[base_icon_state][smoothing_flags ? "-[smoothing_junction]" : ""]-[open ? "opening" : "closing"]", src)
density = !density
opacity = !opacity
update_icon()
addtimer(VARSET_CALLBACK(src, switching_states, FALSE), 1 SECONDS)
/obj/structure/mineral_door/update_icon_state()
. = ..()
if(open)
icon_state = "[base_icon_state][smoothing_flags ? "-[smoothing_junction]" : ""]-open"
else
icon_state = "[base_icon_state][smoothing_flags ? "-[smoothing_junction]" : ""]"
/obj/structure/mineral_door/attackby(obj/item/attacking_item, mob/living/user)
. = ..()
if(.)
return
if(QDELETED(src))
return
if(user.a_intent == INTENT_HARM)
return
if(!(obj_flags & CAN_BE_HIT))
return
return attacking_item.attack_obj(src, user)
/obj/structure/mineral_door/attacked_by(obj/item/attacking_item, mob/living/user, def_zone)
. = ..()
if(attacking_item.damtype != BURN)
return
var/damage_multiplier = get_burn_damage_multiplier(attacking_item, user, def_zone)
take_damage(max(0, attacking_item.force * damage_multiplier), attacking_item.damtype, MELEE)
/obj/structure/mineral_door/Destroy()
if(material_type)
for(var/i in 1 to rand(1,5))
new material_type(get_turf(src))
return ..()
///Takes extra damage if our attacking item does burn damage
/obj/structure/mineral_door/proc/get_burn_damage_multiplier(obj/item/attacking_item, mob/living/user, def_zone, bonus_damage = 0)
if(!isplasmacutter(attacking_item))
return bonus_damage
var/obj/item/tool/pickaxe/plasmacutter/attacking_pc = attacking_item
if(attacking_pc.start_cut(user, name, src, PLASMACUTTER_BASE_COST * PLASMACUTTER_VLOW_MOD, no_string = TRUE))
bonus_damage += PLASMACUTTER_RESIN_MULTIPLIER * 0.5
attacking_pc.cut_apart(user, name, src, PLASMACUTTER_BASE_COST * PLASMACUTTER_VLOW_MOD) //Minimal energy cost.
return bonus_damage
/obj/structure/mineral_door/resin/get_burn_damage_multiplier(obj/item/attacking_item, mob/living/user, def_zone, bonus_damage = 1)
if(!isplasmacutter(attacking_item))
return bonus_damage
var/obj/item/tool/pickaxe/plasmacutter/attacking_pc = attacking_item
if(attacking_pc.start_cut(user, name, src, PLASMACUTTER_BASE_COST * PLASMACUTTER_VLOW_MOD, no_string = TRUE))
bonus_damage += PLASMACUTTER_RESIN_MULTIPLIER
attacking_pc.cut_apart(user, name, src, PLASMACUTTER_BASE_COST * PLASMACUTTER_VLOW_MOD) //Minimal energy cost.
return bonus_damage
/obj/structure/mineral_door/resin/plasmacutter_act(mob/living/user, obj/item/I)
if(!isplasmacutter(I) || user.do_actions)
return FALSE
if(!(obj_flags & CAN_BE_HIT) || CHECK_BITFIELD(resistance_flags, PLASMACUTTER_IMMUNE) || CHECK_BITFIELD(resistance_flags, INDESTRUCTIBLE))
return FALSE
var/obj/item/tool/pickaxe/plasmacutter/plasmacutter = I
if(!plasmacutter.powered || (plasmacutter.item_flags & NOBLUDGEON))
return FALSE
var/charge_cost = PLASMACUTTER_BASE_COST * PLASMACUTTER_VLOW_MOD
if(!plasmacutter.start_cut(user, name, src, charge_cost, no_string = TRUE))
return FALSE
user.changeNext_move(plasmacutter.attack_speed)
user.do_attack_animation(src, used_item = plasmacutter)
plasmacutter.cut_apart(user, name, src, charge_cost)
take_damage(max(0, plasmacutter.force * (1 + PLASMACUTTER_RESIN_MULTIPLIER)), plasmacutter.damtype, MELEE)
playsound(src, SFX_ALIEN_RESIN_BREAK, 25)
return TRUE
/obj/structure/mineral_door/iron
name = "iron door"
material_type = /obj/item/stack/sheet/metal
base_icon_state = "metal"
max_integrity = 500
/obj/structure/mineral_door/silver
name = "silver door"
material_type = /obj/item/stack/sheet/mineral/silver
base_icon_state = "silver"
icon_state = "silver"
max_integrity = 500
/obj/structure/mineral_door/gold
name = "gold door"
material_type = /obj/item/stack/sheet/mineral/gold
base_icon_state = "gold"
icon_state = "gold"
max_integrity = 250
/obj/structure/mineral_door/uranium
name = "uranium door"
material_type = /obj/item/stack/sheet/mineral/uranium
base_icon_state = "uranium"
icon_state = "uranium"
max_integrity = 500
/obj/structure/mineral_door/sandstone
name = "sandstone door"
material_type = /obj/item/stack/sheet/mineral/sandstone
base_icon_state = "sandstone"
icon_state = "sandstone"
max_integrity = 100
/obj/structure/mineral_door/transparent
name = "generic transparent door"
desc = "You shouldn't be seeing this."
opacity = FALSE
/obj/structure/mineral_door/transparent/toggle_state()
..()
opacity = FALSE
/obj/structure/mineral_door/transparent/phoron
name = "phoron door"
material_type = /obj/item/stack/sheet/mineral/phoron
base_icon_state = "phoron"
icon_state = "phoron"
max_integrity = 250
/obj/structure/mineral_door/transparent/phoron/attackby(obj/item/attacking_item as obj, mob/user as mob)
if(istype(attacking_item, /obj/item/tool/weldingtool))
var/obj/item/tool/weldingtool/WT = attacking_item
if(WT.remove_fuel(0, user))
var/turf/T = get_turf(src)
T.ignite(25, 25)
visible_message(span_danger("[src] suddenly combusts!"))
return ..()
/obj/structure/mineral_door/transparent/phoron/fire_act(burn_level)
if(burn_level > 30)
var/turf/T = get_turf(src)
T.ignite(25, 25)
/obj/structure/mineral_door/transparent/diamond
name = "diamond door"
material_type = /obj/item/stack/sheet/mineral/diamond
base_icon_state = "diamond"
icon_state = "diamond"
max_integrity = 1000
/obj/structure/mineral_door/wood
name = "wooden door"
material_type = /obj/item/stack/sheet/wood
base_icon_state = "wood"
icon_state = "wood"
trigger_sound = 'sound/effects/doorcreaky.ogg'
max_integrity = 100
/obj/structure/mineral_door/wood/add_debris_element()
AddElement(/datum/element/debris, DEBRIS_WOOD, -40, 5)
| 412 | 0.956543 | 1 | 0.956543 | game-dev | MEDIA | 0.946684 | game-dev | 0.963234 | 1 | 0.963234 |
stubma/cocos2dx-classical | 26,585 | cocos2dx/actions/CCActionInterval.h | /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2011 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __ACTION_CCINTERVAL_ACTION_H__
#define __ACTION_CCINTERVAL_ACTION_H__
#include "base_nodes/CCNode.h"
#include "CCAction.h"
#include "CCProtocols.h"
#include "sprite_nodes/CCSpriteFrame.h"
#include "sprite_nodes/CCAnimation.h"
#include <vector>
NS_CC_BEGIN
/**
* @addtogroup actions
* @{
*/
/**
@brief An interval action is an action that takes place within a certain period of time.
It has an start time, and a finish time. The finish time is the parameter
duration plus the start time.
These CCActionInterval actions have some interesting properties, like:
- They can run normally (default)
- They can run reversed with the reverse method
- They can run with the time altered with the Accelerate, AccelDeccel and Speed actions.
For example, you can simulate a Ping Pong effect running the action normally and
then running it again in Reverse mode.
Example:
CCAction *pingPongAction = CCSequence::actions(action, action->reverse(), NULL);
*/
class CC_DLL CCActionInterval : public CCFiniteTimeAction
{
public:
/** how many seconds had elapsed since the actions started to run. */
inline float getElapsed(void) { return m_elapsed; }
/** initializes the action */
bool initWithDuration(float d);
/** returns true if the action has finished */
virtual bool isDone(void);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void step(float dt);
virtual void startWithTarget(CCNode *pTarget);
/** returns a reversed action */
virtual CCActionInterval* reverse(void);
public:
/** creates the action */
static CCActionInterval* create(float d);
public:
//extension in CCGridAction
void setAmplitudeRate(float amp);
float getAmplitudeRate(void);
protected:
float m_elapsed;
bool m_bFirstTick;
};
/** @brief Runs actions sequentially, one after another
*/
class CC_DLL CCSequence : public CCActionInterval
{
public:
/**
* @js NA
* @lua NA
*/
~CCSequence(void);
/** initializes the action
* @lua NA
*/
bool initWithTwoActions(CCFiniteTimeAction *pActionOne, CCFiniteTimeAction *pActionTwo);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
/**
* @lua NA
*/
virtual void startWithTarget(CCNode *pTarget);
/**
* @lua NA
*/
virtual void stop(void);
/**
* @lua NA
*/
virtual void update(float t);
virtual CCActionInterval* reverse(void);
public:
/** helper constructor to create an array of sequenceable actions
* @lua NA
*/
static CCSequence* create(CCFiniteTimeAction *pAction1, ...);
/** helper constructor to create an array of sequenceable actions given an array
* @js NA
*/
static CCSequence* create(CCArray *arrayOfActions);
/** helper constructor to create an array of sequence-able actions
* @js NA
* @lua NA
*/
static CCSequence* createWithVariableList(CCFiniteTimeAction *pAction1, va_list args);
/** creates the action
* @js NA
*/
static CCSequence* createWithTwoActions(CCFiniteTimeAction *pActionOne, CCFiniteTimeAction *pActionTwo);
protected:
CCFiniteTimeAction *m_pActions[2];
float m_split;
int m_last;
};
/** @brief Repeats an action a number of times.
* To repeat an action forever use the CCRepeatForever action.
*/
class CC_DLL CCRepeat : public CCActionInterval
{
public:
/**
* @js NA
* @lua NA
*/
~CCRepeat(void);
/** initializes a CCRepeat action. Times is an unsigned integer between 1 and pow(2,30) */
bool initWithAction(CCFiniteTimeAction *pAction, unsigned int times);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget);
virtual void stop(void);
virtual void update(float dt);
virtual bool isDone(void);
virtual CCActionInterval* reverse(void);
inline void setInnerAction(CCFiniteTimeAction *pAction)
{
if (m_pInnerAction != pAction)
{
CC_SAFE_RETAIN(pAction);
CC_SAFE_RELEASE(m_pInnerAction);
m_pInnerAction = pAction;
}
}
inline CCFiniteTimeAction* getInnerAction()
{
return m_pInnerAction;
}
public:
/** creates a CCRepeat action. Times is an unsigned integer between 1 and pow(2,30) */
static CCRepeat* create(CCFiniteTimeAction *pAction, unsigned int times);
protected:
unsigned int m_uTimes;
unsigned int m_uTotal;
float m_fNextDt;
bool m_bActionInstant;
/** Inner action */
CCFiniteTimeAction *m_pInnerAction;
};
/** @brief Repeats an action for ever.
To repeat the an action for a limited number of times use the Repeat action.
@warning This action can't be Sequenceable because it is not an IntervalAction
*/
class CC_DLL CCRepeatForever : public CCActionInterval
{
public:
/**
* @js ctor
*/
CCRepeatForever()
: m_pInnerAction(NULL)
{}
/**
* @js NA
* @lua NA
*/
virtual ~CCRepeatForever();
/** initializes the action */
bool initWithAction(CCActionInterval *pAction);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone *pZone);
virtual void startWithTarget(CCNode* pTarget);
virtual void step(float dt);
virtual void stop(void);
virtual bool isDone(void);
virtual CCActionInterval* reverse(void);
inline void setInnerAction(CCActionInterval *pAction)
{
if (m_pInnerAction != pAction)
{
CC_SAFE_RELEASE(m_pInnerAction);
m_pInnerAction = pAction;
CC_SAFE_RETAIN(m_pInnerAction);
}
}
inline CCActionInterval* getInnerAction()
{
return m_pInnerAction;
}
public:
/** creates the action */
static CCRepeatForever* create(CCActionInterval *pAction);
protected:
/** Inner action */
CCActionInterval *m_pInnerAction;
};
/** @brief Spawn a new action immediately
*/
class CC_DLL CCSpawn : public CCActionInterval
{
private:
/** helper constructor to create an array of spawned actions
* @js NA
* @lua NA
*/
static CCSpawn* createWithVariableList(CCFiniteTimeAction *pAction1, va_list args);
public:
/**
* @js NA
* @lua NA
*/
~CCSpawn(void);
/** initializes the Spawn action with the 2 actions to spawn
* @lua NA
*/
bool initWithTwoActions(CCFiniteTimeAction *pAction1, CCFiniteTimeAction *pAction2);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
/**
* @lua NA
*/
virtual void startWithTarget(CCNode *pTarget);
/**
* @lua NA
*/
virtual void stop(void);
/**
* @lua NA
*/
virtual void update(float time);
virtual CCActionInterval* reverse(void);
public:
/** helper constructor to create an array of spawned actions
* @lua NA
*/
static CCSpawn* create(CCFiniteTimeAction *pAction1, ...);
/** helper constructor to create an array of spawned actions given an array
* @js NA
*/
static CCSpawn* create(CCArray *arrayOfActions);
/** creates the Spawn action
* @js NA
*/
static CCSpawn* createWithTwoActions(CCFiniteTimeAction *pAction1, CCFiniteTimeAction *pAction2);
protected:
CCFiniteTimeAction *m_pOne;
CCFiniteTimeAction *m_pTwo;
};
/** @brief Rotates a CCNode object to a certain angle by modifying it's
rotation attribute.
The direction will be decided by the shortest angle.
*/
class CC_DLL CCRotateTo : public CCActionInterval
{
public:
/** creates the action */
static CCRotateTo* create(float fDuration, float fDeltaAngle);
/** initializes the action */
bool initWithDuration(float fDuration, float fDeltaAngle);
/** creates the action with separate rotation angles */
static CCRotateTo* create(float fDuration, float fDeltaAngleX, float fDeltaAngleY);
virtual bool initWithDuration(float fDuration, float fDeltaAngleX, float fDeltaAngleY);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget);
virtual void update(float time);
protected:
float m_fDstAngleX;
float m_fStartAngleX;
float m_fDiffAngleX;
float m_fDstAngleY;
float m_fStartAngleY;
float m_fDiffAngleY;
};
/** @brief Rotates a CCNode object clockwise a number of degrees by modifying it's rotation attribute.
*/
class CC_DLL CCRotateBy : public CCActionInterval
{
public:
/** creates the action */
static CCRotateBy* create(float fDuration, float fDeltaAngle);
/** initializes the action */
bool initWithDuration(float fDuration, float fDeltaAngle);
static CCRotateBy* create(float fDuration, float fDeltaAngleX, float fDeltaAngleY);
bool initWithDuration(float fDuration, float fDeltaAngleX, float fDeltaAngleY);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget);
virtual void update(float time);
virtual CCActionInterval* reverse(void);
protected:
float m_fAngleX;
float m_fStartAngleX;
float m_fAngleY;
float m_fStartAngleY;
};
/** Moves a CCNode object x,y pixels by modifying it's position attribute.
x and y are relative to the position of the object.
Several CCMoveBy actions can be concurrently called, and the resulting
movement will be the sum of individual movements.
@since v2.1beta2-custom
*/
class CC_DLL CCMoveBy : public CCActionInterval
{
public:
/** initializes the action */
bool initWithDuration(float duration, const CCPoint& deltaPosition, bool autoHeadOn, float initAngle);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget);
virtual CCActionInterval* reverse(void);
virtual void update(float time);
public:
/** creates the action */
static CCMoveBy* create(float duration, const CCPoint& deltaPosition, bool autoHeadOn = false, float initAngle = 0);
protected:
CCPoint m_positionDelta;
CCPoint m_startPosition;
CCPoint m_previousPosition;
bool m_autoHeadOn;
float m_initAngle;
};
/** Moves a CCNode object to the position x,y. x and y are absolute coordinates by modifying it's position attribute.
Several CCMoveTo actions can be concurrently called, and the resulting
movement will be the sum of individual movements.
@since v2.1beta2-custom
*/
class CC_DLL CCMoveTo : public CCMoveBy
{
public:
/** initializes the action */
bool initWithDuration(float duration, const CCPoint& position, bool autoHeadOn, float initAngle);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget);
public:
/** creates the action */
static CCMoveTo* create(float duration, const CCPoint& position, bool autoHeadOn = false, float initAngle = 0);
protected:
CCPoint m_endPosition;
};
/** Skews a CCNode object to given angles by modifying it's skewX and skewY attributes
@since v1.0
*/
class CC_DLL CCSkewTo : public CCActionInterval
{
public:
/**
* @js ctor
*/
CCSkewTo();
virtual bool initWithDuration(float t, float sx, float sy);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget);
virtual void update(float time);
public:
/** creates the action */
static CCSkewTo* create(float t, float sx, float sy);
protected:
float m_fSkewX;
float m_fSkewY;
float m_fStartSkewX;
float m_fStartSkewY;
float m_fEndSkewX;
float m_fEndSkewY;
float m_fDeltaX;
float m_fDeltaY;
};
/** Skews a CCNode object by skewX and skewY degrees
@since v1.0
*/
class CC_DLL CCSkewBy : public CCSkewTo
{
public:
virtual bool initWithDuration(float t, float sx, float sy);
virtual void startWithTarget(CCNode *pTarget);
virtual CCActionInterval* reverse(void);
public:
/** creates the action */
static CCSkewBy* create(float t, float deltaSkewX, float deltaSkewY);
};
/** @brief Moves a CCNode object simulating a parabolic jump movement by modifying it's position attribute.
*/
class CC_DLL CCJumpBy : public CCActionInterval
{
public:
/** initializes the action */
bool initWithDuration(float duration, const CCPoint& position, float height, unsigned int jumps, bool autoHeadOn, float initAngle);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget);
virtual void update(float time);
virtual CCActionInterval* reverse(void);
public:
/** creates the action */
static CCJumpBy* create(float duration, const CCPoint& position, float height, unsigned int jumps, bool autoHeadOn = false, float initAngle = 0);
protected:
CCPoint m_startPosition;
CCPoint m_delta;
float m_height;
unsigned int m_nJumps;
CCPoint m_previousPos;
bool m_autoHeadOn;
float m_initAngle;
};
/** @brief Moves a CCNode object to a parabolic position simulating a jump movement by modifying it's position attribute.
*/
class CC_DLL CCJumpTo : public CCJumpBy
{
public:
virtual void startWithTarget(CCNode *pTarget);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
public:
/** creates the action */
static CCJumpTo* create(float duration, const CCPoint& position, float height, int jumps, bool autoHeadOn = false, float initAngle = 0);
};
/** @typedef bezier configuration structure
*/
typedef struct _ccBezierConfig {
//! end position of the bezier
CCPoint endPosition;
//! Bezier control point 1
CCPoint controlPoint_1;
//! Bezier control point 2
CCPoint controlPoint_2;
} ccBezierConfig;
/** @brief An action that moves the target with a cubic Bezier curve by a certain distance.
*/
class CC_DLL CCBezierBy : public CCActionInterval
{
public:
/** initializes the action with a duration and a bezier configuration
* @lua NA
*/
bool initWithDuration(float t, const ccBezierConfig& c);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
/**
* @lua NA
*/
virtual void startWithTarget(CCNode *pTarget);
/**
* @lua NA
*/
virtual void update(float time);
virtual CCActionInterval* reverse(void);
public:
/** creates the action with a duration and a bezier configuration
* @code
* when this function bound to js,the input params are changed
* js: var create(var t, var pointTable)
* @endcode
*/
static CCBezierBy* create(float t, const ccBezierConfig& c);
protected:
ccBezierConfig m_sConfig;
CCPoint m_startPosition;
CCPoint m_previousPosition;
};
/** @brief An action that moves the target with a cubic Bezier curve to a destination point.
@since v0.8.2
*/
class CC_DLL CCBezierTo : public CCBezierBy
{
public:
/**
* @lua NA
*/
virtual void startWithTarget(CCNode *pTarget);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
public:
/** creates the action with a duration and a bezier configuration
* @code
* when this function bound to js,the input params are changed
* js: var create(var t, var pointTable)
* @endcode
*/
static CCBezierTo* create(float t, const ccBezierConfig& c);
/**
* @lua NA
*/
bool initWithDuration(float t, const ccBezierConfig &c);
protected:
ccBezierConfig m_sToConfig;
};
/** @brief Scales a CCNode object to a zoom factor by modifying it's scale attribute.
@warning This action doesn't support "reverse"
*/
class CC_DLL CCScaleTo : public CCActionInterval
{
public:
/** initializes the action with the same scale factor for X and Y */
bool initWithDuration(float duration, float s);
/** initializes the action with and X factor and a Y factor */
bool initWithDuration(float duration, float sx, float sy);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget);
virtual void update(float time);
public:
/** creates the action with the same scale factor for X and Y */
static CCScaleTo* create(float duration, float s);
/** creates the action with and X factor and a Y factor */
static CCScaleTo* create(float duration, float sx, float sy);
protected:
float m_fScaleX;
float m_fScaleY;
float m_fStartScaleX;
float m_fStartScaleY;
float m_fEndScaleX;
float m_fEndScaleY;
float m_fDeltaX;
float m_fDeltaY;
};
/** @brief Scales a CCNode object a zoom factor by modifying it's scale attribute.
*/
class CC_DLL CCScaleBy : public CCScaleTo
{
public:
virtual void startWithTarget(CCNode *pTarget);
virtual CCActionInterval* reverse(void);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
public:
/** creates the action with the same scale factor for X and Y */
static CCScaleBy* create(float duration, float s);
/** creates the action with and X factor and a Y factor */
static CCScaleBy* create(float duration, float sx, float sy);
};
/** @brief Blinks a CCNode object by modifying it's visible attribute
*/
class CC_DLL CCBlink : public CCActionInterval
{
public:
/** initializes the action */
bool initWithDuration(float duration, unsigned int uBlinks);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void update(float time);
virtual CCActionInterval* reverse(void);
public:
/** creates the action */
static CCBlink* create(float duration, unsigned int uBlinks);
virtual void startWithTarget(CCNode *pTarget);
virtual void stop();
protected:
unsigned int m_nTimes;
bool m_bOriginalState;
};
/** @brief Fades In an object that implements the CCRGBAProtocol protocol. It modifies the opacity from 0 to 255.
The "reverse" of this action is FadeOut
*/
class CC_DLL CCFadeIn : public CCActionInterval
{
public:
virtual void update(float time);
virtual CCActionInterval* reverse(void);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
public:
/** creates the action */
static CCFadeIn* create(float d);
};
/** @brief Fades Out an object that implements the CCRGBAProtocol protocol. It modifies the opacity from 255 to 0.
The "reverse" of this action is FadeIn
*/
class CC_DLL CCFadeOut : public CCActionInterval
{
public:
virtual void update(float time);
virtual CCActionInterval* reverse(void);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
public:
/** creates the action */
static CCFadeOut* create(float d);
};
/** @brief Fades an object that implements the CCRGBAProtocol protocol. It modifies the opacity from the current value to a custom one.
@warning This action doesn't support "reverse"
*/
class CC_DLL CCFadeTo : public CCActionInterval
{
public:
/** initializes the action with duration and opacity */
bool initWithDuration(float duration, GLubyte opacity);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget);
virtual void update(float time);
public:
/** creates an action with duration and opacity */
static CCFadeTo* create(float duration, GLubyte opacity);
protected:
GLubyte m_toOpacity;
GLubyte m_fromOpacity;
};
/** @brief Tints a CCNode that implements the CCNodeRGB protocol from current tint to a custom one.
@warning This action doesn't support "reverse"
@since v0.7.2
*/
class CC_DLL CCTintTo : public CCActionInterval
{
public:
/** initializes the action with duration and color */
bool initWithDuration(float duration, GLubyte red, GLubyte green, GLubyte blue);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget);
virtual void update(float time);
public:
/** creates an action with duration and color */
static CCTintTo* create(float duration, GLubyte red, GLubyte green, GLubyte blue);
protected:
ccColor3B m_to;
ccColor3B m_from;
};
/** @brief Tints a CCNode that implements the CCNodeRGB protocol from current tint to a custom one.
@since v0.7.2
*/
class CC_DLL CCTintBy : public CCActionInterval
{
public:
/** initializes the action with duration and color */
bool initWithDuration(float duration, GLshort deltaRed, GLshort deltaGreen, GLshort deltaBlue);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget);
virtual void update(float time);
virtual CCActionInterval* reverse(void);
public:
/** creates an action with duration and color */
static CCTintBy* create(float duration, GLshort deltaRed, GLshort deltaGreen, GLshort deltaBlue);
protected:
GLshort m_deltaR;
GLshort m_deltaG;
GLshort m_deltaB;
GLshort m_fromR;
GLshort m_fromG;
GLshort m_fromB;
};
/** @brief Delays the action a certain amount of seconds
*/
class CC_DLL CCDelayTime : public CCActionInterval
{
public:
virtual void update(float time);
virtual CCActionInterval* reverse(void);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
public:
/** creates the action */
static CCDelayTime* create(float d);
};
/** @brief Executes an action in reverse order, from time=duration to time=0
@warning Use this action carefully. This action is not
sequenceable. Use it as the default "reversed" method
of your own actions, but using it outside the "reversed"
scope is not recommended.
*/
class CC_DLL CCReverseTime : public CCActionInterval
{
public:
/**
* @js ctor
*/
~CCReverseTime(void);
/**
* @js NA
* @lua NA
*/
CCReverseTime();
/** initializes the action */
bool initWithAction(CCFiniteTimeAction *pAction);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget);
virtual void stop(void);
virtual void update(float time);
virtual CCActionInterval* reverse(void);
public:
/** creates the action */
static CCReverseTime* create(CCFiniteTimeAction *pAction);
protected:
CCFiniteTimeAction *m_pOther;
};
class CCTexture2D;
/** @brief Animates a sprite given the name of an Animation */
class CC_DLL CCAnimate : public CCActionInterval
{
public:
/**
* @js ctor
*/
CCAnimate();
/**
* @js NA
* @lua NA
*/
~CCAnimate();
/** initializes the action with an Animation and will restore the original frame when the animation is over */
bool initWithAnimation(CCAnimation *pAnimation);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget);
virtual void stop(void);
virtual void update(float t);
virtual CCActionInterval* reverse(void);
public:
/** creates the action with an Animation and will restore the original frame when the animation is over */
static CCAnimate* create(CCAnimation *pAnimation);
CC_SYNTHESIZE_RETAIN(CCAnimation*, m_pAnimation, Animation)
protected:
std::vector<float>* m_pSplitTimes;
int m_nNextFrame;
CCSpriteFrame* m_pOrigFrame;
unsigned int m_uExecutedLoops;
bool m_isNinePatch;
};
/** Overrides the target of an action so that it always runs on the target
* specified at action creation rather than the one specified by runAction.
*/
class CC_DLL CCTargetedAction : public CCActionInterval
{
public:
/**
* @js ctor
*/
CCTargetedAction();
/**
* @js NA
* @lua NA
*/
virtual ~CCTargetedAction();
/** Create an action with the specified action and forced target */
static CCTargetedAction* create(CCNode* pTarget, CCFiniteTimeAction* pAction);
/** Init an action with the specified action and forced target */
bool initWithTarget(CCNode* pTarget, CCFiniteTimeAction* pAction);
/**
* @js NA
* @lua NA
*/
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget);
virtual void stop(void);
virtual void update(float time);
/** This is the target that the action will be forced to run with */
CC_SYNTHESIZE_RETAIN(CCNode*, m_pForcedTarget, ForcedTarget);
private:
CCFiniteTimeAction* m_pAction;
};
// end of actions group
/// @}
NS_CC_END
#endif //__ACTION_CCINTERVAL_ACTION_H__
| 412 | 0.906487 | 1 | 0.906487 | game-dev | MEDIA | 0.95263 | game-dev | 0.608277 | 1 | 0.608277 |
mattgodbolt/reddog | 1,702 | dreamcast/reddog/game/strats/env_fxrain.dst | // Controls the rain and snow, actually
// Starts raining after activation 0, if it has one
// Stops on activation 1
PARAMINT AmountOutside 1000
PARAMINT AmountInside 0
PARAMINT Snow 0
LOCALINT Amount1
LOCALINT Amount2
LOCALINT RAINSET
LOCALFLOAT VOLUME
TRIGGER RAINEFFECT
VOLUME = RandRange(0.5, 0.6)
SetVolume(0, VOLUME)
TRIGSTOP
ENDTRIGGER
STATE Init
MyFlag = MyFlag | NODISP
IF (HasActivation(0))
WHILE (!PlayerNearActivation(0))
MyFlag = MyFlag
ENDWHILE
ENDIF
// AllocStratSoundBlock(2)
// SetAudibleRange(100, 1000)
// PLAYSOUND>RAINL 0 0.8 0.0 0.0 0.0 (HARDLEFT | CONTINUOUS)
// PLAYSOUND>RAINR 0 0.8 0.0 0.0 0.0 (HARDRIGHT | CONTINUOUS)
IF (MyFlag2 & OWNIPARAMS)
// SetRainAmount (AmountOutside, AmountInside, Snow)
ELSE
AmountOutside = 1000
AmountInside = 0
Snow = 0
// SetRainAmount(1000, 0, 0)
ENDIF
WHILE ((Amount1 < AmountOutside) OR (Amount2 < AmountInside))
IF (Amount1 < AmountOutside)
Amount1 = Amount1 + RandRange(0,30.0)
ENDIF
IF (Amount2 < AmountInside)
Amount2 = Amount2 + RandRange(0,30.0)
ENDIF
IF ((!RAINSET) AND (!Snow))
AllocStratSoundBlock(1)
RAINSET = 1
PLAYSOUND>RAINL 0 0.55 0.0 0.0 0.0 CONTINUOUS | NOPOSITION
TRIGSET>RAINEFFECT EVERY 10
//TRIGSET>
ENDIF
SetRainAmount (Amount1, Amount2, Snow)
frame = RandRange(0,50.0)
LOOP (frame)
MyFlag = MyFlag
ENDLOOP
ENDWHILE
IF (HasActivation(1))
WHILE (!PlayerNearActivation(1))
MyFlag = MyFlag
// Need to check whether we are inside or outside
ENDWHILE
SetRainAmount(0,0,0)
IF (RAINSET)
StopSound(0,0)
RAINSET = 0
TRIGKILL>RAINEFFECT EVERY 10
ENDIF
// StopSound(1)
ELSE
Delete()
ENDIF
ENDSTATE
| 412 | 0.685597 | 1 | 0.685597 | game-dev | MEDIA | 0.726235 | game-dev | 0.965134 | 1 | 0.965134 |
3arthh4ckDevelopment/3arthh4ck-Fabric | 2,013 | src/main/java/me/earth/earthhack/impl/modules/player/autotool/ListenerDamageBlock.java | package me.earth.earthhack.impl.modules.player.autotool;
import me.earth.earthhack.api.cache.ModuleCache;
import me.earth.earthhack.impl.event.events.misc.DamageBlockEvent;
import me.earth.earthhack.impl.event.listeners.ModuleListener;
import me.earth.earthhack.impl.modules.Caches;
import me.earth.earthhack.impl.modules.player.speedmine.Speedmine;
import me.earth.earthhack.impl.modules.player.speedmine.mode.MineMode;
import me.earth.earthhack.impl.util.minecraft.InventoryUtil;
import me.earth.earthhack.impl.util.minecraft.blocks.mine.MineUtil;
import me.earth.earthhack.impl.util.thread.Locks;
final class ListenerDamageBlock extends
ModuleListener<AutoTool, DamageBlockEvent>
{
private static final ModuleCache<Speedmine> SPEED_MINE =
Caches.getModule(Speedmine.class);
public ListenerDamageBlock(AutoTool module)
{
super(module, DamageBlockEvent.class);
}
@Override
public void invoke(DamageBlockEvent event)
{
if (MineUtil.canBreak(event.getPos())
&& !mc.player.isCreative()
&& mc.options.attackKey.isPressed()
&& (!SPEED_MINE.isPresent()
|| !SPEED_MINE.isEnabled()
|| (SPEED_MINE.get().getMode() == MineMode.Damage
|| SPEED_MINE.get().getMode() == MineMode.Reset)))
{
int slot = MineUtil.findBestTool(event.getPos());
if (slot != -1)
{
if (!module.set)
{
module.lastSlot = mc.player.getInventory().selectedSlot;
module.set = true;
}
Locks.acquire(Locks.PLACE_SWITCH_LOCK,
() -> InventoryUtil.switchTo(slot));
}
}
else if (module.set)
{
Locks.acquire(Locks.PLACE_SWITCH_LOCK,
() -> InventoryUtil.switchTo(module.lastSlot));
module.reset();
}
}
}
| 412 | 0.830825 | 1 | 0.830825 | game-dev | MEDIA | 0.97164 | game-dev | 0.864887 | 1 | 0.864887 |
layabox/LayaAir-v1 | 1,162 | plugins/debugtool/src/laya/debug/tools/comps/AutoSizeRec.as | package laya.debug.tools.comps
{
import laya.display.Graphics;
import laya.display.Sprite;
/**
* ...
* @author ww
*/
public class AutoSizeRec extends Sprite
{
public var type:int;
public function AutoSizeRec(type:String)
{
}
override public function set height(value:Number):void
{
// TODO Auto Generated method stub
super.height = value;
changeSize();
}
override public function set width(value:Number):void
{
// TODO Auto Generated method stub
super.width = value;
changeSize();
}
private var _color:String = "#ffffff";
public function setColor(color:String):void
{
_color = color;
reRender();
}
protected function changeSize():void
{
// TODO Auto Generated method stub
reRender();
}
private function reRender():void
{
var g:Graphics = graphics;
g.clear();
g.drawRect(0, 0, width, height, _color);
}
public var preX:Number;
public var preY:Number;
public function record():void
{
preX = x;
preY = y;
}
public function getDx():Number
{
return x - preX;
}
public function getDy():Number
{
return y - preY;
}
}
} | 412 | 0.76447 | 1 | 0.76447 | game-dev | MEDIA | 0.601434 | game-dev,graphics-rendering | 0.9716 | 1 | 0.9716 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.