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
fmzquant/strategies
4,063
Mobo-Bands.md
> Name Mobo-Bands > Author ChaoZhang > Strategy Description This indicator is the Mobo Bands (Momentum Breakout Bands). These bands are bollinger bands that have an adjusted standard deviation. There are Buy signals when it has momentum breakouts above the bands for moves to the upside and Sell signals when it has momentum breakouts below the bands for moves to the downside. The bands simply suggest that all markets have periods of chop which we all know to be true. While the price is inside the bands it is said to be trendless. Once the breakouts happen you can take trades in the breakout direction. I like to use these to swing trade options on the hourly timeframe but the bands should work on most instruments and timeframes. I like to use it to take swings on SPY on the 1 hour chart for entries and use the Daily chart for trend confirmation. **backtest** ![IMG](https://www.fmz.com/upload/asset/1f2ff4b7c1c03df68cb.png) > Strategy Arguments |Argument|Default|Description| |----|----|----| |v_input_1_hl2|0|Price: hl2|high|low|open|close|hlc3|hlcc4|ohlc4| |v_input_2|3|colorNormLength| |v_input_3|13|dpoLength| |v_input_4|false|moboDisplace| |v_input_5|10|moboLength| |v_input_6|-0.8|numDevDn| |v_input_7|0.8|numDevUp| |v_input_8|true|coloredMobo| |v_input_9|true|coloredFill| |v_input_10|true|breakArrows| |v_input_11|true|moboShowMid| > Source (PineScript) ``` pinescript /*backtest start: 2022-04-12 00:00:00 end: 2022-05-11 23:59:00 period: 1h basePeriod: 15m exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}] */ //@version=4 study("Mobo Bands", overlay=false) price = input(hl2, "Price") colorNormLength = input(3, "colorNormLength", input.integer) dpoLength = input(13, "dpoLength", input.integer) moboDisplace = input(0, "moboDisplace", input.integer) moboLength = input(10, "moboLength", input.integer) numDevDn = input(-0.8, "numDevDn", input.float) numDevUp = input(0.8, "numDevUp", input.float) coloredMobo = input(true, "coloredMobo") coloredFill = input(true, "coloredFill") breakArrows = input(true, "breakArrows") moboShowMid = input(true, "moboShowMid") //def DPO = price - Average(price[DPO_length / 2 + 1], DPO_length); xsma = sma(price[int(dpoLength / 2 + 1)], dpoLength) //alert(int(dpoLength / 2 + 1)) //xsma = sma(price, dpoLength) DPO = price - xsma Midline = sma(DPO, moboLength) sDev = stdev(DPO, moboLength) LowerBand = Midline + numDevDn * sDev UpperBand = Midline + numDevUp * sDev plot(DPO, color=color.yellow,linewidth=2) plot(Midline, color=Midline > Midline[1] ? color.lime : color.red,linewidth=2) Upper = plot(UpperBand, color=color.black,linewidth=1) Lower = plot(LowerBand, color=color.black,linewidth=1) plot(0, color=color.white,linewidth=1) Signal1 = DPO > UpperBand and DPO[1] < UpperBand[1] Signal2 = DPO < LowerBand and DPO[1] > LowerBand[1] wasUp = 1 wasDn = 1 wasUp := Signal1 ? 1 : (Signal2 ? 0 : nz(wasUp[1])) wasDn := Signal2 ? 1 : (Signal1 ? 0 : nz(wasDn[1])) //plotshape(Signal1 and wasDn[1] ? UpperBand : na, style=shape.arrowup, location=location.absolute, size=size.normal, color=color.red) //plotshape(Signal2 and wasUp[1] ? LowerBand : na, style=shape.arrowdown, location=location.absolute, size=size.normal, color=color.green) plotshape(Signal1 and wasDn[1] ? UpperBand : na, style=shape.labelup, location=location.absolute, size=size.normal, color=color.green, text="Buy",textcolor=color.white) plotshape(Signal2 and wasUp[1] ? LowerBand : na, style=shape.labeldown, location=location.absolute, size=size.normal, color=color.red, text="Sell",textcolor=color.white) //fill(Upper, Lower, color=color.purple) alertcondition(Signal1 and wasDn[1], "Break Out Arrow", "Break Out Arrow") alertcondition(Signal2 and wasUp[1], "Break Down Arrow", "Break Down Arrow") if Signal1 and wasDn[1] strategy.entry("Enter Long", strategy.long) else if Signal2 and wasUp[1] strategy.entry("Enter Short", strategy.short) ``` > Detail https://www.fmz.com/strategy/362868 > Last Modified 2022-05-13 14:36:34
1
0.821266
1
0.821266
game-dev
MEDIA
0.796413
game-dev
0.746646
1
0.746646
ohrrpgce/ohrrpgce
29,790
formationedit.bas
'OHRRPGCE CUSTOM - Enemy/Hero Formation/Formation Set Editors '(C) Copyright 1997-2020 James Paige, Ralph Versteegen, and the OHRRPGCE Developers 'Dual licensed under the GNU GPL v2+ and MIT Licenses. Read LICENSE.txt for terms and disclaimer of liability. #include "config.bi" #include "const.bi" #include "udts.bi" #include "custom.bi" #include "allmodex.bi" #include "common.bi" #include "loading.bi" #include "customsubs.bi" #include "slices.bi" #include "thingbrowser.bi" #include "sliceedit.bi" #include "bcommon.bi" 'Local SUBs DECLARE SUB formation_editor_main () DECLARE SUB draw_formation_slices OVERLOAD (eform as Formation, rootslice as Slice ptr, selected_slot as integer, page as integer) DECLARE SUB draw_formation_slices OVERLOAD (eform as Formation, hform as HeroFormation, rootslice as Slice ptr, selected_slot as integer, page as integer, byval heromode as bool=NO) DECLARE SUB update_formation_background(form as Formation, rootslice as Slice ptr, byref bgctr as integer, byref bgwait as integer) DECLARE SUB load_formation_slices(ename() as string, form as Formation, rootslice as Slice ptr ptr) DECLARE SUB hero_formation_editor () DECLARE SUB formation_init_added_enemy(byref slot as FormationSlot) DECLARE SUB formation_set_editor_load_preview(state as MenuState, form_id as integer, formset as FormationSet, form as Formation, ename() as string, byref rootslice as Slice Ptr) ' Formation editor slice lookup codes CONST SL_FORMEDITOR_BACKDROP = 100 CONST SL_FORMEDITOR_BATTLEFIELD = 101 CONST SL_FORMEDITOR_ENEMY = 200 '+0 to +7 for 8 slots CONST SL_FORMEDITOR_LAST_ENEMY = 299 'End of range indicating an enemy slot CONST SL_FORMEDITOR_CURSOR = 300 CONST SL_FORMEDITOR_HERO = 400 '+0 to +3 for 4 slots 'What hero sprites to use as placeholders, or -1 for a rectangle DIM SHARED hero_placeholder_sprites(3) as integer = {-1, -1, -1, -1} '========================================================================================== ' Formation Previewer '========================================================================================== 'Preview a hero or enemy formation. Select which by setting heromode. TYPE FormationPreviewer EXTENDS RecordPreviewer heromode as bool 'True if previewing hero rather than enemy formations eform as Formation hform as HeroFormation rootslice as Slice ptr DECLARE DESTRUCTOR() DECLARE SUB update(form_id as integer, force_reload as bool = NO) DECLARE SUB draw(xpos as RelPos, ypos as RelPos, page as integer) END TYPE DESTRUCTOR FormationPreviewer DeleteSlice @rootslice END DESTRUCTOR SUB FormationPreviewer.update(form_id as integer, force_reload as bool = NO) IF heromode THEN eform.background = -1 'Show just a rect load_hero_formation hform, form_id ELSE LoadFormation eform, form_id load_hero_formation hform, eform.hero_form END IF DIM ename(7) as string 'Unused load_formation_slices ename(), eform, @rootslice END SUB SUB FormationPreviewer.draw(xpos as RelPos, ypos as RelPos, page as integer) draw_formation_slices eform, hform, rootslice, -1, page, heromode END SUB '========================================================================================== ' Top-level formation editor menu '========================================================================================== SUB formation_editor_main () IF read_config_bool("thingbrowser.enable_top_level", YES) THEN DIM b as FormationBrowser b.browse(-1, , @individual_formation_editor) ELSE individual_formation_editor 0 END IF END SUB FUNCTION formation_picker (recindex as integer = -1) as integer DIM b as FormationBrowser RETURN b.browse(recindex, , @individual_formation_editor, NO) END FUNCTION FUNCTION formation_picker_or_none (recindex as integer = -1) as integer DIM b as FormationBrowser RETURN b.browse(recindex - 1, YES , @individual_formation_editor, NO) + 1 END FUNCTION 'Total-level menu SUB formation_editor DIM menu(3) as string menu(0) = "Return to Main Menu" menu(1) = "Edit Individual Enemy Formations..." menu(2) = "Construct Formation Sets..." menu(3) = "Edit Hero Formations..." DIM state as MenuState state.last = UBOUND(menu) setkeys DO setwait 55 setkeys IF keyval(ccCancel) > 1 THEN EXIT DO IF keyval(scF1) > 1 THEN show_help "formation_main" usemenu state IF enter_space_click(state) THEN IF state.pt = 0 THEN EXIT DO IF state.pt = 1 THEN formation_editor_main IF state.pt = 2 THEN formation_set_editor IF state.pt = 3 THEN hero_formation_editor END IF clearpage dpage standardmenu menu(), state, , , dpage SWAP vpage, dpage setvispage vpage dowait LOOP END SUB '========================================================================================== ' Formation Set Editor '========================================================================================== 'set_id: which formation set to show. If -1, same as last time. 'Returns the formation set number we were last editing. FUNCTION formation_set_editor (set_id as integer = -1) as integer STATIC remember_set_id as integer = 1 IF set_id <= 0 THEN set_id = remember_set_id ELSE set_id = bound(set_id, 1, maxFormationSet) END IF DIM form as Formation DIM formset as FormationSet DIM form_id as integer DIM menu(23) as string DIM rootslice as Slice ptr DIM state as MenuState state.last = UBOUND(menu) state.autosize = YES state.autosize_ignore_pixels = 20 state.need_update = YES DIM menuopts as MenuOptions menuopts.edged = YES LoadFormationSet formset, set_id setkeys DO setwait 55 setkeys IF keyval(ccCancel) > 1 THEN SaveFormationSet formset, set_id EXIT DO END IF IF keyval(scF1) > 1 THEN show_help "formation_sets" state.need_update OR= usemenu(state) IF enter_space_click(state) THEN IF state.pt = 0 THEN SaveFormationSet formset, set_id EXIT DO END IF END IF IF state.pt = 1 THEN DIM remember_id as integer = set_id IF intgrabber(set_id, 1, maxFormationSet) THEN SaveFormationSet formset, remember_id LoadFormationSet formset, set_id state.need_update = YES END IF END IF IF state.pt = 2 THEN intgrabber formset.frequency, 0, 200 IF state.pt = 3 THEN tag_grabber formset.tag, state IF state.pt >= 4 THEN '--have form selected '-1 is None state.need_update OR= formationgrabber(formset.formations(state.pt - 4), state, 0, -1) form_id = formset.formations(state.pt - 4) ELSE form_id = -1 END IF IF state.need_update THEN state.need_update = NO formation_set_editor_load_preview state, form_id, formset, form, menu(), rootslice END IF IF rootslice THEN draw_formation_slices form, rootslice, -1, dpage ELSE clearpage dpage END IF IF state.pt >= 4 THEN edgeprint THINGGRABBER_TOOLTIP, pInfoX, pInfoY, uilook(uiMenuItem), dpage END IF menu(0) = "Previous Menu" menu(1) = CHR(27) & "Formation Set " & set_id & CHR(26) menu(2) = "Battle Frequency: " & formset.frequency & " (" & formset_step_estimate(formset.frequency, " steps") & ")" menu(3) = tag_condition_caption(formset.tag, "Only if tag", "No tag check") standardmenu menu(), state, , , dpage, menuopts SWAP vpage, dpage setvispage vpage dowait LOOP DeleteSlice @rootslice remember_set_id = set_id RETURN set_id END FUNCTION SUB formation_set_editor_load_preview(state as MenuState, form_id as integer, formset as FormationSet, form as Formation, menu() as string, byref rootslice as slice Ptr) IF form_id >= 0 THEN '--form not empty LoadFormation form, form_id DIM as string ename(7) 'not used here, but that is okay load_formation_slices ename(), form, @rootslice ELSE DeleteSlice @rootslice END IF 'Also reload the formation descriptions for the menu DIM each_form as Formation FOR i as integer = 0 TO UBOUND(formset.formations) IF formset.formations(i) = -1 THEN menu(4 + i) = "Empty" ELSE LoadFormation each_form, game & ".for", formset.formations(i) menu(4 + i) = "Form " & formset.formations(i) & " " & describe_formation(each_form) END IF NEXT i END SUB '========================================================================================== ' Hero Formation Editor '========================================================================================== 'Prompt user how to add a new formation and update hero_form_id and return true, 'or return false if cancelled. FUNCTION hero_formation_add_new(byref hero_form_id as integer) as bool BUG_IF(hero_form_id <> last_hero_formation_id() + 1, "Bad call", NO) DIM how as integer DIM previewer as FormationPreviewer previewer.heromode = YES how = generic_add_new("hero formation", last_hero_formation_id(), , @previewer, "add_hero_formation_how") '-- -2 =Cancel '-- -1 =New blank '-- >=0 =Copy DIM hform as HeroFormation IF how = -2 THEN RETURN NO ELSEIF how = -1 THEN default_hero_formation hform save_hero_formation hform, hero_form_id ELSEIF how >= 0 THEN load_hero_formation hform, how save_hero_formation hform, hero_form_id ELSE hero_form_id = last_hero_formation_id() END IF RETURN YES END FUNCTION SUB hero_formation_editor () DIM hero_form_id as integer = 0 DIM test_form_id as integer = 0 DIM ename(7) as string DIM eform as Formation DIM hform as HeroFormation DIM default_hform as HeroFormation DIM rootslice as Slice ptr DIM positioning_mode as bool = NO DIM as integer bgwait, bgctr LoadFormation eform, test_form_id load_formation_slices ename(), eform, @rootslice DIM menu(6) as string DIM state as MenuState state.pt = 0 state.top = 0 state.first = 0 state.last = UBOUND(menu) state.size = 20 DIM menuopts as MenuOptions menuopts.edged = YES CONST first_hero_item = 3 'slot -1 indicates no hero selected DIM slot as integer = state.pt - first_hero_item IF slot < 0 THEN slot = -1 default_hero_formation default_hform load_hero_formation hform, hero_form_id setkeys DO setwait 55 setkeys IF positioning_mode = YES THEN '--hero positioning mode IF keyval(ccCancel) > 1 OR enter_or_space() THEN setkeys: positioning_mode = NO IF readmouse.release AND mouseRight THEN setkeys: positioning_mode = NO IF keyval(scF1) > 1 THEN show_help "hero_formation_editor_placement" DIM as integer thiswidth = 0, thisheight = 0, movespeed = 1 IF keyval(scShift) THEN movespeed = 8 WITH hform.slots(slot) DIM hrect as Slice ptr = LookupSlice(SL_FORMEDITOR_HERO + slot, rootslice) IF hrect THEN thiswidth = hrect->Width thisheight = hrect->Height END IF IF keyval(ccUp) > 0 THEN .pos.y -= movespeed IF keyval(ccDown) > 0 THEN .pos.y += movespeed IF keyval(ccLeft) > 0 THEN .pos.x -= movespeed IF keyval(ccRight) > 0 THEN .pos.x += movespeed IF readmouse.dragging AND mouseLeft THEN .pos += (readmouse.pos - readmouse.lastpos) END IF 'Hero positions are the bottom center of the sprite. Very generous bounds. DIM bounds as RectPoints = get_formation_bounds() .pos = bound(.pos, bounds.topleft - HERO_FORM_OFFSET - 1000, bounds.bottomright - HERO_FORM_OFFSET + 1000) END WITH END IF IF positioning_mode = NO THEN '--menu mode IF keyval(ccCancel) > 1 THEN EXIT DO END IF IF keyval(scF1) > 1 THEN show_help "hero_formation_editor" usemenu state slot = state.pt - first_hero_item IF slot < 0 THEN slot = -1 IF enter_space_click(state) THEN IF state.pt = 0 THEN EXIT DO END IF IF slot <> -1 THEN 'a hero slot positioning_mode = YES END IF END IF IF state.pt = 2 THEN IF intgrabber(test_form_id, 0, gen(genMaxFormation)) THEN 'Test with a different enemy formation LoadFormation eform, test_form_id load_formation_slices ename(), eform, @rootslice bgwait = 0 bgctr = 0 END IF END IF IF state.pt = 1 THEN '---SELECT A DIFFERENT HERO FORMATION DIM as integer remember_id = hero_form_id IF intgrabber_with_addset(hero_form_id, 0, last_hero_formation_id(), 32767, "hero formation") THEN save_hero_formation hform, remember_id IF hero_form_id > last_hero_formation_id() THEN hero_formation_add_new hero_form_id load_hero_formation hform, hero_form_id save_hero_formation hform, hero_form_id 'Only needed when adding new END IF END IF IF slot <> -1 THEN IF intgrabber(hero_placeholder_sprites(slot), -1, gen(genMaxHeroPic)) THEN load_formation_slices ename(), eform, @rootslice END IF END IF END IF '--end positioning_mode=NO IF slot <> -1 THEN IF keyval(scCtrl) > 0 ANDALSO keyval(scD) > 1 THEN 'Revert to default hform.slots(slot).pos = default_hform.slots(slot).pos hero_placeholder_sprites(slot) = -1 END IF END IF ' Draw screen update_formation_background eform, rootslice, bgctr, bgwait draw_formation_slices eform, hform, rootslice, slot, dpage, YES IF positioning_mode THEN edgeprint "Arrow keys or mouse-drag", pMenuX, pMenuY, uilook(uiText), dpage edgeprint "ESC or right-click when done", pInfoX, pInfoY, uilook(uiText), dpage DIM pos as XYPair = hform.slots(slot).pos + HERO_FORM_OFFSET edgeprint "x=" & pos.x & " y=" & pos.y, pInfoRight, pMenuY, uilook(uiMenuItem), dpage ELSE menu(0) = "Previous Menu" menu(1) = CHR(27) + "Hero Formation " & hero_form_id & CHR(26) menu(2) = "Preview Enemy Formation: " & test_form_id FOR i as integer = 0 TO 3 DIM placeholder as string placeholder = IIF(hero_placeholder_sprites(i) = -1, "Rect", "Sprite " & hero_placeholder_sprites(i)) menu(first_hero_item + i) = "Hero Slot " & i & " " & CHR(27) & "Preview:" & placeholder & CHR(26) NEXT i standardmenu menu(), state, , , dpage, menuopts END IF IF slot <> -1 THEN edgeprint "CTRL+D to revert to default pos", 1, pBottom - IIF(positioning_mode, 10, 1), uilook(uiText), dpage END IF SWAP vpage, dpage setvispage vpage dowait LOOP save_hero_formation hform, hero_form_id DeleteSlice @rootslice END SUB '========================================================================================== ' Individual Formation editor '========================================================================================== 'Prompt user how to add a new formation, and update form_id and return true, 'or return false if cancelled. FUNCTION formation_add_new(byref form_id as integer) as bool BUG_IF(form_id <> gen(genMaxFormation) + 1, "Bad call", NO) DIM how as integer DIM previewer as FormationPreviewer previewer.heromode = NO how = generic_add_new("formation", gen(genMaxFormation), @describe_formation_by_id, @previewer, "add_formation_how") '-- -2 =Cancel '-- -1 =New blank '-- >=0 =Copy DIM form as Formation IF how = -2 THEN RETURN NO ELSEIF how = -1 THEN gen(genMaxFormation) += 1 ClearFormation form SaveFormation form, form_id ELSEIF how >= 0 THEN gen(genMaxFormation) += 1 LoadFormation form, how SaveFormation form, form_id END IF form_id = gen(genMaxFormation) RETURN YES END FUNCTION TYPE FormationEditor EXTENDS ModularMenu form_id as integer form as Formation slot as integer = -1 'Which formation slot selected, or -1 for none positioning_mode as bool 'Whether positioning an enemy (menu hidden) ename(7) as string 'Enemy names rootslice as Slice ptr bgwait as integer bgctr as integer remem_pt as integer 'Remember state.pt of top menu while in positioning_mode preview_music as bool last_music as integer = -1 DECLARE VIRTUAL SUB each_tick() DECLARE VIRTUAL FUNCTION try_exit() as bool DECLARE VIRTUAL SUB update() DECLARE VIRTUAL SUB draw_underlays() DECLARE SUB load_form() DECLARE SUB update_music() DECLARE SUB each_tick_menu_mode() DECLARE SUB each_tick_positioning_mode() END TYPE 'form_id: which formation to show. If -1, same as last time. If >= max, asks to add a new formation 'Returns the formation number we were last editing, or -1 if cancelled adding a new formation. FUNCTION individual_formation_editor (form_id as integer = -1) as integer STATIC remember_form_id as integer = 0 IF form_id < 0 THEN form_id = remember_form_id ELSEIF form_id > gen(genMaxFormation) THEN IF formation_add_new(form_id) = NO THEN RETURN -1 END IF DIM editor as FormationEditor editor.menuopts.edged = YES editor.preview_music = read_config_bool("formedit.preview_music", NO) editor.form_id = form_id editor.load_form() editor.run() form_id = editor.form_id SaveFormation editor.form, form_id music_stop DeleteSlice @editor.rootslice remember_form_id = form_id RETURN form_id END FUNCTION SUB FormationEditor.load_form() LoadFormation form, form_id load_formation_slices ename(), form, @rootslice bgwait = 0 bgctr = 0 update_music() END SUB FUNCTION FormationEditor.try_exit() as bool IF positioning_mode THEN positioning_mode = NO state.pt = remem_pt state.need_update = YES RETURN NO END IF RETURN YES END FUNCTION SUB FormationEditor.each_tick() IF keyval(scF6) > 1 THEN slice_editor rootslice, SL_COLLECT_EDITOR IF positioning_mode THEN each_tick_positioning_mode() ELSE each_tick_menu_mode() END IF IF positioning_mode THEN helpkey = "formation_editor_placement" clear_menu() 'Hide the menu ELSE helpkey = "formation_editor" 'Rebuild the menu unconditionally, because each_tick_menu_mode doesn't set need_update state.need_update = YES END IF END SUB SUB FormationEditor.each_tick_positioning_mode() 'ccCancel is handled by try_exit() IF enter_or_space() ORELSE (readmouse.release AND mouseRight) THEN 'positioning_mode = NO 'state.pt = remem_pt want_exit = YES 'Call try_exit EXIT SUB END IF DIM as integer movespeed = 1 IF keyval(scShift) THEN movespeed = 8 WITH form.slots(slot) DIM sprite as Slice ptr = LookupSlice(SL_FORMEDITOR_ENEMY + slot, rootslice) DIM size as XYPair IF sprite THEN size = sprite->Size ' Note that enemy positions are the top-left corner of the sprite ' (which needs to be changed) IF keyval(ccUp) > 0 THEN .pos.y -= movespeed IF keyval(ccDown) > 0 THEN .pos.y += movespeed IF keyval(ccLeft) > 0 THEN .pos.x -= movespeed IF keyval(ccRight) > 0 THEN .pos.x += movespeed IF readmouse.dragging AND mouseLeft THEN .pos += (readmouse.pos - readmouse.lastpos) END IF ' Allow placing an enemy anywhere onscreen (or just off), not just inside the 'battlefield' DIM bounds as RectPoints = get_formation_bounds() .pos = bound(.pos, bounds.topleft - size, bounds.bottomright) END WITH END SUB SUB FormationEditor.each_tick_menu_mode() IF state.empty() THEN EXIT SUB DIM itemid as integer = itemtypes(state.pt) slot = -1 DIM activate as bool = enter_space_click(state) 'NOTE: we don't set state.need_update (TODO), instead update() called unconditionally. IF cropafter_keycombo(itemid = 1) THEN cropafter form_id, gen(genMaxFormation), game + ".for", 80 SELECT CASE itemid CASE 0 'Previous menu IF activate THEN want_exit = YES CASE 1 'Select a different formation DIM as integer remember_id = form_id IF intgrabber_with_addset(form_id, 0, gen(genMaxFormation), maxMaxFormation, "formation") THEN SaveFormation form, remember_id IF form_id > gen(genMaxFormation) THEN formation_add_new form_id load_form() END IF CASE 2 'Backdrop IF intgrabber(form.background, 0, gen(genNumBackdrops) - 1) THEN bgwait = 0 bgctr = 0 load_formation_slices ename(), form, @rootslice END IF IF activate THEN DIM backdropb as BackdropSpriteBrowser form.background = backdropb.browse(form.background) bgwait = 0 bgctr = 0 load_formation_slices ename(), form, @rootslice END IF CASE 3 'Backdrop animation frames 'IF intgrabber(form.background_frames, 1, 50) THEN DIM temp as integer = form.background_frames - 1 IF xintgrabber(temp, 2, 50) THEN IF form.background_frames = 1 THEN form.background_ticks = 8 'default to 8 ticks because 1 tick can be really painful form.background_frames = temp + 1 IF bgctr >= form.background_frames THEN bgctr = 0 load_formation_slices ename(), form, @rootslice END IF END IF CASE 4 'Backdrop animation ticks IF intgrabber(form.background_ticks, 0, 1000) THEN bgwait = 0 END IF CASE 5 'Battle music IF intgrabber(form.music, -2, gen(genMaxSong)) THEN '-2: same as map, -1: silence update_music END IF IF activate THEN form.music = song_picker_or_none(form.music + 1) - 1 update_music END IF CASE 6 'Victory tag tag_set_grabber(form.victory_tag, state) CASE 7 'On death intgrabber(form.death_action, -1, 0) CASE 8 'Hero formation intgrabber(form.hero_form, 0, last_hero_formation_id()) CASE IS >= 100 slot = itemid - 100 WITH form.slots(slot) DIM oldenemy as integer = .id IF activate THEN 'Usually enemygrabber (below) would handle Enter, but we override it here DIM browse_for_enemy as bool = NO IF .id >= 0 THEN 'This slot has an enemy already DIM choices(1) as string = {"Reposition enemy", "Change Which Enemy"} SELECT CASE multichoice("Slot " & slot, choices()) CASE 0: positioning_mode = YES CASE 1: browse_for_enemy = YES END SELECT remem_pt = state.pt ELSE 'Empty slot browse_for_enemy = YES END IF IF browse_for_enemy THEN .id = enemy_picker_or_none(.id + 1) - 1 END IF ELSEIF enemygrabber(.id, state, 0, -1) THEN END IF IF oldenemy <> .id THEN 'Enemy changed load_formation_slices ename(), form, @rootslice IF oldenemy = -1 THEN formation_init_added_enemy form.slots(slot) END IF 'This would treat the x/y position as being the bottom middle of enemies, which makes much more 'sense, but that would change where enemies of different sizes are spawned in slots in existing games 'See the Plan for battle formation improvements '.pos.x += w(slot) \ 2 '.pos.y += h(slot) END IF END WITH END SELECT END SUB SUB FormationEditor.update_music() IF preview_music ANDALSO form.music <> last_music THEN IF form.music >= 0 THEN playsongnum form.music ELSE music_stop END IF END IF last_music = form.music END SUB SUB FormationEditor.update() IF positioning_mode THEN EXIT SUB DIM temp as string add_item 0, , "Previous Menu" add_item 1, , CHR(27) + "Formation " & form_id & CHR(26) add_item 2, , "Backdrop: " & form.background IF form.background_frames <= 1 THEN add_item 3, , "Backdrop Animation: none" add_item 4, , " Ticks per Backdrop Frame: -NA-", NO ELSE add_item 3, , "Backdrop Animation: " & form.background_frames & " frames" add_item 4, , " Ticks per Backdrop Frame: " & form.background_ticks END IF IF form.music = -2 THEN temp = "-same music as map-" ELSEIF form.music = -1 THEN temp = "-silence-" ELSEIF form.music >= 0 THEN temp = form.music & " " & getsongname(form.music) END IF add_item 5, , "Battle Music: " & temp add_item 6, , "Victory Tag: " & tag_choice_caption(form.victory_tag) temp = "" IF form.death_action = 0 THEN temp = "gameover/death script" ELSEIF form.death_action = -1 THEN temp = "continue game" END IF add_item 7, , "On Death: " & temp add_item 8, , "Hero Formation: " & form.hero_form FOR i as integer = 0 TO 7 add_item 100 + i, , "Enemy: " + ename(i) NEXT i END SUB SUB FormationEditor.draw_underlays() update_formation_background form, rootslice, bgctr, bgwait draw_formation_slices form, rootslice, slot, vpage IF positioning_mode THEN edgeprint "Arrow keys or mouse-drag", pMenuX, pMenuY, uilook(uiText), vpage edgeprint "ESC or right-click when done", pInfoX, pInfoY, uilook(uiText), vpage edgeprint "x=" & form.slots(slot).pos.x & " y=" & form.slots(slot).pos.y, pInfoRight, pMenuY, uilook(uiMenuItem), vpage END IF END SUB SUB formation_init_added_enemy(byref slot as FormationSlot) 'default to middle of field IF slot.pos = 0 THEN slot.pos.x = 70 slot.pos.y = 95 END IF END SUB '========================================================================================== ' Shared formation display code '========================================================================================== 'Deletes previous rootslice if any, then creates a bunch of sprite slices for enemies 'and rectangles for hero positions, but doesn't position them: that's done in 'draw_formation_slices. 'Also loads enemy names into ename(). SUB load_formation_slices(ename() as string, form as Formation, rootslice as Slice ptr ptr) DIM sl as Slice ptr DeleteSlice rootslice ' Root sl = NewSliceOfType(slContainer) *rootslice = sl sl->Size = get_battle_res() sl->Clip = YES 'Trim off parts of the backdrop that are too large 'In the form editor, show the formation at the bottom-right corner of the screen RealignSlice sl, alignRight, alignBottom, alignRight, alignBottom sl->ClampHoriz = alignLeft sl->ClampVert = alignTop ' Battlefield DIM battlefield_sl as Slice ptr = NewSliceOfType(slContainer, sl) battlefield_sl->Lookup = SL_FORMEDITOR_BATTLEFIELD battlefield_sl->Size = get_battlefield_size() CenterSlice battlefield_sl 'battlefield_sl->AutoSort = slAutoSortBottomY battlefield_sl->AutoSort = slAutoSortCustom ' Backdrop IF form.background < 0 THEN 'Used by FormationPreviewer when previewing a hero formation: blank background sl = NewSliceOfType(slRectangle, battlefield_sl) ChangeRectangleSlice sl, 0, , , borderLine, transOpaque sl->Fill = YES ELSE sl = NewSliceOfType(slSprite, battlefield_sl) ChangeSpriteSlice sl, sprTypeBackdrop, form.background END IF sl->Lookup = SL_FORMEDITOR_BACKDROP CenterSlice sl ' Heroes FOR i as integer = 0 TO 3 IF hero_placeholder_sprites(i) = -1 THEN ' Use a rectangle sl = NewSliceOfType(slRectangle, battlefield_sl) ChangeRectangleSlice sl, , boxlook(0).bgcol, boxlook(0).edgecol, , transFuzzy, 75 sl->Width = 32 sl->Height = 40 ELSE ' Use a hero sprite sl = NewSliceOfType(slSprite, battlefield_sl) ChangeSpriteSlice sl, sprTypeHero, bound(hero_placeholder_sprites(i), 0, gen(genMaxHeroPic)) END IF sl->Lookup = SL_FORMEDITOR_HERO + i sl->AnchorHoriz = alignCenter sl->AnchorVert = alignBottom ' Add the party slot number to the center DIM num_sl as Slice ptr num_sl = NewSliceOfType(slText, sl) num_sl->Pos = XY(2,2) ChangeTextSlice num_sl, STR(i), , YES NEXT ' Enemies FOR i as integer = 0 TO 7 ename(i) = "-EMPTY-" IF form.slots(i).id >= 0 THEN DIM enemy as EnemyDef loadenemydata enemy, form.slots(i).id WITH enemy ename(i) = form.slots(i).id & ":" & .name sl = NewSliceOfType(slSprite, battlefield_sl) ChangeSpriteSlice sl, sprTypeSmallEnemy + bound(.size, 0, 2), .pic, .pal sl->Lookup = SL_FORMEDITOR_ENEMY + i END WITH END IF NEXT i ' Cursor (defaults to invisible) sl = NewSliceOfType(slText, battlefield_sl) sl->AlignHoriz = alignCenter sl->AnchorHoriz = alignCenter sl->Lookup = SL_FORMEDITOR_CURSOR ChangeTextSlice sl, CHR(25), -1 - uiSelectedItem2, YES END SUB SUB draw_formation_slices(eform as Formation, rootslice as Slice ptr, selected_slot as integer, page as integer) DIM hform as HeroFormation load_hero_formation hform, eform.hero_form draw_formation_slices eform, hform, rootslice, selected_slot, page, NO END SUB SUB draw_formation_slices(eform as Formation, hform as HeroFormation, rootslice as Slice ptr, selected_slot as integer, page as integer, byval heromode as bool=NO) DIM cursorsl as Slice ptr = LookupSlice(SL_FORMEDITOR_CURSOR, rootslice) cursorsl->Visible = NO ' Set enemy positions (and maybe parent of cursor slice) DIM sl as Slice ptr = LookupSliceSafe(SL_FORMEDITOR_BATTLEFIELD, rootslice)->FirstChild WHILE sl IF sl->Lookup >= SL_FORMEDITOR_ENEMY AND sl->Lookup <= SL_FORMEDITOR_LAST_ENEMY THEN 'Is an enemy DIM enemy_slot as integer = sl->Lookup - SL_FORMEDITOR_ENEMY DIM fslot as FormationSlot ptr = @eform.slots(enemy_slot) IF fslot->id < 0 THEN showbug "Formation enemy slice corresponds to an empty slot" sl->Pos = fslot->pos ' Set layering, like slAutoSortBottomY but break ties according to the order in bslot() ' (Enemy slices are anchored by the top-left edge) sl->Sorter = (sl->Y + sl->Height) * 1000 + 100 + enemy_slot IF NOT heromode THEN IF enemy_slot = selected_slot AND cursorsl <> NULL THEN cursorsl->Visible = YES SetSliceParent cursorsl, sl END IF END IF END IF sl = sl->NextSibling WEND ' Set hero positions (and maybe parent of cursor slice) DIM hrect as Slice Ptr FOR i as integer = 0 TO 3 hrect = LookupSlice(SL_FORMEDITOR_HERO + i, rootslice) hrect->Pos = hform.slots(i).pos + HERO_FORM_OFFSET ' Set layering, like slAutoSortBottomY but break ties according to the order in bslot() ' (Hero slices are anchored by the bottom-center edge) hrect->Sorter = hrect->Y * 1000 + i IF heromode THEN IF i = selected_slot AND cursorsl <> NULL THEN cursorsl->Visible = YES SetSliceParent cursorsl, hrect END IF END IF NEXT i clearpage page DrawSlice rootslice, page END SUB SUB update_formation_background(form as Formation, rootslice as Slice ptr, byref bgctr as integer, byref bgwait as integer) IF form.background_frames > 1 AND form.background_ticks > 0 THEN bgwait = (bgwait + 1) MOD form.background_ticks 'FIXME: off-by-one bug here IF bgwait = 0 THEN loopvar bgctr, 0, form.background_frames - 1 DIM sl as Slice ptr = LookupSlice(SL_FORMEDITOR_BACKDROP, rootslice) ChangeSpriteSlice sl, , (form.background + bgctr) MOD gen(genNumBackdrops) END IF END IF END SUB
1
0.887142
1
0.887142
game-dev
MEDIA
0.363994
game-dev
0.691683
1
0.691683
Jermesa-Studio/JRS_Vehicle_Physics_Controller
5,907
Library/PackageCache/com.unity.visualscripting@1.9.4/Runtime/VisualScripting.Core/Variables/SavedVariables.cs
using System; using System.Linq; using UnityEngine; using UnityObject = UnityEngine.Object; namespace Unity.VisualScripting { public static class SavedVariables { #region Storage public const string assetPath = "SavedVariables"; public const string playerPrefsKey = "LudiqSavedVariables"; private static VariablesAsset _asset; public static VariablesAsset asset { get { if (_asset == null) { Load(); } return _asset; } } public static void Load() { _asset = Resources.Load<VariablesAsset>(assetPath) ?? ScriptableObject.CreateInstance<VariablesAsset>(); } #endregion #region Lifecycle public static void OnEnterEditMode() { FetchSavedDeclarations(); DestroyMergedDeclarations(); // Required because assemblies don't reload on play mode exit } public static void OnExitEditMode() { SaveDeclarations(saved); } internal static void OnEnterPlayMode() { FetchSavedDeclarations(); MergeInitialAndSavedDeclarations(); // The variables saver gameobject is only instantiated if its needed // It's only needed if a variable in our merged collection changes, requiring re-serialization as // the runtime ends merged.OnVariableChanged += () => { if (VariablesSaver.instance == null) VariablesSaver.Instantiate(); }; } internal static void OnExitPlayMode() { SaveDeclarations(merged); } #endregion #region Declarations public static VariableDeclarations initial => asset.declarations; public static VariableDeclarations saved { get; private set; } public static VariableDeclarations merged { get; private set; } public static VariableDeclarations current => Application.isPlaying ? merged : initial; public static void SaveDeclarations(VariableDeclarations declarations) { WarnAndNullifyUnityObjectReferences(declarations); try { var data = declarations.Serialize(); if (data.objectReferences.Length != 0) { // Hopefully, WarnAndNullify will have prevented this exception, // but in case an object reference was nested as a member of the // serialized objects, it wouldn't have caught it, and thus we need // to abort the save process and inform the user. throw new InvalidOperationException("Cannot use Unity object variable references in saved variables."); } PlayerPrefs.SetString(playerPrefsKey, data.json); PlayerPrefs.Save(); } catch (Exception ex) { Debug.LogWarning($"Failed to save variables to player prefs: \n{ex}"); } } public static void FetchSavedDeclarations() { if (PlayerPrefs.HasKey(playerPrefsKey)) { try { saved = (VariableDeclarations)new SerializationData(PlayerPrefs.GetString(playerPrefsKey)).Deserialize(); } catch (Exception ex) { Debug.LogWarning($"Failed to fetch saved variables from player prefs: \n{ex}"); saved = new VariableDeclarations(); } } else { saved = new VariableDeclarations(); } } private static void MergeInitialAndSavedDeclarations() { merged = initial.CloneViaFakeSerialization(); WarnAndNullifyUnityObjectReferences(merged); foreach (var name in saved.Select(vd => vd.name)) { if (!merged.IsDefined(name)) { merged[name] = saved[name]; } else if (merged[name] == null) { if (saved[name] == null || saved[name].GetType().IsNullable()) { merged[name] = saved[name]; } else { Debug.LogWarning($"Cannot convert saved player pref '{name}' to null.\n"); } } else { if (saved[name].IsConvertibleTo(merged[name].GetType(), true)) { merged[name] = saved[name]; } else { Debug.LogWarning($"Cannot convert saved player pref '{name}' to expected type ({merged[name].GetType()}).\nReverting to initial value."); } } } } private static void DestroyMergedDeclarations() { merged = null; } private static void WarnAndNullifyUnityObjectReferences(VariableDeclarations declarations) { Ensure.That(nameof(declarations)).IsNotNull(declarations); foreach (var declaration in declarations) { if (declaration.value is UnityObject) { Debug.LogWarning($"Saved variable '{declaration.name}' refers to a Unity object. This is not supported. Its value will be null."); declarations[declaration.name] = null; } } } #endregion } }
1
0.838468
1
0.838468
game-dev
MEDIA
0.826893
game-dev
0.937078
1
0.937078
SYSU-RoboticsLab/FAEL
28,182
fael_planner/robot_move/cmu_planner/terrain_analysis/src/terrainAnalysis.cpp
#include <math.h> #include <ros/ros.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <message_filters/subscriber.h> #include <message_filters/sync_policies/approximate_time.h> #include <message_filters/synchronizer.h> #include <nav_msgs/Odometry.h> #include <sensor_msgs/Joy.h> #include <sensor_msgs/PointCloud2.h> #include <std_msgs/Float32.h> #include <tf/transform_broadcaster.h> #include <tf/transform_datatypes.h> #include <tf/transform_listener.h> #include <pcl/filters/voxel_grid.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl_conversions/pcl_conversions.h> using namespace std; const double PI = 3.1415926; double scanVoxelSize = 0.05; double decayTime = 2.0; double noDecayDis = 4.0; double clearingDis = 8.0; bool clearingCloud = false; bool useSorting = true; double quantileZ = 0.25; bool considerDrop = false; bool limitGroundLift = false; double maxGroundLift = 0.15; bool clearDyObs = false; double minDyObsDis = 0.3; double minDyObsAngle = 0; double minDyObsRelZ = -0.5; double minDyObsVFOV = -16.0; double maxDyObsVFOV = 16.0; int minDyObsPointNum = 1; bool noDataObstacle = false; int noDataBlockSkipNum = 0; int minBlockPointNum = 10; double vehicleHeight = 1.5; int voxelPointUpdateThre = 100; double voxelTimeUpdateThre = 2.0; double minRelZ = -1.5; double maxRelZ = 0.2; double disRatioZ = 0.2; // terrain voxel parameters float terrainVoxelSize = 1.0; int terrainVoxelShiftX = 0; int terrainVoxelShiftY = 0; const int terrainVoxelWidth = 21; int terrainVoxelHalfWidth = (terrainVoxelWidth - 1) / 2; const int terrainVoxelNum = terrainVoxelWidth * terrainVoxelWidth; // planar voxel parameters float planarVoxelSize = 0.2; const int planarVoxelWidth = 51; int planarVoxelHalfWidth = (planarVoxelWidth - 1) / 2; const int planarVoxelNum = planarVoxelWidth * planarVoxelWidth; pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloud(new pcl::PointCloud<pcl::PointXYZI>()); pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCrop(new pcl::PointCloud<pcl::PointXYZI>()); pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudDwz(new pcl::PointCloud<pcl::PointXYZI>()); pcl::PointCloud<pcl::PointXYZI>::Ptr terrainCloud(new pcl::PointCloud<pcl::PointXYZI>()); pcl::PointCloud<pcl::PointXYZI>::Ptr terrainCloudElev(new pcl::PointCloud<pcl::PointXYZI>()); pcl::PointCloud<pcl::PointXYZI>::Ptr terrainVoxelCloud[terrainVoxelNum]; int terrainVoxelUpdateNum[terrainVoxelNum] = {0}; float terrainVoxelUpdateTime[terrainVoxelNum] = {0}; float planarVoxelElev[planarVoxelNum] = {0}; int planarVoxelEdge[planarVoxelNum] = {0}; int planarVoxelDyObs[planarVoxelNum] = {0}; vector<float> planarPointElev[planarVoxelNum]; double laserCloudTime = 0; bool newlaserCloud = false; double systemInitTime = 0; bool systemInited = false; int noDataInited = 0; float vehicleRoll = 0, vehiclePitch = 0, vehicleYaw = 0; float vehicleX = 0, vehicleY = 0, vehicleZ = 0; float vehicleXRec = 0, vehicleYRec = 0; float sinVehicleRoll = 0, cosVehicleRoll = 0; float sinVehiclePitch = 0, cosVehiclePitch = 0; float sinVehicleYaw = 0, cosVehicleYaw = 0; pcl::VoxelGrid<pcl::PointXYZI> downSizeFilter; // state estimation callback function void odometryHandler(const nav_msgs::Odometry::ConstPtr &odom) { double roll, pitch, yaw; geometry_msgs::Quaternion geoQuat = odom->pose.pose.orientation; tf::Matrix3x3(tf::Quaternion(geoQuat.x, geoQuat.y, geoQuat.z, geoQuat.w)) .getRPY(roll, pitch, yaw); vehicleRoll = roll; vehiclePitch = pitch; vehicleYaw = yaw; vehicleX = odom->pose.pose.position.x; vehicleY = odom->pose.pose.position.y; vehicleZ = odom->pose.pose.position.z; sinVehicleRoll = sin(vehicleRoll); cosVehicleRoll = cos(vehicleRoll); sinVehiclePitch = sin(vehiclePitch); cosVehiclePitch = cos(vehiclePitch); sinVehicleYaw = sin(vehicleYaw); cosVehicleYaw = cos(vehicleYaw); if (noDataInited == 0) { vehicleXRec = vehicleX; vehicleYRec = vehicleY; noDataInited = 1; } if (noDataInited == 1) { float dis = sqrt((vehicleX - vehicleXRec) * (vehicleX - vehicleXRec) + (vehicleY - vehicleYRec) * (vehicleY - vehicleYRec)); if (dis >= noDecayDis) noDataInited = 2; } } tf::TransformListener *tf_listener_; void laserCloudHandler(const sensor_msgs::PointCloud2ConstPtr &laserCloud2) { laserCloudTime = laserCloud2->header.stamp.toSec(); if (!systemInited) { systemInitTime = laserCloudTime; systemInited = true; } laserCloud->clear(); pcl::fromROSMsg(*laserCloud2, *laserCloud); pcl::PointXYZI point; laserCloudCrop->clear(); int laserCloudSize = laserCloud->points.size(); for (int i = 0; i < laserCloudSize; i++) { point = laserCloud->points[i]; float pointX = point.x; float pointY = point.y; float pointZ = point.z; float dis = sqrt((pointX - vehicleX) * (pointX - vehicleX) + (pointY - vehicleY) * (pointY - vehicleY)); if (pointZ - vehicleZ > minRelZ - disRatioZ * dis && pointZ - vehicleZ < maxRelZ + disRatioZ * dis && dis < terrainVoxelSize * (terrainVoxelHalfWidth + 1)) { point.x = pointX; point.y = pointY; point.z = pointZ; point.intensity = laserCloudTime - systemInitTime; laserCloudCrop->push_back(point); } } newlaserCloud = true; } // joystick callback function void joystickHandler(const sensor_msgs::Joy::ConstPtr &joy) { if (joy->buttons[5] > 0.5) { noDataInited = 0; clearingCloud = true; } } // cloud clearing callback function void clearingHandler(const std_msgs::Float32::ConstPtr &dis) { noDataInited = 0; clearingDis = dis->data; clearingCloud = true; } int main(int argc, char **argv) { ros::init(argc, argv, "terrainAnalysis"); ros::NodeHandle nh; ros::NodeHandle nhPrivate("~"); nhPrivate.getParam("scanVoxelSize", scanVoxelSize); nhPrivate.getParam("decayTime", decayTime); nhPrivate.getParam("noDecayDis", noDecayDis); nhPrivate.getParam("clearingDis", clearingDis); nhPrivate.getParam("useSorting", useSorting); nhPrivate.getParam("quantileZ", quantileZ); nhPrivate.getParam("considerDrop", considerDrop); nhPrivate.getParam("limitGroundLift", limitGroundLift); nhPrivate.getParam("maxGroundLift", maxGroundLift); nhPrivate.getParam("clearDyObs", clearDyObs); nhPrivate.getParam("minDyObsDis", minDyObsDis); nhPrivate.getParam("minDyObsAngle", minDyObsAngle); nhPrivate.getParam("minDyObsRelZ", minDyObsRelZ); nhPrivate.getParam("minDyObsVFOV", minDyObsVFOV); nhPrivate.getParam("maxDyObsVFOV", maxDyObsVFOV); nhPrivate.getParam("minDyObsPointNum", minDyObsPointNum); nhPrivate.getParam("noDataObstacle", noDataObstacle); nhPrivate.getParam("noDataBlockSkipNum", noDataBlockSkipNum); nhPrivate.getParam("minBlockPointNum", minBlockPointNum); nhPrivate.getParam("vehicleHeight", vehicleHeight); nhPrivate.getParam("voxelPointUpdateThre", voxelPointUpdateThre); nhPrivate.getParam("voxelTimeUpdateThre", voxelTimeUpdateThre); nhPrivate.getParam("minRelZ", minRelZ); nhPrivate.getParam("maxRelZ", maxRelZ); nhPrivate.getParam("disRatioZ", disRatioZ); tf_listener_ = new tf::TransformListener; ros::Subscriber subOdometry = nh.subscribe<nav_msgs::Odometry>("/state_estimation", 5, odometryHandler); ros::Subscriber subLaserCloud = nh.subscribe<sensor_msgs::PointCloud2>( "/registered_scan", 5, laserCloudHandler); ros::Subscriber subJoystick = nh.subscribe<sensor_msgs::Joy>("/joy", 5, joystickHandler); ros::Subscriber subClearing = nh.subscribe<std_msgs::Float32>("/map_clearing", 5, clearingHandler); ros::Publisher pubLaserCloud = nh.advertise<sensor_msgs::PointCloud2>("/terrain_map", 2); for (int i = 0; i < terrainVoxelNum; i++) { terrainVoxelCloud[i].reset(new pcl::PointCloud<pcl::PointXYZI>()); } downSizeFilter.setLeafSize(scanVoxelSize, scanVoxelSize, scanVoxelSize); ros::Rate rate(100); bool status = ros::ok(); while (status) { ros::spinOnce(); if (newlaserCloud) { newlaserCloud = false; // terrain voxel roll over float terrainVoxelCenX = terrainVoxelSize * terrainVoxelShiftX; float terrainVoxelCenY = terrainVoxelSize * terrainVoxelShiftY; while (vehicleX - terrainVoxelCenX < -terrainVoxelSize) { for (int indY = 0; indY < terrainVoxelWidth; indY++) { pcl::PointCloud<pcl::PointXYZI>::Ptr terrainVoxelCloudPtr = terrainVoxelCloud[terrainVoxelWidth * (terrainVoxelWidth - 1) + indY]; for (int indX = terrainVoxelWidth - 1; indX >= 1; indX--) { terrainVoxelCloud[terrainVoxelWidth * indX + indY] = terrainVoxelCloud[terrainVoxelWidth * (indX - 1) + indY]; } terrainVoxelCloud[indY] = terrainVoxelCloudPtr; terrainVoxelCloud[indY]->clear(); } terrainVoxelShiftX--; terrainVoxelCenX = terrainVoxelSize * terrainVoxelShiftX; } while (vehicleX - terrainVoxelCenX > terrainVoxelSize) { for (int indY = 0; indY < terrainVoxelWidth; indY++) { pcl::PointCloud<pcl::PointXYZI>::Ptr terrainVoxelCloudPtr = terrainVoxelCloud[indY]; for (int indX = 0; indX < terrainVoxelWidth - 1; indX++) { terrainVoxelCloud[terrainVoxelWidth * indX + indY] = terrainVoxelCloud[terrainVoxelWidth * (indX + 1) + indY]; } terrainVoxelCloud[terrainVoxelWidth * (terrainVoxelWidth - 1) + indY] = terrainVoxelCloudPtr; terrainVoxelCloud[terrainVoxelWidth * (terrainVoxelWidth - 1) + indY] ->clear(); } terrainVoxelShiftX++; terrainVoxelCenX = terrainVoxelSize * terrainVoxelShiftX; } while (vehicleY - terrainVoxelCenY < -terrainVoxelSize) { for (int indX = 0; indX < terrainVoxelWidth; indX++) { pcl::PointCloud<pcl::PointXYZI>::Ptr terrainVoxelCloudPtr = terrainVoxelCloud[terrainVoxelWidth * indX + (terrainVoxelWidth - 1)]; for (int indY = terrainVoxelWidth - 1; indY >= 1; indY--) { terrainVoxelCloud[terrainVoxelWidth * indX + indY] = terrainVoxelCloud[terrainVoxelWidth * indX + (indY - 1)]; } terrainVoxelCloud[terrainVoxelWidth * indX] = terrainVoxelCloudPtr; terrainVoxelCloud[terrainVoxelWidth * indX]->clear(); } terrainVoxelShiftY--; terrainVoxelCenY = terrainVoxelSize * terrainVoxelShiftY; } while (vehicleY - terrainVoxelCenY > terrainVoxelSize) { for (int indX = 0; indX < terrainVoxelWidth; indX++) { pcl::PointCloud<pcl::PointXYZI>::Ptr terrainVoxelCloudPtr = terrainVoxelCloud[terrainVoxelWidth * indX]; for (int indY = 0; indY < terrainVoxelWidth - 1; indY++) { terrainVoxelCloud[terrainVoxelWidth * indX + indY] = terrainVoxelCloud[terrainVoxelWidth * indX + (indY + 1)]; } terrainVoxelCloud[terrainVoxelWidth * indX + (terrainVoxelWidth - 1)] = terrainVoxelCloudPtr; terrainVoxelCloud[terrainVoxelWidth * indX + (terrainVoxelWidth - 1)] ->clear(); } terrainVoxelShiftY++; terrainVoxelCenY = terrainVoxelSize * terrainVoxelShiftY; } // stack registered laser scans pcl::PointXYZI point; int laserCloudCropSize = laserCloudCrop->points.size(); for (int i = 0; i < laserCloudCropSize; i++) { point = laserCloudCrop->points[i]; int indX = int((point.x - vehicleX + terrainVoxelSize / 2) / terrainVoxelSize) + terrainVoxelHalfWidth; int indY = int((point.y - vehicleY + terrainVoxelSize / 2) / terrainVoxelSize) + terrainVoxelHalfWidth; if (point.x - vehicleX + terrainVoxelSize / 2 < 0) indX--; if (point.y - vehicleY + terrainVoxelSize / 2 < 0) indY--; if (indX >= 0 && indX < terrainVoxelWidth && indY >= 0 && indY < terrainVoxelWidth) { terrainVoxelCloud[terrainVoxelWidth * indX + indY]->push_back(point); terrainVoxelUpdateNum[terrainVoxelWidth * indX + indY]++; } } for (int ind = 0; ind < terrainVoxelNum; ind++) { if (terrainVoxelUpdateNum[ind] >= voxelPointUpdateThre || laserCloudTime - systemInitTime - terrainVoxelUpdateTime[ind] >= voxelTimeUpdateThre || clearingCloud) { pcl::PointCloud<pcl::PointXYZI>::Ptr terrainVoxelCloudPtr = terrainVoxelCloud[ind]; laserCloudDwz->clear(); downSizeFilter.setInputCloud(terrainVoxelCloudPtr); downSizeFilter.filter(*laserCloudDwz); terrainVoxelCloudPtr->clear(); int laserCloudDwzSize = laserCloudDwz->points.size(); for (int i = 0; i < laserCloudDwzSize; i++) { point = laserCloudDwz->points[i]; float dis = sqrt((point.x - vehicleX) * (point.x - vehicleX) + (point.y - vehicleY) * (point.y - vehicleY)); if (point.z - vehicleZ > minRelZ - disRatioZ * dis && point.z - vehicleZ < maxRelZ + disRatioZ * dis && (laserCloudTime - systemInitTime - point.intensity < decayTime || dis < noDecayDis) && !(dis < clearingDis && clearingCloud)) { terrainVoxelCloudPtr->push_back(point); } } terrainVoxelUpdateNum[ind] = 0; terrainVoxelUpdateTime[ind] = laserCloudTime - systemInitTime; } } terrainCloud->clear(); for (int indX = terrainVoxelHalfWidth - 5; indX <= terrainVoxelHalfWidth + 5; indX++) { for (int indY = terrainVoxelHalfWidth - 5; indY <= terrainVoxelHalfWidth + 5; indY++) { *terrainCloud += *terrainVoxelCloud[terrainVoxelWidth * indX + indY]; } } for (int i = 0; i < planarVoxelNum; i++) { planarVoxelElev[i] = 0; planarVoxelEdge[i] = 0; planarVoxelDyObs[i] = 0; planarPointElev[i].clear(); } int terrainCloudSize = terrainCloud->points.size(); for (int i = 0; i < terrainCloudSize; i++) { point = terrainCloud->points[i]; int indX = int((point.x - vehicleX + planarVoxelSize / 2) / planarVoxelSize) + planarVoxelHalfWidth; int indY = int((point.y - vehicleY + planarVoxelSize / 2) / planarVoxelSize) + planarVoxelHalfWidth; if (point.x - vehicleX + planarVoxelSize / 2 < 0) indX--; if (point.y - vehicleY + planarVoxelSize / 2 < 0) indY--; if (point.z - vehicleZ > minRelZ && point.z - vehicleZ < maxRelZ) { for (int dX = -1; dX <= 1; dX++) { for (int dY = -1; dY <= 1; dY++) { if (indX + dX >= 0 && indX + dX < planarVoxelWidth && indY + dY >= 0 && indY + dY < planarVoxelWidth) { planarPointElev[planarVoxelWidth * (indX + dX) + indY + dY] .push_back(point.z); } } } } if (clearDyObs) { if (indX >= 0 && indX < planarVoxelWidth && indY >= 0 && indY < planarVoxelWidth) { float pointX1 = point.x - vehicleX; float pointY1 = point.y - vehicleY; float pointZ1 = point.z - vehicleZ; float dis1 = sqrt(pointX1 * pointX1 + pointY1 * pointY1); if (dis1 > minDyObsDis) { float angle1 = atan2(pointZ1 - minDyObsRelZ, dis1) * 180.0 / PI; if (angle1 > minDyObsAngle) { float pointX2 = pointX1 * cosVehicleYaw + pointY1 * sinVehicleYaw; float pointY2 = -pointX1 * sinVehicleYaw + pointY1 * cosVehicleYaw; float pointZ2 = pointZ1; float pointX3 = pointX2 * cosVehiclePitch - pointZ2 * sinVehiclePitch; float pointY3 = pointY2; float pointZ3 = pointX2 * sinVehiclePitch + pointZ2 * cosVehiclePitch; float pointX4 = pointX3; float pointY4 = pointY3 * cosVehicleRoll + pointZ3 * sinVehicleRoll; float pointZ4 = -pointY3 * sinVehicleRoll + pointZ3 * cosVehicleRoll; float dis4 = sqrt(pointX4 * pointX4 + pointY4 * pointY4); float angle4 = atan2(pointZ4, dis4) * 180.0 / PI; if (angle4 > minDyObsVFOV && angle4 < maxDyObsVFOV) { planarVoxelDyObs[planarVoxelWidth * indX + indY]++; } } } else { planarVoxelDyObs[planarVoxelWidth * indX + indY] += minDyObsPointNum; } } } } if (clearDyObs) { for (int i = 0; i < laserCloudCropSize; i++) { point = laserCloudCrop->points[i]; int indX = int((point.x - vehicleX + planarVoxelSize / 2) / planarVoxelSize) + planarVoxelHalfWidth; int indY = int((point.y - vehicleY + planarVoxelSize / 2) / planarVoxelSize) + planarVoxelHalfWidth; if (point.x - vehicleX + planarVoxelSize / 2 < 0) indX--; if (point.y - vehicleY + planarVoxelSize / 2 < 0) indY--; if (indX >= 0 && indX < planarVoxelWidth && indY >= 0 && indY < planarVoxelWidth) { float pointX1 = point.x - vehicleX; float pointY1 = point.y - vehicleY; float pointZ1 = point.z - vehicleZ; float dis1 = sqrt(pointX1 * pointX1 + pointY1 * pointY1); float angle1 = atan2(pointZ1 - minDyObsRelZ, dis1) * 180.0 / PI; if (angle1 > minDyObsAngle) { planarVoxelDyObs[planarVoxelWidth * indX + indY] = 0; } } } } if (useSorting) { for (int i = 0; i < planarVoxelNum; i++) { int planarPointElevSize = planarPointElev[i].size(); if (planarPointElevSize > 0) { sort(planarPointElev[i].begin(), planarPointElev[i].end()); int quantileID = int(quantileZ * planarPointElevSize); if (quantileID < 0) quantileID = 0; else if (quantileID >= planarPointElevSize) quantileID = planarPointElevSize - 1; if (planarPointElev[i][quantileID] > planarPointElev[i][0] + maxGroundLift && limitGroundLift) { planarVoxelElev[i] = planarPointElev[i][0] + maxGroundLift; } else { planarVoxelElev[i] = planarPointElev[i][quantileID]; } } } } else { for (int i = 0; i < planarVoxelNum; i++) { int planarPointElevSize = planarPointElev[i].size(); if (planarPointElevSize > 0) { float minZ = 1000.0; int minID = -1; for (int j = 0; j < planarPointElevSize; j++) { if (planarPointElev[i][j] < minZ) { minZ = planarPointElev[i][j]; minID = j; } } if (minID != -1) { planarVoxelElev[i] = planarPointElev[i][minID]; } } } } terrainCloudElev->clear(); int terrainCloudElevSize = 0; for (int i = 0; i < terrainCloudSize; i++) { point = terrainCloud->points[i]; if (point.z - vehicleZ > minRelZ && point.z - vehicleZ < maxRelZ) { int indX = int((point.x - vehicleX + planarVoxelSize / 2) / planarVoxelSize) + planarVoxelHalfWidth; int indY = int((point.y - vehicleY + planarVoxelSize / 2) / planarVoxelSize) + planarVoxelHalfWidth; if (point.x - vehicleX + planarVoxelSize / 2 < 0) indX--; if (point.y - vehicleY + planarVoxelSize / 2 < 0) indY--; if (indX >= 0 && indX < planarVoxelWidth && indY >= 0 && indY < planarVoxelWidth) { if (planarVoxelDyObs[planarVoxelWidth * indX + indY] < minDyObsPointNum || !clearDyObs) { float disZ = point.z - planarVoxelElev[planarVoxelWidth * indX + indY]; if (considerDrop) disZ = fabs(disZ); int planarPointElevSize = planarPointElev[planarVoxelWidth * indX + indY].size(); if (disZ >= 0 && disZ < vehicleHeight && planarPointElevSize >= minBlockPointNum) { terrainCloudElev->push_back(point); terrainCloudElev->points[terrainCloudElevSize].intensity = disZ; terrainCloudElevSize++; } } } } } if (noDataObstacle && noDataInited == 2) { for (int i = 0; i < planarVoxelNum; i++) { int planarPointElevSize = planarPointElev[i].size(); if (planarPointElevSize < minBlockPointNum) { planarVoxelEdge[i] = 1; } } for (int noDataBlockSkipCount = 0; noDataBlockSkipCount < noDataBlockSkipNum; noDataBlockSkipCount++) { for (int i = 0; i < planarVoxelNum; i++) { if (planarVoxelEdge[i] >= 1) { int indX = int(i / planarVoxelWidth); int indY = i % planarVoxelWidth; bool edgeVoxel = false; for (int dX = -1; dX <= 1; dX++) { for (int dY = -1; dY <= 1; dY++) { if (indX + dX >= 0 && indX + dX < planarVoxelWidth && indY + dY >= 0 && indY + dY < planarVoxelWidth) { if (planarVoxelEdge[planarVoxelWidth * (indX + dX) + indY + dY] < planarVoxelEdge[i]) { edgeVoxel = true; } } } } if (!edgeVoxel) planarVoxelEdge[i]++; } } } for (int i = 0; i < planarVoxelNum; i++) { if (planarVoxelEdge[i] > noDataBlockSkipNum) { int indX = int(i / planarVoxelWidth); int indY = i % planarVoxelWidth; point.x = planarVoxelSize * (indX - planarVoxelHalfWidth) + vehicleX; point.y = planarVoxelSize * (indY - planarVoxelHalfWidth) + vehicleY; point.z = 0.0; point.intensity = vehicleHeight; point.x -= planarVoxelSize / 4.0; point.y -= planarVoxelSize / 4.0; terrainCloudElev->push_back(point); point.x += planarVoxelSize / 2.0; terrainCloudElev->push_back(point); point.y += planarVoxelSize / 2.0; terrainCloudElev->push_back(point); point.x -= planarVoxelSize / 2.0; terrainCloudElev->push_back(point); } } } clearingCloud = false; // publish points with elevation sensor_msgs::PointCloud2 terrainCloud2; pcl::toROSMsg(*terrainCloudElev, terrainCloud2); terrainCloud2.header.stamp = ros::Time().fromSec(laserCloudTime); terrainCloud2.header.frame_id = "map"; pubLaserCloud.publish(terrainCloud2); } status = ros::ok(); rate.sleep(); } return 0; }
1
0.835956
1
0.835956
game-dev
MEDIA
0.547269
game-dev
0.958279
1
0.958279
folgerwang/UnrealEngine
31,039
Engine/Source/Editor/UnrealEd/Public/FileHelpers.h
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "AssetData.h" #include "ISourceControlProvider.h" #include "UObject/TextProperty.h" #include "FileHelpers.generated.h" class ULevel; enum EFileInteraction { FI_Load, FI_Save, FI_ImportScene, FI_ExportScene }; namespace EAutosaveContentPackagesResult { enum Type { Success, NothingToDo, Failure }; } /** * This class is a wrapper for editor loading and saving functionality * It is meant to contain only functions that can be executed in script (but are also allowed in C++). * It is separated from FEditorFileUtils to ensure new easier to use methods can be created without breaking FEditorFileUtils backwards compatibility * However this should be used in place of FEditorFileUtils wherever possible as the goal is to deprecate FEditorFileUtils eventually */ UCLASS(transient) class UEditorLoadingAndSavingUtils : public UObject { GENERATED_BODY() public: UFUNCTION(BlueprintCallable, Category= "Editor Scripting | Editor Loading and Saving") static UNREALED_API UWorld* NewBlankMap(bool bSaveExistingMap); UFUNCTION(BlueprintCallable, Category = "Editor Scripting | Editor Loading and Saving") static UNREALED_API UWorld* NewMapFromTemplate(const FString& PathToTemplateLevel, bool bSaveExistingMap); /** * Prompts the user to save the current map if necessary, the presents a load dialog and * loads a new map if selected by the user. */ UFUNCTION(BlueprintCallable, Category = "Editor Scripting | Editor Loading and Saving") static UNREALED_API UWorld* LoadMapWithDialog(); /** * Loads the specified map. Does not prompt the user to save the current map. * * @param Filename Level package filename, including path. * @return true if the map was loaded successfully. */ UFUNCTION(BlueprintCallable, Category="Editor Scripting | Editor Loading and Saving") static UNREALED_API UWorld* LoadMap(const FString& Filename); /** * Saves the specified map, returning true on success. * * @param World The world to save. * @param AssetPath The valid content directory path and name for the asset. E.g "/Game/MyMap" * * @return true if the map was saved successfully. */ UFUNCTION(BlueprintCallable, Category = "Editor Scripting | Editor Loading and Saving") static UNREALED_API bool SaveMap(UWorld* World, const FString& AssetPath); /** * Save all packages. * Assume all dirty packages should be saved and check out from source control (if enabled). * * @param PackagesToSave The list of packages to save. Both map and content packages are supported * @param bCheckDirty If true, only packages that are dirty in PackagesToSave will be saved * @return true on success, false on fail. */ UFUNCTION(BlueprintCallable, Category = "Editor Scripting | Editor Loading and Saving") static UNREALED_API bool SavePackages(const TArray<UPackage*>& PackagesToSave, bool bOnlyDirty); /** * Save all packages. Optionally prompting the user to select which packages to save. * Prompt the user to select which dirty packages to save and check them out from source control (if enabled). * * @param PackagesToSave The list of packages to save. Both map and content packages are supported * @param bCheckDirty If true, only packages that are dirty in PackagesToSave will be saved * @return true on success, false on fail. */ UFUNCTION(BlueprintCallable, Category = "Editor Scripting | Editor Loading and Saving") static UNREALED_API bool SavePackagesWithDialog(const TArray<UPackage*>& PackagesToSave, bool bOnlyDirty); /** * Looks at all currently loaded packages and saves them if their "bDirty" flag is set. * Assume all dirty packages should be saved and check out from source control (if enabled). * * @param bSaveMapPackages true if map packages should be saved * @param bSaveContentPackages true if we should save content packages. * @return true on success, false on fail. */ UFUNCTION(BlueprintCallable, Category = "Editor Scripting | Editor Loading and Saving") static UNREALED_API bool SaveDirtyPackages(const bool bSaveMapPackages, const bool bSaveContentPackages); /** * Looks at all currently loaded packages and saves them if their "bDirty" flag is set. * Prompt the user to select which dirty packages to save and check them out from source control (if enabled). * * @param bSaveMapPackages true if map packages should be saved * @param bSaveContentPackages true if we should save content packages. * @return true on success, false on fail. */ UFUNCTION(BlueprintCallable, Category = "Editor Scripting | Editor Loading and Saving") static UNREALED_API bool SaveDirtyPackagesWithDialog(const bool bSaveMapPackages, const bool bSaveContentPackages); /** * Saves the active level, prompting the use for checkout if necessary. * * @return true on success, False on fail */ UFUNCTION(BlueprintCallable, Category = "Editor Scripting | Editor Loading and Saving") static UNREALED_API bool SaveCurrentLevel(); /** * Appends array with all currently dirty map packages. * * @param OutDirtyPackages Array to append dirty packages to. */ UFUNCTION(BlueprintCallable, Category = "Editor Scripting | Editor Loading and Saving") static UNREALED_API void GetDirtyMapPackages(TArray<UPackage*>& OutDirtyPackages); /** * Appends array with all currently dirty content packages. * * @param OutDirtyPackages Array to append dirty packages to. */ UFUNCTION(BlueprintCallable, Category = "Editor Scripting | Editor Loading and Saving") static UNREALED_API void GetDirtyContentPackages(TArray<UPackage*>& OutDirtyPackages); /** * Imports a file such as (FBX or obj) and spawns actors f into the current level */ UFUNCTION(BlueprintCallable, Category = "Editor Scripting | Editor Loading and Saving") static UNREALED_API void ImportScene(const FString& Filename); /** * Exports the current scene */ UFUNCTION(BlueprintCallable, Category = "Editor Scripting | Editor Loading and Saving") static UNREALED_API void ExportScene(bool bExportSelectedActorsOnly); /** * Unloads a list of packages * * @param PackagesToUnload Array of packages to unload. */ UFUNCTION(BlueprintCallable, Category = "Editor Scripting | Editor Loading and Saving") static UNREALED_API void UnloadPackages(const TArray<UPackage*>& PackagesToUnload, bool& bOutAnyPackagesUnloaded, FText& OutErrorMessage); }; /** * For saving map files through the main editor frame. */ class FEditorFileUtils { public: /** Used to decide how to handle garbage collection. */ enum EGarbageCollectionOption { GCO_SkipGarbageCollection = 0, GCO_CollectGarbage = 1, }; /** Sets the active level filename so that "Save" operates on this file and "SaveAs" must be used on others */ static void RegisterLevelFilename(UObject* Object, const FString& NewLevelFilename); //////////////////////////////////////////////////////////////////////////// // ResetLevelFilenames /** * Clears current level filename so that the user must SaveAs on next Save. * Called by NewMap() after the contents of the map are cleared. * Also called after loading a map template so that the template isn't overwritten. */ static void ResetLevelFilenames(); //////////////////////////////////////////////////////////////////////////// // Loading DECLARE_DELEGATE_OneParam(FOnLevelsChosen, const TArray<FAssetData>& /*SelectedLevels*/); DECLARE_DELEGATE(FOnLevelPickingCancelled); /** * Opens a non-modal dialog to allow the user to choose a level * * @param OnLevelsChosen Delegate executed when one more more levels have been selected * @param OnLevelPickingDialogClosed Delegate executed when the level picking dialog is closed * @param bAllowMultipleSelection If true, more than one level can be chosen */ static UNREALED_API void OpenLevelPickingDialog(const FOnLevelsChosen& OnLevelsChosen, const FOnLevelPickingCancelled& OnLevelPickingCancelled, bool bAllowMultipleSelection); /** * Returns true if the specified map filename is valid for loading or saving. * When returning false, OutErrorMessage is supplied with a display string describing the reason why the map name is invalid. */ static UNREALED_API bool IsValidMapFilename(const FString& MapFilename, FText& OutErrorMessage); /** * Unloads the specified package potentially containing an inactive world. * When returning false, OutErrorMessage is supplied with a display string describing the reason why the world could not be unloaded. */ static UNREALED_API bool AttemptUnloadInactiveWorldPackage(UPackage* PackageToUnload, FText& OutErrorMessage); /** * Prompts the user to save the current map if necessary, the presents a load dialog and * loads a new map if selected by the user. */ static UNREALED_API bool LoadMap(); /** * Loads the specified map. Does not prompt the user to save the current map. * * @param Filename Map package filename, including path. * * @param LoadAsTemplate Forces the map to load into an untitled outermost package * preventing the map saving over the original file. * @param bShowProgress Whether to show a progress dialog as the map loads\ * @return true on success, false otherwise */ static UNREALED_API bool LoadMap(const FString& Filename, bool LoadAsTemplate = false, const bool bShowProgress=true); //////////////////////////////////////////////////////////////////////////// // Saving /** * Saves the specified map package, returning true on success. * * @param World The world to save. * @param Filename Map package filename, including path. * * @return true if the map was saved successfully. */ static bool SaveMap(UWorld* World, const FString& Filename ); /** * Saves the specified level. SaveAs is performed as necessary. * * @param Level The level to be saved. * @param DefaultFilename File name to use for this level if it doesn't have one yet (or empty string to prompt) * @param OutSavedFilename When returning true, this string will be set to the filename of the saved level. * * @return true if the level was saved. */ static UNREALED_API bool SaveLevel(ULevel* Level, const FString& DefaultFilename = TEXT( "" ), FString* OutSavedFilename = nullptr ); /** Saves packages which contain map data but are not map packages themselves. */ static UNREALED_API void SaveMapDataPackages(UWorld* World, bool bCheckDirty); /** * Does a SaveAs for the specified assets. * * @param Assets The collection of assets to save. * @param SavedAssets The collection of corresponding saved assets (contains original asset if not resaved). */ UNREALED_API static void SaveAssetsAs(const TArray<UObject*>& Assets, TArray<UObject*>& OutSavedAssets); /** * Does a saveAs for the specified level. * * @param Level The Level to be SaveAs'd. * @param OutSavedFilename When returning true, this string will be set to the filename of the saved level. * @return true if the world was saved. */ UNREALED_API static bool SaveLevelAs(ULevel* Level, FString* OutSavedFilename = nullptr); /** * Saves all levels to the specified directory. * * @param AbsoluteAutosaveDir Autosave directory. * @param AutosaveIndex Integer prepended to autosave filenames.. * @param bForceIfNotInList Should the save be forced if the package is dirty, but not in DirtyPackagesForAutoSave? * @param DirtyPackagesForAutoSave A set of packages that are considered by the auto-save system to be dirty, you should check this to see if a package needs saving */ static bool AutosaveMap(const FString& AbsoluteAutosaveDir, const int32 AutosaveIndex, const bool bForceIfNotInList, const TSet< TWeakObjectPtr<UPackage> >& DirtyPackagesForAutoSave); /** * Saves all levels to the specified directory. * * @param AbsoluteAutosaveDir Autosave directory. * @param AutosaveIndex Integer prepended to autosave filenames.. * @param bForceIfNotInList Should the save be forced if the package is dirty, but not in DirtyPackagesForAutoSave? * @param DirtyPackagesForAutoSave A set of packages that are considered by the auto-save system to be dirty, you should check this to see if a package needs saving */ static EAutosaveContentPackagesResult::Type AutosaveMapEx(const FString& AbsoluteAutosaveDir, const int32 AutosaveIndex, const bool bForceIfNotInList, const TSet< TWeakObjectPtr<UPackage> >& DirtyPackagesForAutoSave); /** * Saves all asset packages to the specified directory. * * @param AbsoluteAutosaveDir Autosave directory. * @param AutosaveIndex Integer prepended to autosave filenames. * @param bForceIfNotInList Should the save be forced if the package is dirty, but not in DirtyPackagesForAutoSave? * @param DirtyPackagesForAutoSave A set of packages that are considered by the auto-save system to be dirty, you should check this to see if a package needs saving * * @return true if one or more packages were autosaved; false otherwise */ static bool AutosaveContentPackages(const FString& AbsoluteAutosaveDir, const int32 AutosaveIndex, const bool bForceIfNotInList, const TSet< TWeakObjectPtr<UPackage> >& DirtyPackagesForAutoSave); /** * Saves all asset packages to the specified directory. * * @param AbsoluteAutosaveDir Autosave directory. * @param AutosaveIndex Integer prepended to autosave filenames. * @param bForceIfNotInList Should the save be forced if the package is dirty, but not in DirtyPackagesForAutoSave? * @param DirtyPackagesForAutoSave A set of packages that are considered by the auto-save system to be dirty, you should check this to see if a package needs saving * * @return Success if saved at least one faile. NothingToDo if there was nothing to save. Failure on at least one auto-save failure. */ static EAutosaveContentPackagesResult::Type AutosaveContentPackagesEx(const FString& AbsoluteAutosaveDir, const int32 AutosaveIndex, const bool bForceIfNotInList, const TSet< TWeakObjectPtr<UPackage> >& DirtyPackagesForAutoSave); /** * Looks at all currently loaded packages and saves them if their "bDirty" flag is set, optionally prompting the user to select which packages to save) * * @param bPromptUserToSave true if we should prompt the user to save dirty packages we found. false to assume all dirty packages should be saved. Regardless of this setting the user will be prompted for checkout(if needed) unless bFastSave is set * @param bSaveMapPackages true if map packages should be saved * @param bSaveContentPackages true if we should save content packages. * @param bFastSave true if we should do a fast save. (I.E dont prompt the user to save, dont prompt for checkout, and only save packages that are currently writable). Note: Still prompts for SaveAs if a package needs a filename * @param bNotifyNoPackagesSaved true if a notification should be displayed when no packages need to be saved. * @param bCanBeDeclined true if the user prompt should contain a "Don't Save" button in addition to "Cancel", which won't result in a failure return code. * @param bOutPackagesNeededSaving when not NULL, will be set to true if there was any work to be done, and false otherwise. * @return true on success, false on fail. */ UNREALED_API static bool SaveDirtyPackages(const bool bPromptUserToSave, const bool bSaveMapPackages, const bool bSaveContentPackages, const bool bFastSave = false, const bool bNotifyNoPackagesSaved = false, const bool bCanBeDeclined = true, bool* bOutPackagesNeededSaving = NULL); /** * Looks at all currently loaded packages and saves them if their "bDirty" flag is set and they include specified clasees, optionally prompting the user to select which packages to save) * * @param SaveContentClasses save only specified classes or children classes * @param bPromptUserToSave true if we should prompt the user to save dirty packages we found. false to assume all dirty packages should be saved. Regardless of this setting the user will be prompted for checkout(if needed) unless bFastSave is set * @param bFastSave true if we should do a fast save. (I.E dont prompt the user to save, dont prompt for checkout, and only save packages that are currently writable). Note: Still prompts for SaveAs if a package needs a filename * @param bNotifyNoPackagesSaved true if a notification should be displayed when no packages need to be saved. * @param bCanBeDeclined true if the user prompt should contain a "Don't Save" button in addition to "Cancel", which won't result in a failure return code. * @return true on success, false on fail. */ UNREALED_API static bool SaveDirtyContentPackages(TArray<UClass*>& SaveContentClasses, const bool bPromptUserToSave, const bool bFastSave = false, const bool bNotifyNoPackagesSaved = false, const bool bCanBeDeclined = true); /** * Appends array with all currently dirty world packages. * * @param OutDirtyPackages Array to append dirty packages to. */ UNREALED_API static void GetDirtyWorldPackages(TArray<UPackage*>& OutDirtyPackages); /** * Appends array with all currently dirty content packages. * * @param OutDirtyPackages Array to append dirty packages to. */ UNREALED_API static void GetDirtyContentPackages(TArray<UPackage*>& OutDirtyPackages); /** * Saves the active level, prompting the use for checkout if necessary. * * @return true on success, False on fail */ UNREALED_API static bool SaveCurrentLevel(); /** Enum used for prompt returns */ enum EPromptReturnCode { PR_Success, /** The user has answered in the affirmative to all prompts, and execution succeeded */ PR_Failure, /** The user has answered in the affirmative to prompts, but an operation(s) has failed during execution */ PR_Declined, /** The user has declined out of the prompt; the caller should continue whatever it was doing */ PR_Cancelled /** The user has cancelled out of a prompt; the caller should abort whatever it was doing */ }; /** * Optionally prompts the user for which of the provided packages should be saved, and then additionally prompts the user to check-out any of * the provided packages which are under source control. If the user cancels their way out of either dialog, no packages are saved. It is possible the user * will be prompted again, if the saving process fails for any reason. In that case, the user will be prompted on a package-by-package basis, allowing them * to retry saving, skip trying to save the current package, or to again cancel out of the entire dialog. If the user skips saving a package that failed to save, * the package will be added to the optional OutFailedPackages array, and execution will continue. After all packages are saved (or not), the user is provided with * a warning about any packages that were writable on disk but not in source control, as well as a warning about which packages failed to save. * * @param PackagesToSave The list of packages to save. Both map and content packages are supported * @param bCheckDirty If true, only packages that are dirty in PackagesToSave will be saved * @param bPromptToSave If true the user will be prompted with a list of packages to save, otherwise all passed in packages are saved * @param OutFailedPackages [out] If specified, will be filled in with all of the packages that failed to save successfully * @param bAlreadyCheckedOut If true, the user will not be prompted with the source control dialog * @param bCanBeDeclined If true, offer a "Don't Save" option in addition to "Cancel", which will not result in a cancellation return code. * * @return An enum value signifying success, failure, user declined, or cancellation. If any packages at all failed to save during execution, the return code will be * failure, even if other packages successfully saved. If the user cancels at any point during any prompt, the return code will be cancellation, even though it * is possible some packages have been successfully saved (if the cancel comes on a later package that can't be saved for some reason). If the user opts the "Don't * Save" option on the dialog, the return code will indicate the user has declined out of the prompt. This way calling code can distinguish between a decline and a cancel * and then proceed as planned, or abort its operation accordingly. */ UNREALED_API static EPromptReturnCode PromptForCheckoutAndSave( const TArray<UPackage*>& PackagesToSave, bool bCheckDirty, bool bPromptToSave, TArray<UPackage*>* OutFailedPackages = NULL, bool bAlreadyCheckedOut = false, bool bCanBeDeclined = true ); //////////////////////////////////////////////////////////////////////////// // Import/Export /** * Presents the user with a file dialog for importing. * If the import is not a merge (bMerging is false), AskSaveChanges() is called first. */ UNREALED_API static void Import(); UNREALED_API static void Import(const FString& InFilename); UNREALED_API static void Export(bool bExportSelectedActorsOnly); // prompts user for file etc. //////////////////////////////////////////////////////////////////////////// // Source Control /** * Prompt the user with a check-box dialog allowing him/her to check out the provided packages * from source control, if desired * * @param bCheckDirty If true, non-dirty packages won't be added to the dialog * @param PackagesToCheckOut Reference to array of packages to prompt the user with for possible check out * @param OutPackagesCheckedOutOrMadeWritable If not NULL, this array will be populated with packages that the user selected to check out or make writable. * @param OutPackagesNotNeedingCheckout If not NULL, this array will be populated with packages that the user was not prompted about and do not need to be checked out to save. Useful for saving packages even if the user canceled the checkout dialog. * @param bPromptingAfterModify If true, we are prompting the user after an object has been modified, which changes the cancel button to "Ask me later". * * @return true if the user did not cancel out of the dialog and has potentially checked out some files * (or if there is no source control integration); false if the user cancelled the dialog */ UNREALED_API static bool PromptToCheckoutPackages(bool bCheckDirty, const TArray<UPackage*>& PackagesToCheckOut, TArray< UPackage* >* OutPackagesCheckedOutOrMadeWritable = NULL, TArray< UPackage* >* OutPackagesNotNeedingCheckout = NULL, const bool bPromptingAfterModify = false ); /** * Check out the specified packages from source control and report any errors while checking out * * @param PkgsToCheckOut Reference to array of packages to check out * @param OutPackagesCheckedOut If not NULL, this array will be populated with packages that were checked out. * @param bErrorIfAlreadyCheckedOut true to consider being unable to checkout a package because it is already checked out an error, false to allow this without error * * @return true if all the packages were checked out successfully */ UNREALED_API static ECommandResult::Type CheckoutPackages(const TArray<UPackage*>& PkgsToCheckOut, TArray<UPackage*>* OutPackagesCheckedOut = NULL, const bool bErrorIfAlreadyCheckedOut = true); /** * Check out the specified packages from source control and report any errors while checking out * * @param PkgsToCheckOut Reference to array of package names to check out * @param OutPackagesCheckedOut If not NULL, this array will be populated with packages that were checked out. * @param bErrorIfAlreadyCheckedOut true to consider being unable to checkout a package because it is already checked out an error, false to allow this without error * * @return the result of the check out operation */ UNREALED_API static ECommandResult::Type CheckoutPackages(const TArray<FString>& PkgsToCheckOut, TArray<FString>* OutPackagesCheckedOut = NULL, const bool bErrorIfAlreadyCheckedOut = true); /** * Prompt the user with a check-box dialog allowing him/her to check out relevant level packages * from source control * * @param bCheckDirty If true, non-dirty packages won't be added to the dialog * @param SpecificLevelsToCheckOut If specified, only the provided levels' packages will display in the * dialog if they are under source control; If nothing is specified, all levels * referenced by GWorld whose packages are under source control will be displayed * @param OutPackagesNotNeedingCheckout If not null, this array will be populated with packages that the user was not prompted about and do not need to be checked out to save. Useful for saving packages even if the user canceled the checkout dialog. * * @return true if the user did not cancel out of the dialog and has potentially checked out some files (or if there is * no source control integration); false if the user cancelled the dialog */ UNREALED_API static bool PromptToCheckoutLevels(bool bCheckDirty, const TArray<ULevel*>& SpecificLevelsToCheckOut, TArray<UPackage*>* OutPackagesNotNeedingCheckout = NULL); /** * Overloaded version of PromptToCheckOutLevels which prompts the user with a check-box dialog allowing * him/her to check out the relevant level package if necessary * * @param bCheckDirty If true, non-dirty packages won't be added to the dialog * @param SpecificLevelToCheckOut The level whose package will display in the dialog if it is * under source control * * @return true if the user did not cancel out of the dialog and has potentially checked out some files (or if there is * no source control integration); false if the user cancelled the dialog */ UNREALED_API static bool PromptToCheckoutLevels(bool bCheckDirty, ULevel* SpecificLevelToCheckOut); /** * Checks to see if a filename is valid for saving. * A filename must be under FPlatformMisc::GetMaxPathLength() to be saved * * @param Filename Filename, with or without path information, to check. * @param OutError If an error occurs, this is the reason why */ UE_DEPRECATED(4.18, "Call FFileHelper::IsFilenameValidForSaving instead") UNREALED_API static bool IsFilenameValidForSaving(const FString& Filename, FText& OutError); /** Loads a simple example map */ UNREALED_API static void LoadDefaultMapAtStartup(); /** * Save all packages corresponding to the specified world, with the option to override their path and also * apply a prefix. * * @param InWorld The world to save (including its children) * @param RootPath Root Path override, replaces /Game/ in original name * @param Prefix Optional prefix for base filename, can be NULL * @param OutFilenames The file names of all successfully saved worlds will be added to this * @return true if at least one level was saved. * If bPIESaving, will be true is ALL worlds were saved. */ static bool SaveWorlds(UWorld* InWorld, const FString& RootPath, const TCHAR* Prefix, TArray<FString>& OutFilenames); /** Whether or not we're in the middle of loading the simple startup map */ static bool IsLoadingStartupMap() {return bIsLoadingDefaultStartupMap;} /** * Returns a file filter string appropriate for a specific file interaction. * * @param Interaction A file interaction to get a filter string for. * @return A filter string. */ UNREALED_API static FString GetFilterString(EFileInteraction Interaction); /** * Looks for package files in the known content paths on disk. * * @param OutPackages All found package filenames. */ UNREALED_API static void FindAllPackageFiles(TArray<FString>& OutPackages); /** * Looks for source control submittable files in the known content paths on disk. * * @param OutPackages All found package filenames and their source control state * @param bIncludeMaps If true, also adds maps to the list */ UNREALED_API static void FindAllSubmittablePackageFiles(TMap<FString, FSourceControlStatePtr>& OutPackages, const bool bIncludeMaps); /** * Looks for config files for the current project. * * @param OutConfigFiles All found config filenames. */ UNREALED_API static void FindAllConfigFiles(TArray<FString>& OutConfigFiles); /** * Looks for source control submittable config files for the current project. * * @param OutConfigFiles All found config filenames and their source control state. */ UNREALED_API static void FindAllSubmittableConfigFiles(TMap<FString, FSourceControlStatePtr>& OutConfigFiles); /** * Helper function used to decide whether a package name is a map package or not. Map packages aren't added to the additional package list. * * @param ObjectPath The path to the package to test * @return True if package is a map */ UNREALED_API static bool IsMapPackageAsset(const FString& ObjectPath); /** * Helper function used to decide whether a package name is a map package or not. Map packages aren't added to the additional package list. * * @param ObjectPath The path to the package to test * @param MapFilePath OUT parameter that returns the map file path if it exists. * @return True if package is a map */ UNREALED_API static bool IsMapPackageAsset(const FString& ObjectPath, FString& MapFilePath); /** * Helper function used to extract the package name from the object path * * @param ObjectPath The path to the package to test * @return The package name from the string */ UNREALED_API static FString ExtractPackageName(const FString& ObjectPath);\ //////////////////////////////////////////////////////////////////////////// // File UNREALED_API static FString GetFilename(const FName& PackageName); UNREALED_API static FString GetFilename(UObject* LevelObject); private: /** Private method used to build a list of items requiring checkout */ static bool AddCheckoutPackageItems(bool bCheckDirty, TArray<UPackage*> PackagesToCheckOut, TArray<UPackage*>* OutPackagesNotNeedingCheckout, bool* bOutHavePackageToCheckOut); /** Callback from PackagesDialog used to update the list of items when the source control state changes */ static void UpdateCheckoutPackageItems(bool bCheckDirty, TArray<UPackage*> PackagesToCheckOut, TArray<UPackage*>* OutPackagesNotNeedingCheckout); static bool bIsLoadingDefaultStartupMap; /** Flag used to determine if the checkout and save prompt is already open to prevent re-entrance */ static bool bIsPromptingForCheckoutAndSave; // Set of packages to ignore for save/checkout when using SaveAll. static TSet<FString> PackagesNotSavedDuringSaveAll; // Set of packages which should no longer prompt for checkouts / to be made writable static TSet<FString> PackagesNotToPromptAnyMore; };
1
0.880582
1
0.880582
game-dev
MEDIA
0.36868
game-dev
0.761553
1
0.761553
AztechMC/Modern-Industrialization
11,268
src/main/java/aztech/modern_industrialization/inventory/ConfigurableScreenHandler.java
/* * MIT License * * Copyright (c) 2020 Azercoco & Technici4n * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package aztech.modern_industrialization.inventory; import aztech.modern_industrialization.network.machines.UpdateFluidSlotPacket; import aztech.modern_industrialization.network.machines.UpdateItemSlotPacket; import aztech.modern_industrialization.util.Simulation; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Predicate; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.SlotAccess; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.ClickType; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.Slot; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; /** * The ScreenHandler for a configurable inventory. The first slots must be the * player slots for shift-click to work correctly! */ public abstract class ConfigurableScreenHandler extends AbstractContainerMenu { private static final int PLAYER_SLOTS = 36; public boolean lockingMode = false; protected Inventory playerInventory; public final MIInventory inventory; private List<ConfigurableItemStack> trackedItems; private List<ConfigurableFluidStack> trackedFluids; // Groups slots together to avoid shift-click splitting a stack across to unrelated subinventories. private final Map<Slot, SlotGroup> slotGroups = new IdentityHashMap<>(); private final Set<SlotGroup> slotGroupIndices = new LinkedHashSet<>(); protected ConfigurableScreenHandler(MenuType<?> type, int syncId, Inventory playerInventory, MIInventory inventory) { super(type, syncId); this.playerInventory = playerInventory; this.inventory = inventory; if (playerInventory.player instanceof ServerPlayer) { trackedItems = ConfigurableItemStack.copyList(inventory.getItemStacks()); trackedFluids = ConfigurableFluidStack.copyList(inventory.getFluidStacks()); } } public void updateSlot(int index, Slot slot) { var existingSlot = getSlot(index); var slotGroup = slotGroups.remove(existingSlot); if (slotGroup != null) { slotGroups.put(slot, slotGroup); } this.slots.set(index, slot); } protected Slot addSlot(Slot slot, SlotGroup slotGroup) { slotGroups.put(slot, slotGroup); slotGroupIndices.add(slotGroup); return super.addSlot(slot); } @Override public void broadcastChanges() { if (playerInventory.player instanceof ServerPlayer player) { for (int i = 0; i < trackedItems.size(); i++) { if (!trackedItems.get(i).equals(inventory.getItemStacks().get(i))) { trackedItems.set(i, new ConfigurableItemStack(inventory.getItemStacks().get(i))); new UpdateItemSlotPacket(containerId, i, trackedItems.get(i)) .sendToClient(player); } } for (int i = 0; i < trackedFluids.size(); i++) { if (!trackedFluids.get(i).equals(inventory.getFluidStacks().get(i))) { trackedFluids.set(i, new ConfigurableFluidStack(inventory.getFluidStacks().get(i))); new UpdateFluidSlotPacket(containerId, i, trackedFluids.get(i)) .sendToClient(player); } } } super.broadcastChanges(); } @Override public void clicked(int i, int j, ClickType actionType, Player player) { if (i >= 0) { Slot slot = this.slots.get(i); if (slot instanceof ConfigurableFluidStack.ConfigurableFluidSlot fluidSlot) { if (actionType != ClickType.PICKUP) { return; } ConfigurableFluidStack fluidStack = fluidSlot.getConfStack(); if (lockingMode) { fluidStack.togglePlayerLock(); } else { fluidSlot.playerInteract(createCarriedSlotAccess(), player, true); } return; } else if (slot instanceof ConfigurableItemStack.ConfigurableItemSlot itemSlot) { if (lockingMode) { switch (actionType) { case PICKUP -> { ConfigurableItemStack itemStack = itemSlot.getConfStack(); itemStack.togglePlayerLock(getCarried().getItem()); } case QUICK_MOVE -> { // Try to move everything to player inventory insertItem(itemSlot, 0, PLAYER_SLOTS, true); // Lock to air if empty if (slot.getItem().isEmpty()) { itemSlot.getConfStack().playerLock(Items.AIR, Simulation.ACT); } } } return; } } } super.clicked(i, j, actionType, player); } @Override public final ItemStack quickMoveStack(Player player, int slotIndex) { handleShiftClick(player, slotIndex); return ItemStack.EMPTY; } protected void handleShiftClick(Player player, int slotIndex) { Slot slot = this.slots.get(slotIndex); if (slot.hasItem() && slot.mayPickup(player)) { if (slotIndex < PLAYER_SLOTS) { // from player to container inventory // try to shift-click fluid first var ctx = SlotAccess.forContainer(player.getInventory(), slot.getContainerSlot()); for (var maybeFluidSlot : slots) { if (maybeFluidSlot instanceof ConfigurableFluidStack.ConfigurableFluidSlot fluidSlot && fluidSlot.playerInteract(ctx, player, false)) { return; } } // move by slot group for (var group : slotGroupIndices) { if (this.insertItem(slot, PLAYER_SLOTS, this.slots.size(), false, s -> slotGroups.get(s) == group)) { return; } } if (slotIndex < 27) { // inside inventory this.insertItem(slot, 27, 36, false);// toolbar } else { this.insertItem(slot, 0, 27, false); } } else { // from container inventory to player this.insertItem(slot, 0, PLAYER_SLOTS, true); } } } @Deprecated @Override protected boolean moveItemStackTo(ItemStack stack, int startIndex, int endIndex, boolean fromLast) { throw new UnsupportedOperationException("Don't use this shit, use the one below instead."); } // Rewrite of ScreenHandler's buggy, long and shitty logic. /** * @return True if something was inserted. */ protected boolean insertItem(Slot sourceSlot, int startIndex, int endIndex, boolean fromLast) { return insertItem(sourceSlot, startIndex, endIndex, fromLast, s -> true); } protected boolean insertItem(Slot sourceSlot, int startIndex, int endIndex, boolean fromLast, Predicate<Slot> filter) { boolean insertedSomething = false; for (int iter = 0; iter < 2; ++iter) { boolean allowEmptySlots = iter == 1; // iteration 0 only allows insertion into existing slots int i = fromLast ? endIndex - 1 : startIndex; while (0 <= i && i < endIndex && !sourceSlot.getItem().isEmpty()) { Slot targetSlot = getSlot(i); ItemStack sourceStack = sourceSlot.getItem(); ItemStack targetStack = targetSlot.getItem(); if (filter.test(targetSlot) && targetSlot.mayPlace(sourceStack) && ((allowEmptySlots && targetStack.isEmpty()) || ItemStack.isSameItemSameComponents(targetStack, sourceStack))) { int maxInsert = targetSlot.getMaxStackSize(sourceStack) - targetStack.getCount(); if (maxInsert > 0) { ItemStack newTargetStack = sourceStack.split(maxInsert); newTargetStack.grow(targetStack.getCount()); targetSlot.set(newTargetStack); sourceSlot.setChanged(); insertedSomething = true; } } if (fromLast) { --i; } else { ++i; } } } return insertedSomething; } /** * Return true if any slot is player locked, false otherwise. */ public boolean hasUnlockedSlot() { for (var slot : slots) { if (slot instanceof ConfigurableItemStack.ConfigurableItemSlot cis) { if (!cis.getConfStack().playerLocked && cis.getConfStack().playerLockable) { return true; } } if (slot instanceof ConfigurableFluidStack.ConfigurableFluidSlot cfs) { if (!cfs.getConfStack().playerLocked && cfs.getConfStack().playerLockable) { return true; } } } return false; } public void lockAll(boolean lock) { for (var slot : slots) { if (slot instanceof ConfigurableItemStack.ConfigurableItemSlot cis) { if (cis.getConfStack().playerLocked != lock) { cis.getConfStack().togglePlayerLock(); } } if (slot instanceof ConfigurableFluidStack.ConfigurableFluidSlot cfs) { if (cfs.getConfStack().playerLocked != lock) { cfs.getConfStack().togglePlayerLock(); } } } } }
1
0.922787
1
0.922787
game-dev
MEDIA
0.973543
game-dev
0.932491
1
0.932491
iliakan/javascript-tutorial-cn-old
1,083
1-js/07-object-oriented-programming/13-mixins/head.html
<script> let eventMixin = { /** * Subscribe to event, usage: * menu.on('select', function(item) { ... } */ on(eventName, handler) { if (!this._eventHandlers) this._eventHandlers = {}; if (!this._eventHandlers[eventName]) { this._eventHandlers[eventName] = []; } this._eventHandlers[eventName].push(handler); }, /** * Cancel the subscription, usage: * menu.off('select', handler) */ off(eventName, handler) { let handlers = this._eventHandlers && this._eventHandlers[eventName]; if (!handlers) return; for(let i = 0; i < handlers.length; i++) { if (handlers[i] == handler) { handlers.splice(i--, 1); } } }, /** * Generate the event and attach the data to it * this.trigger('select', data1, data2); */ trigger(eventName, ...args) { if (!this._eventHandlers || !this._eventHandlers[eventName]) { return; // no handlers for that event name } // call the handlers this._eventHandlers[eventName].forEach(handler => handler.apply(this, args)); } }; </script>
1
0.744883
1
0.744883
game-dev
MEDIA
0.325015
game-dev
0.749413
1
0.749413
vu-luong/ezy-smashers
3,694
client-unity/Assets/TextMesh Pro/Examples & Extras/Scripts/Benchmark03.cs
using UnityEngine; using System.Collections; using UnityEngine.TextCore.LowLevel; namespace TMPro.Examples { public class Benchmark03 : MonoBehaviour { public enum BenchmarkType { TMP_SDF_MOBILE = 0, TMP_SDF__MOBILE_SSD = 1, TMP_SDF = 2, TMP_BITMAP_MOBILE = 3, TEXTMESH_BITMAP = 4 } public int NumberOfSamples = 100; public BenchmarkType Benchmark; public Font SourceFont; void Awake() { } void Start() { TMP_FontAsset fontAsset = null; // Create Dynamic Font Asset for the given font file. switch (Benchmark) { case BenchmarkType.TMP_SDF_MOBILE: fontAsset = TMP_FontAsset.CreateFontAsset(SourceFont, 90, 9, GlyphRenderMode.SDFAA, 256, 256, AtlasPopulationMode.Dynamic); break; case BenchmarkType.TMP_SDF__MOBILE_SSD: fontAsset = TMP_FontAsset.CreateFontAsset(SourceFont, 90, 9, GlyphRenderMode.SDFAA, 256, 256, AtlasPopulationMode.Dynamic); fontAsset.material.shader = Shader.Find("TextMeshPro/Mobile/Distance Field SSD"); break; case BenchmarkType.TMP_SDF: fontAsset = TMP_FontAsset.CreateFontAsset(SourceFont, 90, 9, GlyphRenderMode.SDFAA, 256, 256, AtlasPopulationMode.Dynamic); fontAsset.material.shader = Shader.Find("TextMeshPro/Distance Field"); break; case BenchmarkType.TMP_BITMAP_MOBILE: fontAsset = TMP_FontAsset.CreateFontAsset(SourceFont, 90, 9, GlyphRenderMode.SMOOTH, 256, 256, AtlasPopulationMode.Dynamic); break; } for (int i = 0; i < NumberOfSamples; i++) { switch (Benchmark) { case BenchmarkType.TMP_SDF_MOBILE: case BenchmarkType.TMP_SDF__MOBILE_SSD: case BenchmarkType.TMP_SDF: case BenchmarkType.TMP_BITMAP_MOBILE: { GameObject go = new GameObject(); go.transform.position = new Vector3(0, 1.2f, 0); TextMeshPro textComponent = go.AddComponent<TextMeshPro>(); textComponent.font = fontAsset; textComponent.fontSize = 128; textComponent.text = "@"; textComponent.alignment = TextAlignmentOptions.Center; textComponent.color = new Color32(255, 255, 0, 255); if (Benchmark == BenchmarkType.TMP_BITMAP_MOBILE) textComponent.fontSize = 132; } break; case BenchmarkType.TEXTMESH_BITMAP: { GameObject go = new GameObject(); go.transform.position = new Vector3(0, 1.2f, 0); TextMesh textMesh = go.AddComponent<TextMesh>(); textMesh.GetComponent<Renderer>().sharedMaterial = SourceFont.material; textMesh.font = SourceFont; textMesh.anchor = TextAnchor.MiddleCenter; textMesh.fontSize = 130; textMesh.color = new Color32(255, 255, 0, 255); textMesh.text = "@"; } break; } } } } }
1
0.662761
1
0.662761
game-dev
MEDIA
0.891805
game-dev
0.986072
1
0.986072
OpenMods/OpenBlocks
3,076
src/main/java/openblocks/common/entity/EntitySmoothMove.java
package openblocks.common.entity; import net.minecraft.entity.Entity; import net.minecraft.entity.MoverType; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; public abstract class EntitySmoothMove extends Entity { public class MoveSmoother { private final double damp; private final double cutoff; private final double panicLengthSq; private final double minimalLengthSq; private double targetX; private double targetY; private double targetZ; public MoveSmoother(double damp, double cutoff, double panicLength, double minimalLength) { this.damp = damp; this.cutoff = cutoff; this.panicLengthSq = panicLength * panicLength; this.minimalLengthSq = minimalLength * minimalLength; } protected boolean shouldJump(double x, double y, double z) { double dx = x - posX; double dy = y - posY; double dz = z - posZ; double lenSq = dx * dx + dy * dy + dz * dz; return shouldJump(lenSq); } private boolean shouldJump(double lenSq) { return (lenSq > panicLengthSq || lenSq < minimalLengthSq); } public void setTarget(Vec3d position) { setTarget(position.x, position.y, position.z); } public void setTarget(double targetX, double targetY, double targetZ) { if (!isPositionValid || shouldJump(targetX, targetY, targetZ)) { setPositionRaw(targetX, targetY, targetZ); motionX = motionY = motionZ = 0; } this.targetX = targetX; this.targetY = targetY; this.targetZ = targetZ; } public void update() { double dx = targetX - posX; double dy = targetY - posY; double dz = targetZ - posZ; final double lenSq = dx * dx + dy * dy + dz * dz; if (shouldJump(lenSq)) { setPositionRaw(targetX, targetY, targetZ); motionX = motionY = motionZ = 0; } else { if (lenSq > cutoff * cutoff) { double scale = cutoff / Math.sqrt(lenSq); dx *= scale; dy *= scale; dz *= scale; } move(MoverType.SELF, motionX + dx * damp, motionY + dy * damp, motionZ + dz * damp); } } } protected final MoveSmoother smoother; private boolean isPositionValid; public EntitySmoothMove(World world) { super(world); smoother = createSmoother(world.isRemote); } protected MoveSmoother createSmoother(boolean isRemote) { return isRemote? new MoveSmoother(0.25, 1.0, 8.0, 0.01) : new MoveSmoother(0.5, 5.0, 128.0, 0.01); } private boolean isFullyInitialized() { // may be null for calls made in superclass return smoother != null; } private void setPositionRaw(double x, double y, double z) { // ignore dummy position set in super constructor isPositionValid = isFullyInitialized(); super.setPosition(x, y, z); } @Override public void setPosition(double x, double y, double z) { if (isFullyInitialized()) smoother.setTarget(x, y, z); else setPositionRaw(x, y, z); } protected void updatePrevPosition() { prevDistanceWalkedModified = distanceWalkedModified; prevPosX = posX; prevPosY = posY; prevPosZ = posZ; prevRotationPitch = this.rotationPitch; prevRotationYaw = this.rotationYaw; } }
1
0.807103
1
0.807103
game-dev
MEDIA
0.954454
game-dev
0.942041
1
0.942041
dorisoy/Dorisoy.Pan
1,107
Client/Dorisoy.Pan/Services/Document/IPhysicalFolderService.cs
namespace Dorisoy.PanClient.Services; public interface IPhysicalFolderService { Task<ServiceResult<PhysicalFolder>> AddAsync(PhysicalFolder entity); Task AddRangeAsync(List<PhysicalFolder> physicalFolders); Task<ServiceResult<PhysicalFolderModel>> AddAsync(PhysicalFolderModel model); IObservable<IChangeSet<PhysicalFolderModel, Guid>> Connect(); Task DeleteAsync(PhysicalFolderModel model); Task<string> GetParentFolderPath(Guid childId); Task<string> GetParentOriginalFolderPath(Guid childId); Task<List<HierarchyFolder>> GetParentsHierarchyById(Guid id); Task<List<PhysicalFolderModel>> GetPhysicalFolders(); bool PhysicalFoldernameIsFree(Guid id, string physicalFoldername); Task<List<HierarchyFolder>> GetChildsHierarchyById(Guid id); Task<ServiceResult<PhysicalFolderModel>> UpdateAsync(PhysicalFolderModel model); Task<PhysicalFolderModel> ExistingPhysicalFolder(string name, Guid physicalFolderId, Guid userId); Task<ServiceResult<VirtualFolderInfoModel>> AddFolder(string name, Guid virtualParentId, Guid? physicalFolderId, Guid userId); }
1
0.837026
1
0.837026
game-dev
MEDIA
0.595782
game-dev
0.873159
1
0.873159
JetBoom/zombiesurvival
1,733
gamemodes/zombiesurvival/entities/weapons/weapon_zs_crowbar.lua
AddCSLuaFile() SWEP.PrintName = "Crowbar" SWEP.Description = "An effective and fast swinging melee weapon, the crowbar also has the ability to instantly kill headcrabs." if CLIENT then SWEP.ViewModelFOV = 65 end SWEP.Base = "weapon_zs_basemelee" SWEP.ViewModel = "models/weapons/c_crowbar.mdl" SWEP.WorldModel = "models/weapons/w_crowbar.mdl" SWEP.UseHands = true SWEP.HoldType = "melee" SWEP.DamageType = DMG_CLUB SWEP.MeleeDamage = 35 SWEP.OriginalMeleeDamage = SWEP.MeleeDamage SWEP.MeleeRange = 55 SWEP.MeleeSize = 1.5 SWEP.MeleeKnockBack = 110 SWEP.Primary.Delay = 0.7 SWEP.SwingTime = 0.4 SWEP.SwingRotation = Angle(30, -30, -30) SWEP.SwingHoldType = "grenade" SWEP.AllowQualityWeapons = true GAMEMODE:AttachWeaponModifier(SWEP, WEAPON_MODIFIER_MELEE_RANGE, 3) function SWEP:PlaySwingSound() self:EmitSound("Weapon_Crowbar.Single") end function SWEP:PlayHitSound() self:EmitSound("Weapon_Crowbar.Melee_HitWorld") end function SWEP:PlayHitFleshSound() self:EmitSound("Weapon_Crowbar.Melee_Hit") end function SWEP:PostOnMeleeHit(hitent, hitflesh, tr) if hitent:IsValid() and hitent:IsPlayer() and hitent:Team() == TEAM_UNDEAD and hitent:IsHeadcrab() and gamemode.Call("PlayerShouldTakeDamage", hitent, self:GetOwner()) then hitent:TakeSpecialDamage(hitent:Health(), DMG_DIRECT, self:GetOwner(), self, tr.HitPos) end end --[[function SWEP:OnMeleeHit(hitent, hitflesh, tr) if hitent:IsValid() and hitent:IsPlayer() and hitent:Team() == TEAM_UNDEAD and hitent:IsHeadcrab() and gamemode.Call("PlayerShouldTakeDamage", hitent, self:GetOwner()) then self.MeleeDamage = hitent:GetMaxHealth() * 10 end end function SWEP:PostOnMeleeHit(hitent, hitflesh, tr) self.MeleeDamage = self.OriginalMeleeDamage end]]
1
0.94134
1
0.94134
game-dev
MEDIA
0.982417
game-dev
0.767721
1
0.767721
smilehao/fog-of-war
2,433
Assets/Plugins/NGUI/Scripts/UI/UILocalize.cs
//---------------------------------------------- // NGUI: Next-Gen UI kit // Copyright © 2011-2016 Tasharen Entertainment //---------------------------------------------- using UnityEngine; /// <summary> /// Simple script that lets you localize a UIWidget. /// </summary> [ExecuteInEditMode] [RequireComponent(typeof(UIWidget))] [AddComponentMenu("NGUI/UI/Localize")] public class UILocalize : MonoBehaviour { /// <summary> /// Localization key. /// </summary> public string key; /// <summary> /// Manually change the value of whatever the localization component is attached to. /// </summary> public string value { set { if (!string.IsNullOrEmpty(value)) { UIWidget w = GetComponent<UIWidget>(); UILabel lbl = w as UILabel; UISprite sp = w as UISprite; if (lbl != null) { // If this is a label used by input, we should localize its default value instead UIInput input = NGUITools.FindInParents<UIInput>(lbl.gameObject); if (input != null && input.label == lbl) input.defaultText = value; else lbl.text = value; #if UNITY_EDITOR if (!Application.isPlaying) NGUITools.SetDirty(lbl); #endif } else if (sp != null) { UIButton btn = NGUITools.FindInParents<UIButton>(sp.gameObject); if (btn != null && btn.tweenTarget == sp.gameObject) btn.normalSprite = value; sp.spriteName = value; sp.MakePixelPerfect(); #if UNITY_EDITOR if (!Application.isPlaying) NGUITools.SetDirty(sp); #endif } } } } bool mStarted = false; /// <summary> /// Localize the widget on enable, but only if it has been started already. /// </summary> void OnEnable () { #if UNITY_EDITOR if (!Application.isPlaying) return; #endif if (mStarted) OnLocalize(); } /// <summary> /// Localize the widget on start. /// </summary> void Start () { #if UNITY_EDITOR if (!Application.isPlaying) return; #endif mStarted = true; OnLocalize(); } /// <summary> /// This function is called by the Localization manager via a broadcast SendMessage. /// </summary> void OnLocalize () { // If no localization key has been specified, use the label's text as the key if (string.IsNullOrEmpty(key)) { UILabel lbl = GetComponent<UILabel>(); if (lbl != null) key = lbl.text; } // If we still don't have a key, leave the value as blank if (!string.IsNullOrEmpty(key)) value = Localization.Get(key); } }
1
0.854869
1
0.854869
game-dev
MEDIA
0.748182
game-dev
0.978447
1
0.978447
AdultLink/TexturePanner
9,609
Assets/PostProcessing/Editor/PropertyDrawers/TrackballGroupDrawer.cs
using System.Collections.Generic; using System.Reflection; using UnityEngine; using UnityEngine.PostProcessing; namespace UnityEditor.PostProcessing { [CustomPropertyDrawer(typeof(TrackballGroupAttribute))] sealed class TrackballGroupDrawer : PropertyDrawer { static Material s_Material; const int k_MinWheelSize = 80; const int k_MaxWheelSize = 256; bool m_ResetState; // Cached trackball computation methods (for speed reasons) static Dictionary<string, MethodInfo> m_TrackballMethods = new Dictionary<string, MethodInfo>(); internal static int m_Size { get { int size = Mathf.FloorToInt(EditorGUIUtility.currentViewWidth / 3f) - 18; size = Mathf.Clamp(size, k_MinWheelSize, k_MaxWheelSize); return size; } } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { if (s_Material == null) s_Material = new Material(Shader.Find("Hidden/Post FX/UI/Trackball")) { hideFlags = HideFlags.HideAndDontSave }; position = new Rect(position.x, position.y, position.width / 3f, position.height); int size = m_Size; position.x += 5f; var enumerator = property.GetEnumerator(); while (enumerator.MoveNext()) { var prop = enumerator.Current as SerializedProperty; if (prop == null || prop.propertyType != SerializedPropertyType.Color) continue; OnWheelGUI(position, size, prop.Copy()); position.x += position.width; } } void OnWheelGUI(Rect position, int size, SerializedProperty property) { if (Event.current.type == EventType.Layout) return; var value = property.colorValue; float offset = value.a; var wheelDrawArea = position; wheelDrawArea.height = size; if (wheelDrawArea.width > wheelDrawArea.height) { wheelDrawArea.x += (wheelDrawArea.width - wheelDrawArea.height) / 2.0f; wheelDrawArea.width = position.height; } wheelDrawArea.width = wheelDrawArea.height; float hsize = size / 2f; float radius = 0.38f * size; Vector3 hsv; Color.RGBToHSV(value, out hsv.x, out hsv.y, out hsv.z); if (Event.current.type == EventType.Repaint) { float scale = EditorGUIUtility.pixelsPerPoint; // Wheel texture var oldRT = RenderTexture.active; var rt = RenderTexture.GetTemporary((int)(size * scale), (int)(size * scale), 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); s_Material.SetFloat("_Offset", offset); s_Material.SetFloat("_DisabledState", GUI.enabled ? 1f : 0.5f); s_Material.SetVector("_Resolution", new Vector2(size * scale, size * scale / 2f)); Graphics.Blit(null, rt, s_Material, EditorGUIUtility.isProSkin ? 0 : 1); RenderTexture.active = oldRT; GUI.DrawTexture(wheelDrawArea, rt); RenderTexture.ReleaseTemporary(rt); // Thumb var thumbPos = Vector2.zero; float theta = hsv.x * (Mathf.PI * 2f); float len = hsv.y * radius; thumbPos.x = Mathf.Cos(theta + (Mathf.PI / 2f)); thumbPos.y = Mathf.Sin(theta - (Mathf.PI / 2f)); thumbPos *= len; var thumbSize = FxStyles.wheelThumbSize; var thumbSizeH = thumbSize / 2f; FxStyles.wheelThumb.Draw(new Rect(wheelDrawArea.x + hsize + thumbPos.x - thumbSizeH.x, wheelDrawArea.y + hsize + thumbPos.y - thumbSizeH.y, thumbSize.x, thumbSize.y), false, false, false, false); } var bounds = wheelDrawArea; bounds.x += hsize - radius; bounds.y += hsize - radius; bounds.width = bounds.height = radius * 2f; hsv = GetInput(bounds, hsv, radius); value = Color.HSVToRGB(hsv.x, hsv.y, 1f); value.a = offset; // Luminosity booster position = wheelDrawArea; float oldX = position.x; float oldW = position.width; position.y += position.height + 4f; position.x += (position.width - (position.width * 0.75f)) / 2f; position.width = position.width * 0.75f; position.height = EditorGUIUtility.singleLineHeight; value.a = GUI.HorizontalSlider(position, value.a, -1f, 1f); // Advanced controls var data = Vector3.zero; if (TryGetDisplayValue(value, property, out data)) { position.x = oldX; position.y += position.height; position.width = oldW / 3f; using (new EditorGUI.DisabledGroupScope(true)) { GUI.Label(position, data.x.ToString("F2"), EditorStyles.centeredGreyMiniLabel); position.x += position.width; GUI.Label(position, data.y.ToString("F2"), EditorStyles.centeredGreyMiniLabel); position.x += position.width; GUI.Label(position, data.z.ToString("F2"), EditorStyles.centeredGreyMiniLabel); position.x += position.width; } } // Title position.x = oldX; position.y += position.height; position.width = oldW; GUI.Label(position, property.displayName, EditorStyles.centeredGreyMiniLabel); if (m_ResetState) { value = Color.clear; m_ResetState = false; } property.colorValue = value; } bool TryGetDisplayValue(Color color, SerializedProperty property, out Vector3 output) { output = Vector3.zero; MethodInfo method; if (!m_TrackballMethods.TryGetValue(property.name, out method)) { var field = ReflectionUtils.GetFieldInfoFromPath(property.serializedObject.targetObject, property.propertyPath); if (!field.IsDefined(typeof(TrackballAttribute), false)) return false; var attr = (TrackballAttribute)field.GetCustomAttributes(typeof(TrackballAttribute), false)[0]; const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; method = typeof(ColorGradingComponent).GetMethod(attr.method, flags); m_TrackballMethods.Add(property.name, method); } if (method == null) return false; output = (Vector3)method.Invoke(property.serializedObject.targetObject, new object[] { color }); return true; } static readonly int k_ThumbHash = "colorWheelThumb".GetHashCode(); Vector3 GetInput(Rect bounds, Vector3 hsv, float radius) { var e = Event.current; var id = GUIUtility.GetControlID(k_ThumbHash, FocusType.Passive, bounds); var mousePos = e.mousePosition; var relativePos = mousePos - new Vector2(bounds.x, bounds.y); if (e.type == EventType.MouseDown && GUIUtility.hotControl == 0 && bounds.Contains(mousePos)) { if (e.button == 0) { var center = new Vector2(bounds.x + radius, bounds.y + radius); float dist = Vector2.Distance(center, mousePos); if (dist <= radius) { e.Use(); GetWheelHueSaturation(relativePos.x, relativePos.y, radius, out hsv.x, out hsv.y); GUIUtility.hotControl = id; GUI.changed = true; } } else if (e.button == 1) { e.Use(); GUI.changed = true; m_ResetState = true; } } else if (e.type == EventType.MouseDrag && e.button == 0 && GUIUtility.hotControl == id) { e.Use(); GUI.changed = true; GetWheelHueSaturation(relativePos.x, relativePos.y, radius, out hsv.x, out hsv.y); } else if (e.rawType == EventType.MouseUp && e.button == 0 && GUIUtility.hotControl == id) { e.Use(); GUIUtility.hotControl = 0; } return hsv; } void GetWheelHueSaturation(float x, float y, float radius, out float hue, out float saturation) { float dx = (x - radius) / radius; float dy = (y - radius) / radius; float d = Mathf.Sqrt(dx * dx + dy * dy); hue = Mathf.Atan2(dx, -dy); hue = 1f - ((hue > 0) ? hue : (Mathf.PI * 2f) + hue) / (Mathf.PI * 2f); saturation = Mathf.Clamp01(d); } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return m_Size + 4f * 2f + EditorGUIUtility.singleLineHeight * 3f; } } }
1
0.961823
1
0.961823
game-dev
MEDIA
0.575933
game-dev,desktop-app
0.996672
1
0.996672
SteamRE/Steam4NET
1,828
Steam4NET/Autogen/ISteamRemoteStorage004.cs
// This file is automatically generated. using System; using System.Text; using System.Runtime.InteropServices; using Steam4NET.Attributes; namespace Steam4NET { [InterfaceVersion("STEAMREMOTESTORAGE_INTERFACE_VERSION004")] public interface ISteamRemoteStorage004 { [VTableSlot(0)] bool FileWrite(string pchFile, Byte[] pvData, Int32 cubData); [VTableSlot(1)] Int32 FileRead(string pchFile, Byte[] pvData, Int32 cubDataToRead); [VTableSlot(2)] bool FileForget(string pchFile); [VTableSlot(3)] bool FileDelete(string pchFile); [VTableSlot(4)] UInt64 FileShare(string pchFile); [VTableSlot(5)] bool SetSyncPlatforms(string pchFile, ERemoteStoragePlatform eRemoteStoragePlatform); [VTableSlot(6)] bool FileExists(string pchFile); [VTableSlot(7)] bool FilePersisted(string pchFile); [VTableSlot(8)] Int32 GetFileSize(string pchFile); [VTableSlot(9)] Int64 GetFileTimestamp(string pchFile); [VTableSlot(10)] ERemoteStoragePlatform GetSyncPlatforms(string pchFile); [VTableSlot(11)] Int32 GetFileCount(); [VTableSlot(12)] string GetFileNameAndSize(Int32 iFile, ref Int32 pnFileSizeInBytes); [VTableSlot(13)] bool GetQuota(ref Int32 pnTotalBytes, ref Int32 puAvailableBytes); [VTableSlot(14)] bool IsCloudEnabledForAccount(); [VTableSlot(15)] bool IsCloudEnabledForApp(); [VTableSlot(16)] void SetCloudEnabledForApp(bool bEnabled); [VTableSlot(17)] UInt64 UGCDownload(UInt64 hContent); [VTableSlot(18)] bool GetUGCDetails(UInt64 hContent, ref UInt32 pnAppID, StringBuilder ppchName, ref Int32 pnFileSizeInBytes, ref CSteamID pSteamIDOwner); [VTableSlot(19)] Int32 UGCRead(UInt64 hContent, Byte[] pvData, Int32 cubDataToRead); [VTableSlot(20)] Int32 GetCachedUGCCount(); [VTableSlot(21)] UInt64 GetCachedUGCHandle(Int32 iCachedContent); }; }
1
0.936108
1
0.936108
game-dev
MEDIA
0.316932
game-dev
0.706971
1
0.706971
mattgodbolt/xania
3,944
src/entity_balance.cpp
/*************************************************************************/ /* Xania (M)ulti(U)ser(D)ungeon server source code */ /* (C) 1995-2000 Xania Development Team */ /* See merc.h and README for original copyrights */ /*************************************************************************/ #include "AFFECT_DATA.hpp" #include "Char.hpp" #include "Logging.hpp" #include "Object.hpp" #include "ObjectIndex.hpp" #include "ObjectType.hpp" #include "ObjectWearFlag.hpp" #include "WeaponFlag.hpp" #include "common/BitOps.hpp" #include "db.h" #include "handler.hpp" #include "string_utils.hpp" #include <fmt/format.h> #include <range/v3/numeric/accumulate.hpp> #include <range/v3/view/transform.hpp> namespace { void objectbug(std::string_view str, ObjectIndex *obj, const Logger &logger) { logger.log_string("obj> {} (#{}): {}", obj->short_descr, obj->vnum, str); } /* report_object, takes an object_index_data obj and returns the 'worth' of an object in points. */ int report_object(const Object *object, const Logger &logger) { int averagedam, allowedaverage; ObjectIndex *obj = object->objIndex; auto value = ranges::accumulate(obj->affected | ranges::views::transform(&AFFECT_DATA::worth), AFFECT_DATA::Value{}); /* Weapons are allowed 1 hit and 1 dam for each point */ auto worth = value.worth + (obj->type == ObjectType::Weapon ? (value.hit + value.damage) / 2 : value.hit + value.damage); /* Object specific routines */ switch (obj->type) { case ObjectType::Weapon: /* Calculate the damage allowed and actual */ allowedaverage = (object->level / 2) + 4; if (check_enum_bit(obj->value[4], WeaponFlag::TwoHands) && check_enum_bit(obj->wear_flags, ObjectWearFlag::TwoHands)) allowedaverage += std::max(1, (allowedaverage) / 20); averagedam = (obj->value[1] * obj->value[2] + obj->value[1]) / 2; if ((averagedam > allowedaverage)) { objectbug("average damage too high", obj, logger); } /* Add to worth for each weapon type */ if (check_enum_bit(obj->value[4], WeaponFlag::Flaming)) worth++; if (check_enum_bit(obj->value[4], WeaponFlag::Frost)) worth++; if (check_enum_bit(obj->value[4], WeaponFlag::Vampiric)) worth++; if (check_enum_bit(obj->value[4], WeaponFlag::Sharp)) worth++; if (check_enum_bit(obj->value[4], WeaponFlag::Vorpal)) worth++; break; case ObjectType::Potion: case ObjectType::Pill: case ObjectType::Scroll: case ObjectType::Bomb: case ObjectType::Staff: if ((obj->value[4] > (object->level + (std::max(5, obj->level / 10))))) objectbug("level of spell too high", obj, logger); break; default: break; } if (worth > ((obj->level / 10) + 1)) { objectbug(fmt::format("points too high: has {} points (max should be {})", worth, ((obj->level / 10) + 1)), obj, logger); } return worth; } } void do_immworth(Char *ch, ArgParser args) { const auto *obj = get_obj_world(ch, args.shift()); if (!obj) { ch->send_line("No object found."); return; } const auto worth = report_object(obj, ch->mud_.logger()); const auto shouldbe = ((obj->level / 10) + 1); if (worth == shouldbe) { ch->send_line("Object '{}' has {} point(s) - exactly right.", obj->objIndex->short_descr, worth); } else if (worth > shouldbe) { ch->send_line("Object '{}' has {} point(s), {} points |Rtoo high|w.", obj->objIndex->short_descr, worth, worth - shouldbe); } else { ch->send_line("Object '{}' has {} point(s), within the {} point maximum.", obj->objIndex->short_descr, worth, shouldbe); } }
1
0.855441
1
0.855441
game-dev
MEDIA
0.554793
game-dev
0.897623
1
0.897623
GregTechCE/GregTech
2,433
src/main/java/gregtech/api/recipes/machines/RecipeMapFormingPress.java
package gregtech.api.recipes.machines; import gregtech.api.recipes.MatchingMode; import gregtech.api.recipes.Recipe; import gregtech.api.recipes.RecipeMap; import gregtech.api.recipes.builders.SimpleRecipeBuilder; import gregtech.api.recipes.ingredients.NBTIngredient; import gregtech.api.util.GTUtility; import gregtech.common.items.MetaItems; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; import javax.annotation.Nullable; import java.util.List; public class RecipeMapFormingPress extends RecipeMap<SimpleRecipeBuilder> { public RecipeMapFormingPress(String unlocalizedName, int minInputs, int maxInputs, int minOutputs, int maxOutputs, int minFluidInputs, int maxFluidInputs, int minFluidOutputs, int maxFluidOutputs, int amperage, SimpleRecipeBuilder defaultRecipe) { super(unlocalizedName, minInputs, maxInputs, minOutputs, maxOutputs, minFluidInputs, maxFluidInputs, minFluidOutputs, maxFluidOutputs, defaultRecipe); } @Override @Nullable public Recipe findRecipe(long voltage, List<ItemStack> inputs, List<FluidStack> fluidInputs, int outputFluidTankCapacity, MatchingMode mode) { Recipe recipe = super.findRecipe(voltage, inputs, fluidInputs, outputFluidTankCapacity, mode); if (inputs.size() < 2 || inputs.get(0).isEmpty() || inputs.get(1).isEmpty()) { return recipe; } if (recipe == null) { ItemStack moldStack = ItemStack.EMPTY; ItemStack itemStack = ItemStack.EMPTY; for (ItemStack inputStack : inputs) { if (MetaItems.SHAPE_MOLD_NAME.getStackForm().isItemEqual(moldStack)) { moldStack = inputStack; } else { itemStack = inputStack; } } if (!moldStack.isEmpty() && !itemStack.isEmpty()) { ItemStack output = GTUtility.copyAmount(1, itemStack); output.setStackDisplayName(inputs.get(0).getDisplayName()); return this.recipeBuilder() .notConsumable(new NBTIngredient(moldStack)) //recipe is reusable as long as mold stack matches .inputs(GTUtility.copyAmount(1, itemStack)) .outputs(output) .duration(40).EUt(4) .build().getResult(); } return null; } return recipe; } }
1
0.757187
1
0.757187
game-dev
MEDIA
0.707263
game-dev
0.87588
1
0.87588
mono/CocosSharp
22,532
box2d/Dynamics/b2Island.cs
/* * Copyright (c) 2006-2011 Erin Catto http://www.box2d.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. */ /* Position Correction Notes ========================= I tried the several algorithms for position correction of the 2D revolute joint. I looked at these systems: - simple pendulum (1m diameter sphere on massless 5m stick) with initial angular velocity of 100 rad/s. - suspension bridge with 30 1m long planks of length 1m. - multi-link chain with 30 1m long links. Here are the algorithms: Baumgarte - A fraction of the position error is added to the velocity error. There is no separate position solver. Pseudo Velocities - After the velocity solver and position integration, the position error, Jacobian, and effective mass are recomputed. Then the velocity constraints are solved with pseudo velocities and a fraction of the position error is added to the pseudo velocity error. The pseudo velocities are initialized to zero and there is no warm-starting. After the position solver, the pseudo velocities are added to the positions. This is also called the First Order World method or the Position LCP method. Modified Nonlinear Gauss-Seidel (NGS) - Like Pseudo Velocities except the position error is re-computed for each constraint and the positions are updated after the constraint is solved. The radius vectors (aka Jacobians) are re-computed too (otherwise the algorithm has horrible instability). The pseudo velocity states are not needed because they are effectively zero at the beginning of each iteration. Since we have the current position error, we allow the iterations to terminate early if the error becomes smaller than b2_linearSlop. Full NGS or just NGS - Like Modified NGS except the effective mass are re-computed each time a constraint is solved. Here are the results: Baumgarte - this is the cheapest algorithm but it has some stability problems, especially with the bridge. The chain links separate easily close to the root and they jitter as they struggle to pull together. This is one of the most common methods in the field. The big drawback is that the position correction artificially affects the momentum, thus leading to instabilities and false bounce. I used a bias factor of 0.2. A larger bias factor makes the bridge less stable, a smaller factor makes joints and contacts more spongy. Pseudo Velocities - the is more stable than the Baumgarte method. The bridge is stable. However, joints still separate with large angular velocities. Drag the simple pendulum in a circle quickly and the joint will separate. The chain separates easily and does not recover. I used a bias factor of 0.2. A larger value lead to the bridge collapsing when a heavy cube drops on it. Modified NGS - this algorithm is better in some ways than Baumgarte and Pseudo Velocities, but in other ways it is worse. The bridge and chain are much more stable, but the simple pendulum goes unstable at high angular velocities. Full NGS - stable in all tests. The joints display good stiffness. The bridge still sags, but this is better than infinite forces. Recommendations Pseudo Velocities are not really worthwhile because the bridge and chain cannot recover from joint separation. In other cases the benefit over Baumgarte is small. Modified NGS is not a robust method for the revolute joint due to the violent instability seen in the simple pendulum. Perhaps it is viable with other constraint types, especially scalar constraints where the effective mass is a scalar. This leaves Baumgarte and Full NGS. Baumgarte has small, but manageable instabilities and is very fast. I don't think we can escape Baumgarte, especially in highly demanding cases where high constraint fidelity is not needed. Full NGS is robust and easy on the eyes. I recommend this as an option for higher fidelity simulation and certainly for suspension bridges and long chains. Full NGS might be a good choice for ragdolls, especially motorized ragdolls where joint separation can be problematic. The number of NGS iterations can be reduced for better performance without harming robustness much. Each joint in a can be handled differently in the position solver. So I recommend a system where the user can select the algorithm on a per joint basis. I would probably default to the slower Full NGS and let the user select the faster Baumgarte method in performance critical scenarios. */ /* Cache Performance The Box2D solvers are dominated by cache misses. Data structures are designed to increase the number of cache hits. Much of misses are due to random access to body data. The constraint structures are iterated over linearly, which leads to few cache misses. The bodies are not accessed during iteration. Instead read only data, such as the mass values are stored with the constraints. The mutable data are the constraint impulses and the bodies velocities/positions. The impulses are held inside the constraint structures. The body velocities/positions are held in compact, temporary arrays to increase the number of cache hits. Linear and angular velocity are stored in a single array since multiple arrays lead to multiple misses. */ /* 2D Rotation R = [cos(theta) -sin(theta)] [sin(theta) cos(theta) ] thetaDot = omega Let q1 = cos(theta), q2 = sin(theta). R = [q1 -q2] [q2 q1] q1Dot = -thetaDot * q2 q2Dot = thetaDot * q1 q1_new = q1_old - dt * w * q2 q2_new = q2_old + dt * w * q1 then normalize. This might be faster than computing sin+cos. However, we can compute sin+cos of the same angle fast. */ using System; using System.Diagnostics; using Box2D.Common; using Box2D.Collision; using Box2D.Dynamics.Contacts; using Box2D.Collision.Shapes; using Box2D.Dynamics.Joints; namespace Box2D.Dynamics { public class b2Island { public b2ContactListener m_listener; public b2Body[] m_bodies; public b2Contact[] m_contacts; public b2Joint[] m_joints; //public b2Position[] m_positions; //public b2Velocity[] m_velocities; public int m_bodyCount; public int m_jointCount; public int m_contactCount; public int m_bodyCapacity; public int m_contactCapacity; public int m_jointCapacity; public void Clear() { m_bodyCount = 0; m_contactCount = 0; m_jointCount = 0; } public void Add(b2Body body) { Debug.Assert(m_bodyCount < m_bodyCapacity); body.IslandIndex = m_bodyCount; m_bodies[m_bodyCount] = body; ++m_bodyCount; } public void Add(b2Contact contact) { Debug.Assert(m_contactCount < m_contactCapacity); m_contacts[m_contactCount++] = contact; } public void Add(b2Joint joint) { Debug.Assert(m_jointCount < m_jointCapacity); m_joints[m_jointCount++] = joint; } public b2Island( int bodyCapacity, int contactCapacity, int jointCapacity, b2ContactListener listener) { Reset(bodyCapacity, contactCapacity, jointCapacity, listener); } public void Reset(int bodyCapacity, int contactCapacity, int jointCapacity, b2ContactListener listener) { if (m_bodyCapacity < bodyCapacity) { m_bodyCapacity = 128; while (m_bodyCapacity < bodyCapacity) m_bodyCapacity <<= 1; m_bodies = new b2Body[m_bodyCapacity]; //m_velocities = new b2Velocity[m_bodyCapacity]; //m_positions = new b2Position[m_bodyCapacity]; } if (m_contactCapacity < contactCapacity) { m_contactCapacity = 128; while (m_contactCapacity < contactCapacity) m_contactCapacity <<= 1; m_contacts = new b2Contact[m_contactCapacity]; } if (m_jointCapacity < jointCapacity) { m_jointCapacity = 128; while (m_jointCapacity < jointCapacity) m_jointCapacity <<= 1; m_joints = new b2Joint[m_jointCapacity]; } m_bodyCount = 0; m_contactCount = 0; m_jointCount = 0; m_listener = listener; } #if PROFILING public void Solve(ref b2Profile profile, b2TimeStep step, b2Vec2 gravity, bool allowSleep) #else public void Solve(b2TimeStep step, b2Vec2 gravity, bool allowSleep) #endif { #if PROFILING b2Timer timer = new b2Timer(); #endif float h = step.dt; // Integrate velocities and apply damping. Initialize the body state. for (int i = 0, count = m_bodyCount; i < count; ++i) { b2Body b = m_bodies[i]; b2Vec2 c = b.Sweep.c; float a = b.Sweep.a; b2Vec2 v = b.LinearVelocity; float w = b.AngularVelocity; // Store positions for continuous collision. b.Sweep.c0 = b.Sweep.c; b.Sweep.a0 = b.Sweep.a; if (b.BodyType == b2BodyType.b2_dynamicBody) { // Integrate velocities. v += h * (b.GravityScale * gravity + b.InvertedMass * b.Force); w += h * b.InvertedI * b.Torque; // Apply damping. // ODE: dv/dt + c * v = 0 // Solution: v(t) = v0 * exp(-c * t) // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt) // v2 = exp(-c * dt) * v1 // Taylor expansion: // v2 = (1.0f - c * dt) * v1 v *= b2Math.b2Clamp(1.0f - h * b.LinearDamping, 0.0f, 1.0f); w *= b2Math.b2Clamp(1.0f - h * b.AngularDamping, 0.0f, 1.0f); } b.InternalPosition.c = c; b.InternalPosition.a = a; b.InternalVelocity.v = v; b.InternalVelocity.w = w; } #if PROFILING timer.Reset(); #endif // Solver data b2SolverData solverData = new b2SolverData(); solverData.step = step; //solverData.positions = m_positions; //solverData.velocities = m_velocities; // Initialize velocity constraints. b2ContactSolverDef contactSolverDef; contactSolverDef.step = step; contactSolverDef.contacts = m_contacts; contactSolverDef.count = m_contactCount; //contactSolverDef.positions = m_positions; //contactSolverDef.velocities = m_velocities; b2ContactSolver contactSolver = b2ContactSolver.Create(ref contactSolverDef); contactSolver.InitializeVelocityConstraints(); if (step.warmStarting) { contactSolver.WarmStart(); } for (int i = 0; i < m_jointCount; ++i) { m_joints[i].InitVelocityConstraints(solverData); } #if PROFILING profile.solveInit = timer.GetMilliseconds(); #endif // Solve velocity constraints #if PROFILING timer.Reset(); #endif for (int i = 0; i < step.velocityIterations; ++i) { for (int j = 0; j < m_jointCount; ++j) { m_joints[j].SolveVelocityConstraints(solverData); } contactSolver.SolveVelocityConstraints(); } // Store impulses for warm starting contactSolver.StoreImpulses(); #if PROFILING profile.solveVelocity = timer.GetMilliseconds(); #endif // Integrate positions for (int i = 0; i < m_bodyCount; ++i) { var b = m_bodies[i]; b2Vec2 c = b.InternalPosition.c; float a = b.InternalPosition.a; b2Vec2 v = b.InternalVelocity.v; float w = b.InternalVelocity.w; // Check for large velocities b2Vec2 translation = h * v; if (translation.LengthSquared /* b2Math.b2Dot(translation, translation)*/ > b2Settings.b2_maxTranslationSquared) { float ratio = b2Settings.b2_maxTranslation / translation.Length; v *= ratio; } float rotation = h * w; if (rotation * rotation > b2Settings.b2_maxRotationSquared) { float ratio = b2Settings.b2_maxRotation / Math.Abs(rotation); w *= ratio; } // Integrate c += h * v; a += h * w; b.InternalPosition.c = c; b.InternalPosition.a = a; b.InternalVelocity.v = v; b.InternalVelocity.w = w; } // Solve position constraints #if PROFILING timer.Reset(); #endif bool positionSolved = false; for (int i = 0; i < step.positionIterations; ++i) { bool contactsOkay = contactSolver.SolvePositionConstraints(); bool jointsOkay = true; for (int i2 = 0; i2 < m_jointCount; ++i2) { bool jointOkay = m_joints[i2].SolvePositionConstraints(solverData); jointsOkay = jointsOkay && jointOkay; } if (contactsOkay && jointsOkay) { // Exit early if the position errors are small. positionSolved = true; break; } } // Copy state buffers back to the bodies for (int i = 0; i < m_bodyCount; ++i) { b2Body body = m_bodies[i]; body.Sweep.c = body.InternalPosition.c; body.Sweep.a = body.InternalPosition.a; body.LinearVelocity = body.InternalVelocity.v; body.AngularVelocity = body.InternalVelocity.w; body.SynchronizeTransform(); } #if PROFILING profile.solvePosition = timer.GetMilliseconds(); #endif Report(contactSolver.m_constraints); if (allowSleep) { float minSleepTime = b2Settings.b2_maxFloat; float linTolSqr = b2Settings.b2_linearSleepTolerance * b2Settings.b2_linearSleepTolerance; float angTolSqr = b2Settings.b2_angularSleepTolerance * b2Settings.b2_angularSleepTolerance; for (int i = 0; i < m_bodyCount; ++i) { b2Body b = m_bodies[i]; if (b.BodyType == b2BodyType.b2_staticBody) { continue; } if ((b.BodyFlags & b2BodyFlags.e_autoSleepFlag) == 0 || b.AngularVelocity * b.AngularVelocity > angTolSqr || b2Math.b2Dot(ref b.m_linearVelocity, ref b.m_linearVelocity) > linTolSqr) { b.SleepTime = 0.0f; minSleepTime = 0.0f; } else { b.SleepTime = b.SleepTime + h; minSleepTime = Math.Min(minSleepTime, b.SleepTime); } } if (minSleepTime >= b2Settings.b2_timeToSleep && positionSolved) { for (int i = 0; i < m_bodyCount; ++i) { b2Body b = m_bodies[i]; b.SetAwake(false); } } } contactSolver.Free(); } public void SolveTOI(ref b2TimeStep subStep, int toiIndexA, int toiIndexB) { Debug.Assert(toiIndexA < m_bodyCount); Debug.Assert(toiIndexB < m_bodyCount); // Initialize the body state. for (int i = 0; i < m_bodyCount; ++i) { b2Body b = m_bodies[i]; b.InternalPosition.c = b.Sweep.c; b.InternalPosition.a = b.Sweep.a; b.InternalVelocity.v = b.LinearVelocity; b.InternalVelocity.w = b.AngularVelocity; } b2ContactSolverDef contactSolverDef; contactSolverDef.contacts = m_contacts; contactSolverDef.count = m_contactCount; contactSolverDef.step = subStep; //contactSolverDef.positions = m_positions; //contactSolverDef.velocities = m_velocities; b2ContactSolver contactSolver = b2ContactSolver.Create(ref contactSolverDef); // Solve position constraints. for (int i = 0; i < subStep.positionIterations; ++i) { bool contactsOkay = contactSolver.SolveTOIPositionConstraints(toiIndexA, toiIndexB); if (contactsOkay) { break; } } #if false // Is the new position really safe? for (int i = 0; i < m_contactCount; ++i) { b2Contact c = m_contacts[i]; b2Fixture fA = c.GetFixtureA(); b2Fixture fB = c.GetFixtureB(); b2Body bA = fA.Body; b2Body bB = fB.Body; int indexA = c.GetChildIndexA(); int indexB = c.GetChildIndexB(); b2DistanceInput input = new b2DistanceInput(); input.proxyA.Set(fA.Shape, indexA); input.proxyB.Set(fB.Shape, indexB); input.transformA = bA.Transform; input.transformB = bB.Transform; input.useRadii = false; b2DistanceOutput output; b2SimplexCache cache = new b2SimplexCache(); cache.count = 0; output = b2Distance(cache, input); if (output.distance == 0 || cache.count == 3) { cache.count += 0; } } #endif var bodyA = m_bodies[toiIndexA]; var bodyB = m_bodies[toiIndexB]; // Leap of faith to new safe state. bodyA.Sweep.c0 = bodyA.InternalPosition.c; bodyA.Sweep.a0 = bodyA.InternalPosition.a; bodyB.Sweep.c0 = bodyB.InternalPosition.c; bodyB.Sweep.a0 = bodyB.InternalPosition.a; // No warm starting is needed for TOI events because warm // starting impulses were applied in the discrete solver. contactSolver.InitializeVelocityConstraints(); // Solve velocity constraints. for (int i = 0; i < subStep.velocityIterations; ++i) { contactSolver.SolveVelocityConstraints(); } // Don't store the TOI contact forces for warm starting // because they can be quite large. float h = subStep.dt; // Integrate positions for (int i = 0, count = m_bodyCount; i < count; ++i) { var body = m_bodies[i]; b2Vec2 c = body.InternalPosition.c; float a = body.InternalPosition.a; b2Vec2 v = body.InternalVelocity.v; float w = body.InternalVelocity.w; // Check for large velocities b2Vec2 translation = h * v; if (b2Math.b2Dot(ref translation, ref translation) > b2Settings.b2_maxTranslationSquared) { float ratio = b2Settings.b2_maxTranslation / translation.Length; v *= ratio; } float rotation = h * w; if (rotation * rotation > b2Settings.b2_maxRotationSquared) { float ratio = b2Settings.b2_maxRotation / Math.Abs(rotation); w *= ratio; } // Integrate c += h * v; a += h * w; body.InternalPosition.c = c; body.InternalPosition.a = a; body.InternalVelocity.v = v; body.InternalVelocity.w = w; // Sync bodies body.Sweep.c = c; body.Sweep.a = a; body.LinearVelocity = v; body.AngularVelocity = w; body.SynchronizeTransform(); } Report(contactSolver.m_constraints); contactSolver.Free(); } //Memory Optimization b2ContactImpulse _impulse = b2ContactImpulse.Create(); public void Report(b2ContactConstraint[] constraints) { if (m_listener == null) { return; } //b2ContactImpulse impulse = b2ContactImpulse.Create(); var normals = _impulse.normalImpulses; var tangens = _impulse.tangentImpulses; for (int i = 0, count = m_contactCount; i < count; ++i) { b2Contact c = m_contacts[i]; var vc = constraints[i]; _impulse.count = vc.pointCount; for (int j = 0; j < vc.pointCount; ++j) { normals[j] = vc.points[j].normalImpulse; tangens[j] = vc.points[j].tangentImpulse; } m_listener.PostSolve(c, ref _impulse); } } } }
1
0.968073
1
0.968073
game-dev
MEDIA
0.573927
game-dev,scientific-computing
0.921047
1
0.921047
AElfProject/AElf
2,746
contract/AElf.Contracts.Consensus.AEDPoS/ConsensusCommandGeneration/Strategies/CommandStrategyBase.cs
using AElf.CSharp.Core; using AElf.Standards.ACS4; using Google.Protobuf.WellKnownTypes; namespace AElf.Contracts.Consensus.AEDPoS; public partial class AEDPoSContract { /// <summary> /// Basically provides some useful fields for other strategies. /// </summary> public abstract class CommandStrategyBase : ICommandStrategy { /// <summary> /// In AElf Main Chain, miner will produce 8 blocks (as fast as possible) during every time slot by default. /// </summary> private const int TinyBlocksCount = 8; /// <summary> /// The minimum interval between two blocks of same time slot. /// </summary> protected const int TinyBlockMinimumInterval = 50; protected readonly Timestamp CurrentBlockTime; protected readonly Round CurrentRound; protected readonly string Pubkey; protected CommandStrategyBase(Round currentRound, string pubkey, Timestamp currentBlockTime) { CurrentRound = currentRound; Pubkey = pubkey; CurrentBlockTime = currentBlockTime; } protected MinerInRound MinerInRound => CurrentRound.RealTimeMinersInformation[Pubkey]; protected int Order => CurrentRound.GetMiningOrder(Pubkey); protected int MiningInterval => CurrentRound.GetMiningInterval(); /// <summary> /// Producing time of every (tiny) block at most. /// </summary> private int TinyBlockSlotInterval => MiningInterval.Div(TinyBlocksCount); protected int MinersCount => CurrentRound.RealTimeMinersInformation.Count; /// <summary> /// Give 3/5 of producing time for mining by default. /// </summary> protected int DefaultBlockMiningLimit => TinyBlockSlotInterval.Mul(3).Div(5); /// <summary> /// If this tiny block is the last one of current time slot, give half of producing time for mining. /// </summary> protected int LastTinyBlockMiningLimit => TinyBlockSlotInterval.Div(2); /// <summary> /// If this block is of consensus behaviour NEXT_TERM, the producing time is MiningInterval, /// so the limitation of mining is 8 times than DefaultBlockMiningLimit. /// </summary> protected int LastBlockOfCurrentTermMiningLimit => MiningInterval.Mul(3).Div(5); public ConsensusCommand GetConsensusCommand() { return GetAEDPoSConsensusCommand(); } // ReSharper disable once InconsistentNaming public virtual ConsensusCommand GetAEDPoSConsensusCommand() { return ConsensusCommandProvider.InvalidConsensusCommand; } } }
1
0.940832
1
0.940832
game-dev
MEDIA
0.769673
game-dev
0.843128
1
0.843128
chraft/c-raft
3,834
Chraft.PluginSystem/Event/IChraftEventHandler.cs
#region C#raft License // This file is part of C#raft. Copyright C#raft Team // // C#raft 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/>. #endregion using System.Collections.Generic; using Chraft.PluginSystem.Args; using Chraft.PluginSystem.Listener; namespace Chraft.PluginSystem.Event { public interface IChraftEventHandler { /// <summary> /// The type of event this is. /// </summary> EventType Type { get; } /// <summary> /// The list of events this handler holds. /// Events should be added in the constructer. /// </summary> List<Event> Events { get; } /// <summary> /// The list of EventListeners that listen to this handler. /// </summary> List<EventListener> Plugins { get; } /// <summary> /// Calls an event in this event handler. /// This should only be called from the PluginManager. /// </summary> /// <param name="Event">The event to call</param> /// <param name="e">Attached EventArgs</param> void CallEvent(Event Event, ChraftEventArgs e); /// <summary> /// Registers an event listener with this event handler. /// This should only be called from the PluginManager. /// </summary> /// <param name="listener">An EventListener instance.</param> void RegisterEvent(EventListener listener); } /// <summary> /// A list of event types. /// </summary> public enum EventType { World, Player, Server, Plugin, Entity, Block, Other } public enum Event { EntityDeath, EntitySpawn, EntityMove, EntityDamage, EntityAttack, PlayerJoined, PlayerLeft, PlayerCommand, PlayerPreCommand, PlayerChat, PlayerPreChat, PlayerKicked, PlayerMove, PlayerDied, IrcJoined, IrcLeft, IrcMessage, PacketReceived, PacketSent, PluginEnabled, PluginDisabled, CommandAdded, CommandRemoved, WorldLoad, WorldUnload, WorldJoin, WorldLeave, WorldCreate, WorldDelete, ServerCommand, ServerChat, ServerBroadcast, ServerAccept, LoggerLog, BlockPlace, BlockDestroy, BlockTouch } public struct EventListener { /// <summary> /// initializes a new instance of the EventListener struct. /// </summary> /// <param name="listener">A valid Listener. /// All Listeners are in the Chraft.Plugins.Listener namespace.</param> /// <param name="plugin">The IPlugin that the listener is attached to.</param> /// <param name="Event">The name of the event to listen for.</param> public EventListener(IChraftListener listener, IPlugin plugin, Event Event) { this.Listener = listener; this.Event = Event; this.Plugin = plugin; } public IChraftListener Listener; public IPlugin Plugin; public Event Event; } }
1
0.873629
1
0.873629
game-dev
MEDIA
0.404242
game-dev
0.630752
1
0.630752
iniside/Velesarc
7,625
ArcX/ArcCore/Source/ArcCore/BoneControllers/AnimNode_CopyMotion.h
/** * This file is part of Velesarc * Copyright (C) 2025-2025 Lukasz Baran * * Licensed under the European Union Public License (EUPL), Version 1.2 or – * as soon as they will be approved by the European Commission – later versions * of the EUPL (the "License"); * * You may not use this work except in compliance with the License. * You may get a copy of the License at: * * https://eupl.eu/ * * 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. */ #pragma once #include "BoneControllers/AnimNode_SkeletalControlBase.h" #include "UObject/ObjectPtr.h" #include "TransformNoScale.h" #include "AnimNode_CopyMotion.generated.h" class UCurveVector; class UCurveFloat; UENUM(BlueprintType) enum class ECopyMotion_Component : uint8 { TranslationX = 0, TranslationY = 1, TranslationZ = 2, // In Degrees RotationAngle = 3, }; // Highly experimental plugin. There's a strong chance that this gets replaced with Control Rig functionality after initial exploration. USTRUCT(BlueprintInternalUseOnly, Experimental) struct ARCCORE_API FAnimNode_CopyMotion : public FAnimNode_SkeletalControlBase { GENERATED_BODY(); public: FAnimNode_CopyMotion(); // FAnimNode_Base interface virtual void GatherDebugData(FNodeDebugData& DebugData) override; virtual void UpdateInternal(const FAnimationUpdateContext& Context) override; // End of FAnimNode_Base interface // FAnimNode_SkeletalControlBase interface virtual void Initialize_AnyThread(const FAnimationInitializeContext& Context) override; virtual void EvaluateSkeletalControl_AnyThread(FComponentSpacePoseContext& Output, TArray<FBoneTransform>& OutBoneTransforms) override; virtual void UpdateComponentPose_AnyThread(const FAnimationUpdateContext& Context) override; virtual void CacheBones_AnyThread(const FAnimationCacheBonesContext& Context); virtual bool IsValidToEvaluate(const USkeleton* Skeleton, const FBoneContainer& RequiredBones) override; // End of FAnimNode_SkeletalControlBase interface // Input pose to copy the motion from. UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=Links) FComponentSpacePoseLink BasePose; // Reference pose used to calculate a motion delta from the base pose. UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=Links) FComponentSpacePoseLink BasePoseReference; // Whether to use the input Base Pose. Curves will be used when this is disabled. UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Copy) bool bUseBasePose = false; // Tag of the pose history node to use to reference past bone transforms. // Your Pose History must include the desired bones used as Source and Copy. UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Copy) FName PoseHistoryTag = NAME_None; // How much to delay the motion we're copying. // Your Pose History time horizon/duration must be at least this long. UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Copy, meta = (ClampMin="0", PinHiddenByDefault)) float Delay = 0.0f; // Bone to copy the motion from. UPROPERTY(EditAnywhere, Category = Copy, meta = (EditCondition = "bUseBasePose")) FBoneReference SourceBone; /** Name of bone to control. This is the main bone chain to modify from. **/ UPROPERTY(EditAnywhere, Category = Copy) FBoneReference BoneToModify; /** Bone to use as the reference frame/space for our copied transform delta. If no reference frame is used, the source bone motion will be copied in component space. */ UPROPERTY(EditAnywhere, Category = Copy, meta = (EditCondition = "bUseBasePose")) FBoneReference CopySpace; /** Bone to use as the reference frame/space for our applied transform delta. If no reference frame is used, the source bone motion will be applied in component space. */ UPROPERTY(EditAnywhere, Category = Copy) FBoneReference ApplySpace; /** Offset to use before applying the translation deltas (in degrees). This is useful for changing the direction of motion, relative to our reference frame/bone */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Translation, meta=(PinHiddenByDefault)) FRotator TranslationOffset = FRotator::ZeroRotator; /** Rotation offset (in degrees) to apply before the rotation deltas. This is useful for changing the direction of motion, relative to our reference frame/bone */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Rotation, meta=(PinHiddenByDefault)) FRotator RotationOffset = FRotator::ZeroRotator; /** Pivot offset (in local space) to use when applying the rotation. Any non-zero value will cause the target bone to rotate around the pivot, effectively introducing additional translation. */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Rotation, meta=(PinHiddenByDefault)) FVector RotationPivot = FVector::ZeroVector; /** Curve prefix used for the animation curves. Format matches those generated by the LayeringMotionExtractorModifier */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Copy, meta = (EditCondition = "!bUseBasePose")) FName CurvePrefix = NAME_None; /** Name of the curve we're outputting motion to. */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Curve) FName TargetCurveName = NAME_None; /** Which component of motion we're outputting to the curve. */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Curve, meta=(PinHiddenByDefault)) float TargetCurveScale = 1.0f; /** Which component of motion we're outputting to the curve. */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Curve) ECopyMotion_Component TargetCurveComponent = ECopyMotion_Component::RotationAngle; /** Axis around which to consider the rotation angle for the curve output. */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Curve, meta = (EditCondition = "TargetCurveComponent == ECopyMotion_Component::RotationAngle")) TEnumAsByte<EAxis::Type> TargetCurveRotationAxis = EAxis::X; UPROPERTY() FName TranslationX_CurveName = NAME_None; UPROPERTY() FName TranslationY_CurveName = NAME_None; UPROPERTY() FName TranslationZ_CurveName = NAME_None; UPROPERTY() FName RotationRoll_CurveName = NAME_None; UPROPERTY() FName RotationPitch_CurveName = NAME_None; UPROPERTY() FName RotationYaw_CurveName = NAME_None; UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Translation, meta = (AllowPreserveRatio, PinHiddenByDefault)) FVector TranslationScale = FVector::One(); UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Translation, meta = (PinHiddenByDefault)) TObjectPtr<const UCurveVector> TranslationRemapCurve = nullptr; UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Rotation, meta = (PinHiddenByDefault)) float RotationScale = 1.0f; UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = Rotation, meta = (PinHiddenByDefault)) TObjectPtr<const UCurveFloat> RotationRemapCurve = nullptr; protected: void InitializeBoneReferences(const FBoneContainer& RequiredBones) override; float GetTargetCurveValue(const FTransformNoScale& InTransformDelta, ECopyMotion_Component MotionComponent); bool HasTargetBone(const FBoneContainer& BoneContainer) const; bool HasTargetCurve() const; void Reset(); bool bIsFirstUpdate = true; private: #if ENABLE_ANIM_DEBUG FVector LastLocDebug = FVector::Zero(); FVector LastRotDebug = FVector::Zero(); bool bIsDrawHistoryEnabled = false; #endif FGraphTraversalCounter UpdateCounter; };
1
0.977447
1
0.977447
game-dev
MEDIA
0.663842
game-dev
0.771058
1
0.771058
starfish-studios/Naturalist
4,938
fabric/src/main/java/com/starfish_studios/naturalist/common/item/fabric/CaughtMobItem.java
package com.starfish_studios.naturalist.common.item.fabric; import com.starfish_studios.naturalist.common.entity.Butterfly; import com.starfish_studios.naturalist.common.entity.core.Catchable; import com.starfish_studios.naturalist.core.registry.NaturalistEntityTypes; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvent; import net.minecraft.stats.Stats; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.MobSpawnType; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.*; import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.gameevent.GameEvent; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public class CaughtMobItem extends MobBucketItem { private final EntityType<?> type; public CaughtMobItem(EntityType<?> entitySupplier, Fluid fluid, SoundEvent emptyingSound, Properties settings) { super(entitySupplier, fluid, emptyingSound, settings); this.type = entitySupplier; } @Override public void appendHoverText(ItemStack stack, Level level, List<Component> tooltip, TooltipFlag flagIn) { if (this.type == NaturalistEntityTypes.BUTTERFLY.get()) { CompoundTag compoundnbt = stack.getTag(); if (compoundnbt != null && compoundnbt.contains("Variant", 3)) { Butterfly.Variant variant = Butterfly.Variant.getTypeById(compoundnbt.getInt("Variant")); tooltip.add((Component.translatable(String.format("tooltip.naturalist.%s", variant.toString().toLowerCase())).withStyle(ChatFormatting.ITALIC, ChatFormatting.GRAY))); } } /* else if (this.type == NaturalistEntityTypes.MOTH.get()) { CompoundTag compoundnbt = stack.getTag(); if (compoundnbt != null && compoundnbt.contains("Variant", 3)) { Moth.Variant variant = Moth.Variant.getTypeById(compoundnbt.getInt("Variant")); tooltip.add((Component.translatable(String.format("tooltip.naturalist.%s", variant.toString().toLowerCase())).withStyle(ChatFormatting.ITALIC, ChatFormatting.GRAY))); } } */ } private void spawn(ServerLevel serverLevel, ItemStack itemStack, @NotNull BlockPos pos) { Entity entity = this.type.spawn(serverLevel, itemStack, null, pos, MobSpawnType.BUCKET, true, false); if (entity instanceof Catchable catchable) { catchable.loadFromHandTag(itemStack.getOrCreateTag()); catchable.setFromHand(true); } } @Override public void checkExtraContent(@Nullable Player player, Level level, ItemStack containerStack, BlockPos pos) { if (level instanceof ServerLevel) { this.spawn((ServerLevel)level, containerStack, pos); level.gameEvent(player, GameEvent.ENTITY_PLACE, pos); } } @Override public @NotNull InteractionResultHolder<ItemStack> use(Level pLevel, Player pPlayer, InteractionHand pHand) { ItemStack itemstack = pPlayer.getItemInHand(pHand); BlockHitResult blockhitresult = getPlayerPOVHitResult(pLevel, pPlayer, ClipContext.Fluid.NONE); if (blockhitresult.getType() == HitResult.Type.MISS) { return InteractionResultHolder.pass(itemstack); } else if (blockhitresult.getType() != HitResult.Type.BLOCK) { return InteractionResultHolder.pass(itemstack); } else { BlockPos pos = blockhitresult.getBlockPos(); Direction direction = blockhitresult.getDirection(); BlockPos blockpos1 = pos.relative(direction); if (pLevel.mayInteract(pPlayer, pos) && pPlayer.mayUseItemAt(blockpos1, direction, itemstack)) { this.checkExtraContent(pPlayer, pLevel, itemstack, pos); this.playEmptySound(pPlayer, pLevel, pos); pPlayer.awardStat(Stats.ITEM_USED.get(this)); return InteractionResultHolder.sidedSuccess(getEmptySuccessItem(itemstack, pPlayer), pLevel.isClientSide()); } else { return InteractionResultHolder.fail(itemstack); } } } public static @NotNull ItemStack getEmptySuccessItem(ItemStack bucketStack, Player player) { return !player.getAbilities().instabuild ? new ItemStack(Items.AIR) : bucketStack; } }
1
0.841321
1
0.841321
game-dev
MEDIA
0.997469
game-dev
0.955985
1
0.955985
Dzierzan/OpenSA
6,284
OpenRA.Mods.OpenSA/Traits/SpawnsShrapnel.cs
#region Copyright & License Information /* * Copyright The OpenSA Developers (see CREDITS) * This file is part of OpenSA, which is free software. It is made * available to you 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. For more * information, see COPYING. */ #endregion using System; using System.Linq; using OpenRA.GameRules; using OpenRA.Mods.Common; using OpenRA.Mods.Common.Traits; using OpenRA.Mods.OpenSA.Traits.Render; using OpenRA.Traits; namespace OpenRA.Mods.OpenSA.Traits { [Desc("Spawns shrapnel weapons after a periodic interval.")] public class SpawnsShrapnelInfo : PausableConditionalTraitInfo { [WeaponReference] [FieldLoader.Require] [Desc("Has to be defined in weapons.yaml as well.")] public readonly string Weapon = null; [Desc("Amount of shrapnels thrown. Two values indicate a range.")] public readonly int[] Amount = { 1 }; [Desc("Delay between two spawns. Two values indicate a range.")] public readonly int[] Delay = { 50 }; [Desc("The percentage of aiming this shrapnel to a suitable target actor.")] public readonly int AimChance = 0; [Desc("What diplomatic stances can be targeted by the shrapnel.")] public readonly PlayerRelationship AimTargetStances = PlayerRelationship.Ally | PlayerRelationship.Neutral | PlayerRelationship.Enemy; [Desc("Allow this shrapnel to be thrown randomly when no targets found.")] public readonly bool ThrowWithoutTarget = true; [Desc("Should the shrapnel hit the spawner actor?")] public readonly bool AllowSelfHit = false; [Desc("Shrapnel spawn offset relative to actor's position.")] public readonly WVec LocalOffset = WVec.Zero; public WeaponInfo WeaponInfo { get; private set; } public override object Create(ActorInitializer init) { return new SpawnsShrapnel(init.Self, this); } public override void RulesetLoaded(Ruleset rules, ActorInfo ai) { base.RulesetLoaded(rules, ai); var weaponToLower = Weapon.ToLowerInvariant(); if (!rules.Weapons.TryGetValue(weaponToLower, out var weaponInfo)) throw new YamlException($"Weapons Ruleset does not contain an entry '{weaponToLower}'"); WeaponInfo = weaponInfo; } } class SpawnsShrapnel : PausableConditionalTrait<SpawnsShrapnelInfo>, ITick, ISync { readonly OpenRA.World world; readonly BodyOrientation body; [Sync] int ticks; WithSpawnsShrapnelAnimation[] animations; public SpawnsShrapnel(Actor self, SpawnsShrapnelInfo info) : base(info) { world = self.World; body = self.TraitOrDefault<BodyOrientation>(); } protected override void Created(Actor self) { base.Created(self); animations = self.TraitsImplementing<WithSpawnsShrapnelAnimation>().ToArray(); } void ITick.Tick(Actor self) { if (IsTraitDisabled || IsTraitPaused || !self.IsInWorld || --ticks > 0) return; ticks = Info.Delay.Length == 2 ? world.SharedRandom.Next(Info.Delay[0], Info.Delay[1]) : Info.Delay[0]; var localoffset = body != null ? body.LocalToWorld(Info.LocalOffset.Rotate(body.QuantizeOrientation(self.Orientation))) : Info.LocalOffset; var position = self.CenterPosition + localoffset; var availableTargetActors = world.FindActorsOnCircle(position, Info.WeaponInfo.Range) .Where(x => (Info.AllowSelfHit || x != self) && Info.WeaponInfo.IsValidAgainst(Target.FromActor(x), world, self) && Info.AimTargetStances.HasRelationship(self.Owner.RelationshipWith(x.Owner))) .Where(x => { var activeShapes = x.TraitsImplementing<HitShape>().Where(Exts.IsTraitEnabled); if (!activeShapes.Any()) return false; var distance = activeShapes.Min(t => t.DistanceFromEdge(x, position)); if (distance < Info.WeaponInfo.Range) return true; return false; }) .Shuffle(world.SharedRandom); var targetActor = availableTargetActors.GetEnumerator(); var amount = Info.Amount.Length == 2 ? world.SharedRandom.Next(Info.Amount[0], Info.Amount[1]) : Info.Amount[0]; for (var i = 0; i < amount; i++) { var shrapnelTarget = Target.Invalid; if (world.SharedRandom.Next(100) < Info.AimChance && targetActor.MoveNext()) shrapnelTarget = Target.FromActor(targetActor.Current); if (Info.ThrowWithoutTarget && shrapnelTarget.Type == TargetType.Invalid) { var rotation = WRot.FromFacing(world.SharedRandom.Next(1024)); var range = world.SharedRandom.Next(Info.WeaponInfo.MinRange.Length, Info.WeaponInfo.Range.Length); var targetpos = position + new WVec(range, 0, 0).Rotate(rotation); var tpos = Target.FromPos(new WPos(targetpos.X, targetpos.Y, world.Map.CenterOfCell(world.Map.CellContaining(targetpos)).Z)); if (Info.WeaponInfo.IsValidAgainst(tpos, world, self)) shrapnelTarget = tpos; } if (shrapnelTarget.Type == TargetType.Invalid) continue; var args = new ProjectileArgs { Weapon = Info.WeaponInfo, Facing = (shrapnelTarget.CenterPosition - position).Yaw, DamageModifiers = !self.IsDead ? self.TraitsImplementing<IFirepowerModifier>() .Select(a => a.GetFirepowerModifier()).ToArray() : Array.Empty<int>(), InaccuracyModifiers = !self.IsDead ? self.TraitsImplementing<IInaccuracyModifier>() .Select(a => a.GetInaccuracyModifier()).ToArray() : Array.Empty<int>(), RangeModifiers = !self.IsDead ? self.TraitsImplementing<IRangeModifier>() .Select(a => a.GetRangeModifier()).ToArray() : Array.Empty<int>(), Source = position, CurrentSource = () => position, SourceActor = self, GuidedTarget = shrapnelTarget, PassiveTarget = shrapnelTarget.CenterPosition }; if (args.Weapon.Projectile != null) { var projectile = args.Weapon.Projectile.Create(args); if (projectile != null) world.AddFrameEndTask(w => w.Add(projectile)); if (args.Weapon.Report != null && args.Weapon.Report.Any()) Game.Sound.Play(SoundType.World, args.Weapon.Report.Random(world.SharedRandom), position); } foreach (var animation in animations) animation.Trigger(self); } } protected override void TraitEnabled(Actor self) { ticks = 0; } } }
1
0.952009
1
0.952009
game-dev
MEDIA
0.974192
game-dev
0.896934
1
0.896934
sha0coder/mwemu
3,503
crates/libmwemu/src/emu_context.rs
use iced_x86::Formatter as _; use std::cell::RefCell; use crate::emu::Emu; thread_local! { static CURRENT_EMU: RefCell<Option<*const Emu>> = RefCell::new(None); } pub fn with_current_emu<F, R>(f: F) -> Option<R> where F: FnOnce(&Emu) -> R, { CURRENT_EMU.with(|current| { current .borrow() .and_then(|ptr| unsafe { ptr.as_ref().map(|emu| f(emu)) }) }) } pub fn with_current_emu_mut<F, R>(f: F) -> Option<R> where F: FnOnce(&mut Emu) -> R, { CURRENT_EMU.with(|current| { current .borrow() .and_then(|ptr| unsafe { (ptr as *mut Emu).as_mut().map(|emu| f(emu)) }) }) } pub fn set_current_emu(emu: &Emu) { CURRENT_EMU.with(|current| { *current.borrow_mut() = Some(emu as *const _); }); } pub fn clear_current_emu() { CURRENT_EMU.with(|current| { *current.borrow_mut() = None; }); } pub fn is_emu_set() -> bool { CURRENT_EMU.with(|current| current.borrow().is_some()) } pub fn log_emu_state(emu: &mut Emu) { log::error!("=== EMULATOR STATE AT PANIC ==="); log::error!("Current position: {}", emu.pos); let mut out: String = String::new(); let color = "\x1b[0;31m"; match emu.instruction { Some(ins) => { let ins = ins.clone(); emu.formatter.format(&ins, &mut out); log::info!( "{}{} 0x{:x}: {}{}", color, emu.pos, ins.ip(), out, emu.colors.nc ); } None => {} }; // Log general purpose registers log::error!("Registers:"); log::error!( " RAX: 0x{:016x} RBX: 0x{:016x}", emu.regs().rax, emu.regs().rbx ); log::error!( " RCX: 0x{:016x} RDX: 0x{:016x}", emu.regs().rcx, emu.regs().rdx ); log::error!( " RSI: 0x{:016x} RDI: 0x{:016x}", emu.regs().rsi, emu.regs().rdi ); log::error!( " RBP: 0x{:016x} RSP: 0x{:016x}", emu.regs().rbp, emu.regs().rsp ); log::error!( " R8: 0x{:016x} R9: 0x{:016x}", emu.regs().r8, emu.regs().r9 ); log::error!( " R10: 0x{:016x} R11: 0x{:016x}", emu.regs().r10, emu.regs().r11 ); log::error!( " R12: 0x{:016x} R13: 0x{:016x}", emu.regs().r12, emu.regs().r13 ); log::error!( " R14: 0x{:016x} R15: 0x{:016x}", emu.regs().r14, emu.regs().r15 ); log::error!(" RIP: 0x{:016x}", emu.regs().rip); // Log flags log::error!("EFLAGS: 0x{:08x}", emu.flags().dump()); // Log last instruction if available if let Some(ref _instruction) = emu.instruction { log::error!("Last instruction: {}", emu.mnemonic); log::error!("Instruction size: {}", emu.last_instruction_size); } // Log call stack if !emu.call_stack().is_empty() { log::error!( "Call stack (last {} entries):", emu.call_stack().len().min(10) ); for (i, entry) in emu.call_stack().iter().rev().take(10).enumerate() { log::error!(" {}: {:x}:call:{:x}", i, entry.0, entry.1); } } // Log execution info log::error!("Tick count: {}", emu.tick); log::error!("Base address: 0x{:x}", emu.base); log::error!("Filename: {}", emu.filename); log::error!("=============================="); }
1
0.666083
1
0.666083
game-dev
MEDIA
0.335028
game-dev
0.518882
1
0.518882
openmoh/openmohaa
9,648
code/client/cl_uiloadsave.cpp
/* =========================================================================== Copyright (C) 2023 the OpenMoHAA team This file is part of OpenMoHAA source code. OpenMoHAA source code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. OpenMoHAA source code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenMoHAA source code; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ #include "cl_ui.h" #include "../qcommon/localization.h" class FAKKLoadGameItem : public UIListCtrlItem { str strings[4]; public: FAKKLoadGameItem(const str& missionName, const str& elapsedTime, const str& dateTime, const str& fileName); int getListItemValue(int which) const override; griditemtype_t getListItemType(int which) const override; str getListItemString(int which) const override; void DrawListItem(int iColumn, const UIRect2D& drawRect, bool bSelected, UIFont *pFont) override; qboolean IsHeaderEntry() const override; }; static UIFAKKLoadGameClass *loadgame_ui = NULL; Event EV_FAKKLoadGame_LoadGame ( "loadgame", EV_DEFAULT, NULL, NULL, "Load the currently selected game" ); Event EV_FAKKLoadGame_RemoveGame ( "removegame", EV_DEFAULT, NULL, NULL, "Delete the currently selected game" ); Event EV_FAKKLoadGame_DeleteGame ( "deletegame", EV_DEFAULT, NULL, NULL, "Delete the currently selected game... for real" ); Event EV_FAKKLoadGame_NoDeleteGame ( "nodeletegame", EV_DEFAULT, NULL, NULL, "Delete the currently selected game... for real" ); Event EV_FAKKLoadGame_SaveGame ( "savegame", EV_DEFAULT, NULL, NULL, "Save the currently selected game" ); CLASS_DECLARATION(UIListCtrl, UIFAKKLoadGameClass, NULL) { {&EV_UIListBase_ItemSelected, &UIFAKKLoadGameClass::SelectGame }, {&EV_UIListBase_ItemDoubleClicked, &UIFAKKLoadGameClass::LoadGame }, {&EV_FAKKLoadGame_RemoveGame, &UIFAKKLoadGameClass::RemoveGame }, {&EV_FAKKLoadGame_DeleteGame, &UIFAKKLoadGameClass::DeleteGame }, {&EV_FAKKLoadGame_NoDeleteGame, &UIFAKKLoadGameClass::NoDeleteGame}, {&EV_FAKKLoadGame_LoadGame, &UIFAKKLoadGameClass::LoadGame }, {&EV_FAKKLoadGame_SaveGame, &UIFAKKLoadGameClass::SaveGame }, {NULL, NULL } }; UIFAKKLoadGameClass::UIFAKKLoadGameClass() { Connect(this, EV_UIListBase_ItemDoubleClicked, EV_UIListBase_ItemDoubleClicked); Connect(this, EV_UIListBase_ItemSelected, EV_UIListBase_ItemSelected); AllowActivate(true); m_bRemovePending = false; setHeaderFont("facfont-20"); loadgame_ui = this; } UIFAKKLoadGameClass::~UIFAKKLoadGameClass() { loadgame_ui = NULL; } void UIFAKKLoadGameClass::UpdateUIElement(void) { float width; RemoveAllColumns(); width = getClientFrame().size.width; AddColumn(Sys_LV_CL_ConvertString("Mission"), 0, width * 0.555, false, false); AddColumn(Sys_LV_CL_ConvertString("Elapsed Time"), 1, width * 0.17f, true, true); AddColumn(Sys_LV_CL_ConvertString("Date & Time Logged"), 2, width * 0.275f, true, true); uWinMan.ActivateControl(this); SetupFiles(); } void UIFAKKLoadGameClass::SetupFiles(void) { char **filenames; int numfiles; int i; const char *searchFolder = Com_GetArchiveFolder(); // cleanup DeleteAllItems(); filenames = FS_ListFiles(searchFolder, "ssv", qfalse, &numfiles); for (i = 0; i < numfiles; i++) { const char *filename; str work; str gametime; str date; fileHandle_t f; savegamestruct_t save; filename = filenames[i]; work = searchFolder; work += "/"; work += filename; FS_FOpenFileRead(work, &f, qfalse, qtrue); if (!f) { continue; } FS_Read(&save, sizeof(savegamestruct_t), f); FS_FCloseFile(f); Com_SwapSaveStruct(&save); if (save.version != SAVEGAME_STRUCT_VERSION) { // wrong save game version continue; } if (save.type != com_target_game->integer) { continue; } gametime = (save.mapTime / 1000); date = save.time; AddItem(new FAKKLoadGameItem(save.comment, gametime, date, save.saveName)); } FS_FreeFileList(filenames); // sort by date SortByColumn(2); // select the first item TrySelectItem(1); SelectGame(NULL); } void UIFAKKLoadGameClass::SelectGame(Event *ev) { UIWidget *wid; const char *shotName; if (getCurrentItem() > 0) { shotName = Com_GetArchiveFileName(GetItem(getCurrentItem())->getListItemString(3), "tga"); } else { shotName = "textures/menu/no_saved_games.tga"; } wid = findSibling("LoadSaveShot"); if (!wid) { return; } wid->setMaterial(uWinMan.RefreshShader(shotName)); } void UIFAKKLoadGameClass::RemoveGame(Event *ev) { if (m_bRemovePending || getCurrentItem() <= 0) { return; } Cbuf_ExecuteText( EXEC_NOW, "dialog \"\" \"\" \"widgetcommand LoadSaveList deletegame\" \"widgetcommand LoadSaveList nodeletegame\" 256 64 " "confirm_delete menu_button_trans menu_button_trans\n" ); m_bRemovePending = true; } void UIFAKKLoadGameClass::NoDeleteGame(Event *ev) { m_bRemovePending = false; } void UIFAKKLoadGameClass::DeleteGame(Event *ev) { str name; cvar_t *var; m_bRemovePending = false; if (getCurrentItem() <= 0) { return; } name = GetItem(getCurrentItem())->getListItemString(3); var = Cvar_Get("g_lastsave", "", 0); if (!strcmp(name, var->string)) { // Make sure the last save is not the save being deleted Cvar_Set("g_lastsave", ""); } Com_WipeSavegame(name); SetupFiles(); } void UIFAKKLoadGameClass::LoadGame(Event *ev) { char cmdString[266]; str name; if (getCurrentItem() <= 0) { return; } name = GetItem(getCurrentItem())->getListItemString(3); // Execute the command Com_sprintf(cmdString, sizeof(cmdString), "loadgame %s\n", name.c_str()); Cbuf_AddText(cmdString); } void UIFAKKLoadGameClass::SaveGame(Event *ev) { Cbuf_ExecuteText(EXEC_NOW, "savegame"); } qboolean UIFAKKLoadGameClass::KeyEvent(int key, unsigned int time) { switch (key) { case K_DEL: RemoveGame(NULL); return qtrue; case K_ENTER: case K_KP_ENTER: LoadGame(NULL); return qtrue; case K_UPARROW: if (getCurrentItem() > 1) { TrySelectItem(getCurrentItem() - 1); SelectGame(NULL); return qtrue; } break; case K_DOWNARROW: if (getCurrentItem() < getNumItems()) { TrySelectItem(getCurrentItem() + 1); SelectGame(NULL); return qtrue; } break; default: return UIListCtrl::KeyEvent(key, time); } return qfalse; } void UI_SetupFiles(void) { if (loadgame_ui && loadgame_ui->getShow()) { loadgame_ui->SetupFiles(); } } FAKKLoadGameItem::FAKKLoadGameItem( const str& missionName, const str& elapsedTime, const str& dateTime, const str& fileName ) { strings[0] = missionName; strings[1] = elapsedTime; strings[2] = dateTime; strings[3] = fileName; } int FAKKLoadGameItem::getListItemValue(int which) const { return atoi(strings[which]); } griditemtype_t FAKKLoadGameItem::getListItemType(int which) const { return griditemtype_t::TYPE_STRING; } str FAKKLoadGameItem::getListItemString(int which) const { str itemstring; switch (which) { case 0: case 3: itemstring = strings[which]; break; case 1: { int numseconds; int numseconds_hours; int seconds; // hours numseconds = atol(strings[1]); itemstring += (numseconds / 3600); itemstring += ":"; // minutes numseconds_hours = numseconds % 3600; if (numseconds_hours / 60 < 10) { itemstring += "0"; } itemstring += (numseconds_hours / 60); itemstring += ":"; // seconds seconds = numseconds_hours % 60; if (seconds < 10) { itemstring += "0"; } itemstring += seconds; } break; case 2: { time_t time; char buffer[2048]; time = atol(strings[2]); strftime(buffer, sizeof(buffer), "%a %b %d %Y %H:%M:%S", localtime(&time)); itemstring = buffer; } break; } return itemstring; } void FAKKLoadGameItem::DrawListItem(int iColumn, const UIRect2D& drawRect, bool bSelected, UIFont *pFont) {} qboolean FAKKLoadGameItem::IsHeaderEntry() const { return qfalse; }
1
0.826677
1
0.826677
game-dev
MEDIA
0.84735
game-dev
0.976769
1
0.976769
PacktPublishing/CPP-Game-Development-By-Example
3,130
Chapter07/7.OpenGLProject/OpenGLProject/Dependencies/bullet/include/BulletDynamics/Featherstone/btMultiBodySliderConstraint.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2013 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ ///This file was written by Erwin Coumans #ifndef BT_MULTIBODY_SLIDER_CONSTRAINT_H #define BT_MULTIBODY_SLIDER_CONSTRAINT_H #include "btMultiBodyConstraint.h" class btMultiBodySliderConstraint : public btMultiBodyConstraint { protected: btRigidBody* m_rigidBodyA; btRigidBody* m_rigidBodyB; btVector3 m_pivotInA; btVector3 m_pivotInB; btMatrix3x3 m_frameInA; btMatrix3x3 m_frameInB; btVector3 m_jointAxis; public: btMultiBodySliderConstraint(btMultiBody* body, int link, btRigidBody* bodyB, const btVector3& pivotInA, const btVector3& pivotInB, const btMatrix3x3& frameInA, const btMatrix3x3& frameInB, const btVector3& jointAxis); btMultiBodySliderConstraint(btMultiBody* bodyA, int linkA, btMultiBody* bodyB, int linkB, const btVector3& pivotInA, const btVector3& pivotInB, const btMatrix3x3& frameInA, const btMatrix3x3& frameInB, const btVector3& jointAxis); virtual ~btMultiBodySliderConstraint(); virtual void finalizeMultiDof(); virtual int getIslandIdA() const; virtual int getIslandIdB() const; virtual void createConstraintRows(btMultiBodyConstraintArray& constraintRows, btMultiBodyJacobianData& data, const btContactSolverInfo& infoGlobal); const btVector3& getPivotInA() const { return m_pivotInA; } void setPivotInA(const btVector3& pivotInA) { m_pivotInA = pivotInA; } const btVector3& getPivotInB() const { return m_pivotInB; } virtual void setPivotInB(const btVector3& pivotInB) { m_pivotInB = pivotInB; } const btMatrix3x3& getFrameInA() const { return m_frameInA; } void setFrameInA(const btMatrix3x3& frameInA) { m_frameInA = frameInA; } const btMatrix3x3& getFrameInB() const { return m_frameInB; } virtual void setFrameInB(const btMatrix3x3& frameInB) { m_frameInB = frameInB; } const btVector3& getJointAxis() const { return m_jointAxis; } void setJointAxis(const btVector3& jointAxis) { m_jointAxis = jointAxis; } virtual void debugDraw(class btIDebugDraw* drawer); }; #endif //BT_MULTIBODY_SLIDER_CONSTRAINT_H
1
0.75804
1
0.75804
game-dev
MEDIA
0.960085
game-dev
0.815959
1
0.815959
ProjectIgnis/CardScripts
2,068
rush/c160008060.lua
--埋め盾 --Buried Shield local s,id=GetID() function s.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(id,0)) e1:SetCategory(CATEGORY_POSITION+CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetCondition(s.condition) e1:SetCost(s.cost) e1:SetTarget(s.target) e1:SetOperation(s.operation) c:RegisterEffect(e1) end function s.tdfilter(c) return c:IsFieldSpell() and c:IsAbleToDeckOrExtraAsCost() end function s.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(s.tdfilter,tp,LOCATION_GRAVE,0,1,nil) end end function s.condition(e,tp,eg,ep,ev,re,r,rp) if #eg~=1 then return false end local tc=eg:GetFirst() return tc:IsFaceup() and tc:IsCanTurnSet() and tc:IsCanChangePositionRush() and tc:IsSummonPlayer(1-tp) end function s.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_POSITION,eg:GetFirst(),1,0,0) end function s.filter(c) return c:IsRace(RACE_WYRM) and c:IsFaceup() end function s.operation(e,tp,eg,ep,ev,re,r,rp) --Requirement Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK) local td=Duel.SelectMatchingCard(tp,s.tdfilter,tp,LOCATION_GRAVE,0,1,1,nil) Duel.HintSelection(td) if Duel.SendtoDeck(td,nil,SEQ_DECKBOTTOM,REASON_COST)~0 then --Effect local tc=eg:GetFirst() Duel.ChangePosition(tc,POS_FACEDOWN_DEFENSE) if Duel.IsExistingMatchingCard(aux.FilterMaximumSideFunctionEx(s.filter),tp,LOCATION_MZONE,0,1,nil) and Duel.SelectYesNo(tp,aux.Stringid(id,0)) then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK) local tc2=Duel.SelectMatchingCard(tp,aux.FilterMaximumSideFunctionEx(s.filter),tp,LOCATION_MZONE,0,1,1,nil):GetFirst() --Increase its ATK/DEF by 500 local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(500) e1:SetReset(RESETS_STANDARD_PHASE_END) tc2:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EFFECT_UPDATE_DEFENSE) tc2:RegisterEffect(e2) end end end
1
0.893932
1
0.893932
game-dev
MEDIA
0.9667
game-dev
0.972606
1
0.972606
fr1tz/terminal-overload
1,366
Engine/source/NOTC/hexagonVolumeCollisionShape.h
// Copyright information can be found in the file named COPYING // located in the root directory of this distribution. #ifndef _HEXAGONVOLUMECOLLISIONSHAPE_H_ #define _HEXAGONVOLUMECOLLISIONSHAPE_H_ #ifndef _STATICSHAPE_H_ #include "T3D/staticShape.h" #endif //---------------------------------------------------------------------------- class HexagonVolumeCollisionShape : public ShapeBase { typedef ShapeBase Parent; StaticShapeData* mDataBlock; protected: enum MaskBits { PositionMask = Parent::NextFreeMask, NextFreeMask = Parent::NextFreeMask << 1 }; public: DECLARE_CONOBJECT(HexagonVolumeCollisionShape); HexagonVolumeCollisionShape(); HexagonVolumeCollisionShape(bool onClient); ~HexagonVolumeCollisionShape(); // SimObject bool onAdd(); void onRemove(); void onEditorEnable(); void onEditorDisable(); // NetObject U32 packUpdate (NetConnection *conn, U32 mask, BitStream *stream); void unpackUpdate(NetConnection *conn, BitStream *stream); // SceneObject void setTransform(const MatrixF &mat); void setRenderTransform(const MatrixF &mat); // GameBase bool onNewDataBlock(GameBaseData *dptr, bool reload); void processTick(const Move *move); void interpolateTick(F32 delta); static void initPersistFields(); }; #endif // _HEXAGONVOLUMECOLLISIONSHAPE_H_
1
0.93082
1
0.93082
game-dev
MEDIA
0.709232
game-dev,graphics-rendering
0.764281
1
0.764281
skykapok/dawn
3,058
engine/platform/winfw.c
#include <stdlib.h> #include <stdio.h> #include "opengl.h" #include "lauxlib.h" #include "ejoy2dgame.h" #include "fault.h" #include "screen.h" #include "winfw.h" struct WINDOWGAME { struct game *game; int intouch; }; static struct WINDOWGAME *G = NULL; static const char * startscript = "local path, script, sw, sh, ss = ...\n" "local fw = require('ejoy2d.framework')\n" "fw.WorkDir = path..'/'\n" "fw.ScreenWidth, fw.ScreenHeight, fw.ScreenScale = sw, sh, ss\n" "assert(script, 'I need a script name')\n" "script = path..'/'..script\n" "package.path = './?.lua;./?/init.lua;'\n" "package.path = package.path..path..'/?.lua;'\n" "package.path = package.path..path..'/?/init.lua;'\n" "package.path = package.path..path..'/src/?.lua;'\n" "local f = loadfile(script)\n" "f(script)\n"; static struct WINDOWGAME * create_game() { struct WINDOWGAME * g = malloc(sizeof(*g)); g->game = ejoy2d_game(); g->intouch = 0; return g; } static int traceback(lua_State *L) { const char *msg = lua_tostring(L, 1); if (msg) { luaL_traceback(L, L, msg, 1); } else if (!lua_isnoneornil(L, 1)) { if (!luaL_callmeta(L, 1, "__tostring")) lua_pushliteral(L, "(no error message)"); } return 1; } void ejoy2d_win_init(int orix, int oriy, int width, int height, float scale, const char* folder) { G = create_game(); lua_State *L = ejoy2d_game_lua(G->game); lua_pushcfunction(L, traceback); int tb = lua_gettop(L); int err = luaL_loadstring(L, startscript); if (err) { const char *msg = lua_tostring(L,-1); fault("%s", msg); } lua_pushstring(L, folder); lua_pushstring(L, "src/main.lua"); lua_pushnumber(L, width); lua_pushnumber(L, height); lua_pushnumber(L, scale); err = lua_pcall(L, 5, 0, tb); if (err) { const char *msg = lua_tostring(L,-1); fault("%s", msg); } lua_pop(L,1); screen_init(width,height,scale); ejoy2d_game_start(G->game); } void ejoy2d_win_release() { ejoy2d_game_exit(G->game); } void ejoy2d_win_update(float dt) { ejoy2d_game_update(G->game, dt); } void ejoy2d_win_frame() { ejoy2d_game_drawframe(G->game); } void ejoy2d_win_resume(){ ejoy2d_game_resume(G->game); } void ejoy2d_win_touch(int x, int y,int touch) { switch (touch) { case TOUCH_BEGIN: G->intouch = 1; break; case TOUCH_END: G->intouch = 0; break; case TOUCH_MOVE: if (!G->intouch) { return; } break; } // windows only support one touch id (0) int id = 0; ejoy2d_game_touch(G->game, id, x,y,touch); } void ejoy2d_win_rotate(int width, int height, float scale, int orient) { screen_init(width, height, scale); switch (orient) { case ORIENT_UP: ejoy2d_game_message(G->game, 0, NULL, "UP", 0); break; case ORIENT_DOWN: ejoy2d_game_message(G->game, 0, NULL, "DOWN", 0); break; case ORIENT_LEFT: ejoy2d_game_message(G->game, 0, NULL, "LEFT", 0); break; case ORIENT_RIGHT: ejoy2d_game_message(G->game, 0, NULL, "RIGHT", 0); break; default: break; } }
1
0.673335
1
0.673335
game-dev
MEDIA
0.62391
game-dev
0.737444
1
0.737444
Kaedrin/nwn2cc
1,090
NWN2 WIP/Override/override_latest/Scripts/cmi_s2_forcepers.NSS
//:://///////////////////////////////////////////// //:: Force of Personality //:: cmi_s2_forcepers //:: Purpose: //:: Created By: Kaedrin (Matt) //:: Created On: November 23, 2009 //::////////////////////////////////////////////// //#include "cmi_ginc_spells" #include "x2_inc_spellhook" #include "nwn2_inc_spells" #include "cmi_includes" void main() { if (!X2PreSpellCastCode()) { // If code within the PreSpellCastHook (i.e. UMD) reports FALSE, do not run this spell return; } int nSpellId = SPELLABILITY_SCOUT_BATTLEFORT; if (GetHasSpellEffect(nSpellId,OBJECT_SELF)) { RemoveSpellEffects(nSpellId, OBJECT_SELF, OBJECT_SELF); } int nWis = GetAbilityModifier(ABILITY_WISDOM); int nCha= GetAbilityModifier(ABILITY_CHARISMA); int nBonus = nCha - nWis; if (nBonus <= 0) return; effect eFort = EffectSavingThrowIncrease(SAVING_THROW_WILL, nBonus); eFort = SetEffectSpellId(eFort,nSpellId); eFort = SupernaturalEffect(eFort); DelayCommand(0.1f, ApplyEffectToObject(DURATION_TYPE_TEMPORARY, eFort, OBJECT_SELF, HoursToSeconds(72))); }
1
0.610048
1
0.610048
game-dev
MEDIA
0.936822
game-dev
0.917081
1
0.917081
gscept/nebula-trifid
3,148
code/extlibs/bullet/bullet/src/BulletMultiThreaded/GpuSoftBodySolvers/DX11/btSoftBodySolverTriangleData_DX11.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "BulletMultiThreaded/GpuSoftBodySolvers/Shared/btSoftBodySolverData.h" #include "btSoftBodySolverBuffer_DX11.h" #ifndef BT_SOFT_BODY_SOLVER_TRIANGLE_DATA_DX11_H #define BT_SOFT_BODY_SOLVER_TRIANGLE_DATA_DX11_H struct ID3D11Device; struct ID3D11DeviceContext; class btSoftBodyTriangleDataDX11 : public btSoftBodyTriangleData { public: bool m_onGPU; ID3D11Device *m_d3dDevice; ID3D11DeviceContext *m_d3dDeviceContext; btDX11Buffer<btSoftBodyTriangleData::TriangleNodeSet> m_dx11VertexIndices; btDX11Buffer<float> m_dx11Area; btDX11Buffer<Vectormath::Aos::Vector3> m_dx11Normal; struct BatchPair { int start; int length; BatchPair() : start(0), length(0) { } BatchPair( int s, int l ) : start( s ), length( l ) { } }; /** * Link addressing information for each cloth. * Allows link locations to be computed independently of data batching. */ btAlignedObjectArray< int > m_triangleAddresses; /** * Start and length values for computation batches over link data. */ btAlignedObjectArray< BatchPair > m_batchStartLengths; //ID3D11Buffer* readBackBuffer; public: btSoftBodyTriangleDataDX11( ID3D11Device *d3dDevice, ID3D11DeviceContext *d3dDeviceContext ); virtual ~btSoftBodyTriangleDataDX11(); /** Allocate enough space in all link-related arrays to fit numLinks links */ virtual void createTriangles( int numTriangles ); /** Insert the link described into the correct data structures assuming space has already been allocated by a call to createLinks */ virtual void setTriangleAt( const btSoftBodyTriangleData::TriangleDescription &triangle, int triangleIndex ); virtual bool onAccelerator(); virtual bool moveToAccelerator(); virtual bool moveFromAccelerator(); /** * Generate (and later update) the batching for the entire triangle set. * This redoes a lot of work because it batches the entire set when each cloth is inserted. * In theory we could delay it until just before we need the cloth. * It's a one-off overhead, though, so that is a later optimisation. */ void generateBatches(); }; #endif // #ifndef BT_SOFT_BODY_SOLVER_TRIANGLE_DATA_DX11_H
1
0.937659
1
0.937659
game-dev
MEDIA
0.732451
game-dev
0.633304
1
0.633304
LostArtefacts/TRX
10,697
src/libtrx/game/items/common.c
#include "game/items/common.h" #include "game/carrier.h" #include "game/game.h" #include "game/game_buf.h" #include "game/game_flow.h" #include "game/lara/common.h" #include "game/objects/common.h" #include "game/output/const.h" #include "game/rooms.h" #include "memory.h" #include "utils.h" #include <string.h> static int32_t m_LevelItemCount = 0; static int16_t m_MaxUsedItemCount = 0; static ITEM *m_Items = nullptr; static int16_t m_NextItemActive = NO_ITEM; static int16_t m_PrevItemActive = NO_ITEM; static int16_t m_NextItemFree = NO_ITEM; void Item_InitialiseItems(const int32_t num_items) { m_Items = GameBuf_Alloc(sizeof(ITEM) * MAX_ITEMS, GBUF_ITEMS); m_LevelItemCount = num_items; m_MaxUsedItemCount = num_items; m_NextItemFree = num_items; m_NextItemActive = NO_ITEM; m_PrevItemActive = NO_ITEM; for (int32_t i = m_NextItemFree; i < MAX_ITEMS - 1; i++) { ITEM *const item = &m_Items[i]; item->active = false; item->next_item = i + 1; } m_Items[MAX_ITEMS - 1].next_item = NO_ITEM; } ITEM *Item_Get(const int16_t item_num) { if (item_num == NO_ITEM) { return nullptr; } return &m_Items[item_num]; } int16_t Item_GetIndex(const ITEM *const item) { return item - Item_Get(0); } ITEM *Item_Find(const GAME_OBJECT_ID obj_id) { for (int32_t item_num = 0; item_num < Item_GetTotalCount(); item_num++) { ITEM *const item = Item_Get(item_num); if (item->object_id == obj_id) { return item; } } return nullptr; } bool Item_SetName(const int16_t item_num, const char *const name) { ITEM *const item = Item_Get(item_num); if (item == nullptr) { return false; } if (name != nullptr) { ITEM *const existing = Item_GetByName(name); if (existing != nullptr && existing != item) { return false; } } if (name != nullptr) { item->name = GameBuf_Alloc(strlen(name) + 1, GBUF_ITEMS); strcpy(item->name, name); } else { item->name = nullptr; } return true; } ITEM *Item_GetByName(const char *const name) { if (name == nullptr) { return nullptr; } // search through all items for matching name for (int32_t i = 0; i < Item_GetTotalCount(); i++) { ITEM *const item = Item_Get(i); if (item->name != nullptr && strcmp(item->name, name) == 0) { return item; } } return nullptr; } int32_t Item_GetLevelCount(void) { return m_LevelItemCount; } int32_t Item_GetTotalCount(void) { return m_MaxUsedItemCount; } int16_t Item_GetNextActive(void) { return m_NextItemActive; } int16_t Item_GetPrevActive(void) { return m_PrevItemActive; } void Item_SetPrevActive(const int16_t item_num) { m_PrevItemActive = item_num; } int16_t Item_Create(void) { const int16_t item_num = m_NextItemFree; if (item_num != NO_ITEM) { m_Items[item_num].flags = 0; m_NextItemFree = m_Items[item_num].next_item; } m_MaxUsedItemCount = MAX(m_MaxUsedItemCount, item_num + 1); return item_num; } int16_t Item_CreateLevelItem(void) { const int16_t item_num = Item_Create(); if (item_num != NO_ITEM) { m_LevelItemCount++; } return item_num; } int16_t Item_Spawn(const ITEM *const item, const GAME_OBJECT_ID obj_id) { const int16_t spawn_num = Item_Create(); if (spawn_num != NO_ITEM) { ITEM *const spawn = Item_Get(spawn_num); spawn->object_id = obj_id; spawn->room_num = item->room_num; spawn->pos = item->pos; spawn->rot = item->rot; Item_Initialise(spawn_num); spawn->status = IS_INACTIVE; spawn->shade.value_1 = SHADE_NEUTRAL; } return spawn_num; } void Item_Initialise(const int16_t item_num) { ITEM *const item = Item_Get(item_num); const OBJECT *const obj = Object_Get(item->object_id); Item_SwitchToAnim(item, 0, 0); item->goal_anim_state = Item_GetAnim(item)->current_anim_state; item->current_anim_state = item->goal_anim_state; item->required_anim_state = 0; item->rot.x = 0; item->rot.z = 0; item->speed = 0; item->fall_speed = 0; item->hit_points = obj->hit_points; item->max_hit_points = obj->hit_points; item->timer = 0; item->mesh_bits = 0xFFFFFFFF; item->touch_bits = 0; item->data = nullptr; item->priv = nullptr; item->carried_item = nullptr; item->name = nullptr; item->active = false; item->status = IS_INACTIVE; item->gravity = false; item->hit_status = false; item->collidable = true; item->looked_at = false; item->enable_interpolation = true; item->enable_shadow = true; #if TR_VERSION >= 2 item->killed = false; if ((item->flags & IF_KILLED) != 0) { item->killed = true; item->flags &= ~IF_KILLED; } #endif if ((item->flags & IF_INVISIBLE) != 0) { item->status = IS_INVISIBLE; item->flags &= ~IF_INVISIBLE; } else if (TR_VERSION >= 2 && obj->intelligent) { item->status = IS_INVISIBLE; } if ((item->flags & IF_CODE_BITS) == IF_CODE_BITS) { item->flags &= ~IF_CODE_BITS; item->flags |= IF_REVERSE; Item_AddActive(item_num); item->status = IS_ACTIVE; } ROOM *const room = Room_Get(item->room_num); item->next_item = room->item_num; room->item_num = item_num; const SECTOR *const sector = Room_GetWorldSector(room, item->pos.x, item->pos.z); item->floor = sector->floor.height; // TODO: remove GF check once demo config reset is run before level load if (Game_IsBonusFlagSet(GBF_NGPLUS) && GF_GetCurrentLevel()->type != GFL_DEMO) { item->hit_points *= 2; } if (obj->initialise_func != nullptr) { obj->initialise_func(item_num); } } void Item_Control(void) { int16_t item_num = Item_GetNextActive(); while (item_num != NO_ITEM) { const ITEM *const item = Item_Get(item_num); const int16_t next = item->next_active; const OBJECT *obj = Object_Get(item->object_id); if ((item->flags & IF_KILLED) == 0 && obj->control_func != nullptr) { obj->control_func(item_num); } item_num = next; } Carrier_AnimateDrops(); } void Item_Kill(const int16_t item_num) { Item_RemoveActive(item_num); Item_RemoveDrawn(item_num); ITEM *const item = &m_Items[item_num]; LARA_INFO *const lara = Lara_GetLaraInfo(); if (item == lara->target) { lara->target = nullptr; } #if TR_VERSION == 1 item->hit_points = -1; item->flags |= IF_KILLED; #else // NOTE: if changing this, test if GS(CMD_WINSTON_DEAD) works as expected if (item_num < m_LevelItemCount) { item->flags |= IF_KILLED; } #endif if (item_num >= m_LevelItemCount) { item->next_item = m_NextItemFree; m_NextItemFree = item_num; } while (m_MaxUsedItemCount > 0 && m_Items[m_MaxUsedItemCount - 1].flags & IF_KILLED) { m_MaxUsedItemCount--; } } void Item_RemoveActive(const int16_t item_num) { ITEM *const item = &m_Items[item_num]; if (!item->active) { return; } item->active = false; int16_t link_num = m_NextItemActive; if (link_num == item_num) { m_NextItemActive = item->next_active; return; } while (link_num != NO_ITEM) { if (m_Items[link_num].next_active == item_num) { m_Items[link_num].next_active = item->next_active; return; } link_num = m_Items[link_num].next_active; } } void Item_RemoveDrawn(const int16_t item_num) { const ITEM *const item = &m_Items[item_num]; if (item->room_num == NO_ROOM) { return; } ROOM *const room = Room_Get(item->room_num); int16_t link_num = room->item_num; if (link_num == item_num) { room->item_num = item->next_item; return; } while (link_num != NO_ITEM) { if (m_Items[link_num].next_item == item_num) { m_Items[link_num].next_item = item->next_item; return; } link_num = m_Items[link_num].next_item; } } void Item_ClearKilled(void) { // Remove corpses and other killed items. Part of OG performance // improvements, generously used in Opera House and Barkhang Monastery int16_t link_num = Item_GetPrevActive(); while (link_num != NO_ITEM) { ITEM *const item = Item_Get(link_num); Item_Kill(link_num); link_num = item->next_active; item->next_active = NO_ITEM; } Item_SetPrevActive(NO_ITEM); } void Item_AddActive(const int16_t item_num) { ITEM *const item = &m_Items[item_num]; if (Object_Get(item->object_id)->control_func == nullptr) { item->status = IS_INACTIVE; return; } if (item->active) { return; } item->active = true; item->next_active = m_NextItemActive; m_NextItemActive = item_num; } void Item_UpdateRoom(const int16_t item_num, const int16_t room_num) { ITEM *const item = &m_Items[item_num]; if (item->room_num == room_num) { return; } ROOM *room = nullptr; if (item->room_num != NO_ROOM) { room = Room_Get(item->room_num); int16_t link_num = room->item_num; if (link_num == item_num) { room->item_num = item->next_item; } else { while (link_num != NO_ITEM) { if (m_Items[link_num].next_item == item_num) { m_Items[link_num].next_item = item->next_item; break; } link_num = m_Items[link_num].next_item; } } } room = Room_Get(room_num); item->room_num = room_num; item->next_item = room->item_num; room->item_num = item_num; } int32_t Item_GlobalReplace( const GAME_OBJECT_ID src_obj_id, const GAME_OBJECT_ID dst_obj_id) { int32_t changed = 0; for (int32_t item_num = 0; item_num < m_MaxUsedItemCount; item_num++) { ITEM *const item = &m_Items[item_num]; if (item->object_id == src_obj_id) { item->object_id = dst_obj_id; changed++; } } return changed; } bool Item_IsTriggerActive(ITEM *const item) { const bool ok = !(item->flags & IF_REVERSE); if ((item->flags & IF_CODE_BITS) != IF_CODE_BITS) { return !ok; } if (!item->timer) { return ok; } if (item->timer == -1) { return !ok; } item->timer--; if (item->timer == 0) { item->timer = -1; } return ok; }
1
0.915543
1
0.915543
game-dev
MEDIA
0.959035
game-dev
0.80917
1
0.80917
lua9520/source-engine-2018-cstrike15_src
1,306
matchmaking/mm_events.h
//===== Copyright 1996-2009, Valve Corporation, All rights reserved. ======// // // Purpose: // //===========================================================================// #ifndef MM_EVENTS_H #define MM_EVENTS_H #ifdef _WIN32 #pragma once #endif #include "mm_framework.h" #include "utlvector.h" class CMatchEventsSubscription : public IMatchEventsSubscription { // Methods of IMatchEventsSubscription public: virtual void Subscribe( IMatchEventsSink *pSink ); virtual void Unsubscribe( IMatchEventsSink *pSink ); virtual void BroadcastEvent( KeyValues *pEvent ); virtual void RegisterEventData( KeyValues *pEventData ); virtual KeyValues * GetEventData( char const *szEventDataKey ); public: bool IsBroacasting() const { return m_bBroadcasting; } void Shutdown(); public: CMatchEventsSubscription(); ~CMatchEventsSubscription(); protected: CUtlVector< IMatchEventsSink * > m_arrSinks; CUtlVector< int > m_arrRefCount; CUtlVector< int > m_arrIteratorsOutstanding; bool m_bBroadcasting; bool m_bAllowNestedBroadcasts; CUtlVector< KeyValues * > m_arrQueuedEvents; CUtlVector< KeyValues * > m_arrEventData; CUtlVector< KeyValues * > m_arrSentEvents; }; // Match events subscription singleton extern CMatchEventsSubscription *g_pMatchEventsSubscription; #endif // MM_EVENTS_H
1
0.905497
1
0.905497
game-dev
MEDIA
0.484228
game-dev
0.740541
1
0.740541
maceq687/FullBodyPoseEstimation
4,050
Assets/TutorialInfo/Scripts/Editor/ReadmeEditor.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using System; using System.IO; using System.Reflection; [CustomEditor(typeof(Readme))] [InitializeOnLoad] public class ReadmeEditor : Editor { static string kShowedReadmeSessionStateName = "ReadmeEditor.showedReadme"; static float kSpace = 16f; static ReadmeEditor() { EditorApplication.delayCall += SelectReadmeAutomatically; } static void SelectReadmeAutomatically() { if (!SessionState.GetBool(kShowedReadmeSessionStateName, false )) { var readme = SelectReadme(); SessionState.SetBool(kShowedReadmeSessionStateName, true); if (readme && !readme.loadedLayout) { LoadLayout(); readme.loadedLayout = true; } } } static void LoadLayout() { var assembly = typeof(EditorApplication).Assembly; var windowLayoutType = assembly.GetType("UnityEditor.WindowLayout", true); var method = windowLayoutType.GetMethod("LoadWindowLayout", BindingFlags.Public | BindingFlags.Static); method.Invoke(null, new object[]{Path.Combine(Application.dataPath, "TutorialInfo/Layout.wlt"), false}); } [MenuItem("Tutorial/Show Tutorial Instructions")] static Readme SelectReadme() { var ids = AssetDatabase.FindAssets("Readme t:Readme"); if (ids.Length == 1) { var readmeObject = AssetDatabase.LoadMainAssetAtPath(AssetDatabase.GUIDToAssetPath(ids[0])); Selection.objects = new UnityEngine.Object[]{readmeObject}; return (Readme)readmeObject; } else { Debug.Log("Couldn't find a readme"); return null; } } protected override void OnHeaderGUI() { var readme = (Readme)target; Init(); var iconWidth = Mathf.Min(EditorGUIUtility.currentViewWidth/3f - 20f, 128f); GUILayout.BeginHorizontal("In BigTitle"); { GUILayout.Label(readme.icon, GUILayout.Width(iconWidth), GUILayout.Height(iconWidth)); GUILayout.Label(readme.title, TitleStyle); } GUILayout.EndHorizontal(); } public override void OnInspectorGUI() { var readme = (Readme)target; Init(); foreach (var section in readme.sections) { if (!string.IsNullOrEmpty(section.heading)) { GUILayout.Label(section.heading, HeadingStyle); } if (!string.IsNullOrEmpty(section.text)) { GUILayout.Label(section.text, BodyStyle); } if (!string.IsNullOrEmpty(section.linkText)) { if (LinkLabel(new GUIContent(section.linkText))) { Application.OpenURL(section.url); } } GUILayout.Space(kSpace); } } bool m_Initialized; GUIStyle LinkStyle { get { return m_LinkStyle; } } [SerializeField] GUIStyle m_LinkStyle; GUIStyle TitleStyle { get { return m_TitleStyle; } } [SerializeField] GUIStyle m_TitleStyle; GUIStyle HeadingStyle { get { return m_HeadingStyle; } } [SerializeField] GUIStyle m_HeadingStyle; GUIStyle BodyStyle { get { return m_BodyStyle; } } [SerializeField] GUIStyle m_BodyStyle; void Init() { if (m_Initialized) return; m_BodyStyle = new GUIStyle(EditorStyles.label); m_BodyStyle.wordWrap = true; m_BodyStyle.fontSize = 14; m_TitleStyle = new GUIStyle(m_BodyStyle); m_TitleStyle.fontSize = 26; m_HeadingStyle = new GUIStyle(m_BodyStyle); m_HeadingStyle.fontSize = 18 ; m_LinkStyle = new GUIStyle(m_BodyStyle); m_LinkStyle.wordWrap = false; // Match selection color which works nicely for both light and dark skins m_LinkStyle.normal.textColor = new Color (0x00/255f, 0x78/255f, 0xDA/255f, 1f); m_LinkStyle.stretchWidth = false; m_Initialized = true; } bool LinkLabel (GUIContent label, params GUILayoutOption[] options) { var position = GUILayoutUtility.GetRect(label, LinkStyle, options); Handles.BeginGUI (); Handles.color = LinkStyle.normal.textColor; Handles.DrawLine (new Vector3(position.xMin, position.yMax), new Vector3(position.xMax, position.yMax)); Handles.color = Color.white; Handles.EndGUI (); EditorGUIUtility.AddCursorRect (position, MouseCursor.Link); return GUI.Button (position, label, LinkStyle); } }
1
0.889274
1
0.889274
game-dev
MEDIA
0.692807
game-dev,desktop-app
0.932772
1
0.932772
cfl-minds/drl_shape_optimization
11,456
src/tensorforce/examples/scripts/extraterrestrial_maurauders.py
# Copyright 2018 Tensorforce Team. All Rights Reserved. # # 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. # ============================================================================== """Defeat marauders from somewhere exterior to this planet. Keys: left, right - move. space - fire. """ import curses import numpy as np import sys from pycolab import ascii_art from pycolab import human_ui from pycolab import rendering from pycolab import things as plab_things from pycolab.prefab_parts import sprites as prefab_sprites # Not shown in this ASCII art diagram are the Sprites we use for laser blasts, # which control the characters listed in UPWARD_BOLT_CHARS and # DOWNWARD_BOLT_CHARS below. GAME_ART = [' X X X X X X X X ', # Row 0 ' X X X X X X X X ', ' X X X X X X X X ', ' X X X X X X X X ', ' X X X X X X X X ', ' ', # Row 5 ' ', ' ', ' ', ' ', ' ', # Row 10. If a Marauder ' BBBB BBBB BBBB BBBB ', # makes it to row 10, ' BBBB BBBB BBBB BBBB ', # the game is over. ' BBBB BBBB BBBB BBBB ', ' ', ' P '] # Characters listed in UPWARD_BOLT_CHARS are used for Sprites that represent # laser bolts that the player shoots toward Marauders. Add more characters if # you want to be able to have more than two of these bolts in the "air" at once. UPWARD_BOLT_CHARS = 'abcd' # Characters listed in DOWNWARD_BOLT_CHARS are used for Sprites that represent # laser bolts that Marauders shoot toward the player. Add more charcters if you # want more shooting from the Marauders. DOWNWARD_BOLT_CHARS = 'yz' # Shorthand for various points in the program: _ALL_BOLT_CHARS = UPWARD_BOLT_CHARS + DOWNWARD_BOLT_CHARS # To make life a bit easier for the player (and avoid the need for frame # stacking), we use different characters to indicate the directions that the # bolts go. If you'd like to make this game harder, you might try mapping both # kinds of bolts to the same character. LASER_REPAINT_MAPPING = dict( [(b, '^') for b in UPWARD_BOLT_CHARS] + [(b, '|') for b in DOWNWARD_BOLT_CHARS]) # These colours are only for humans to see in the CursesUi. COLOURS_FG = {' ': (0, 0, 0), # Space, inky blackness of. 'X': (999, 999, 999), # The Marauders. 'B': (400, 50, 30), # The bunkers. 'P': (0, 999, 0), # The player. '^': (0, 999, 999), # Bolts from player to aliens. '|': (0, 999, 999)} # Bolts from aliens to player. COLOURS_BG = {'^': (0, 0, 0), # Bolts from player to aliens. '|': (0, 0, 0)} # Bolts from aliens to player. def make_game(): """Builds and returns an Extraterrestrial Marauders game.""" return ascii_art.ascii_art_to_game( GAME_ART, what_lies_beneath=' ', sprites=dict( [('P', PlayerSprite)] + [(c, UpwardLaserBoltSprite) for c in UPWARD_BOLT_CHARS] + [(c, DownwardLaserBoltSprite) for c in DOWNWARD_BOLT_CHARS]), drapes=dict(X=MarauderDrape, B=BunkerDrape), update_schedule=['P', 'B', 'X'] + list(_ALL_BOLT_CHARS)) class BunkerDrape(plab_things.Drape): """A `Drape` for the bunkers at the bottom of the screen. Bunkers are gradually eroded by laser bolts, for which the user loses one point. Other than that, they don't really do much. If a laser bolt hits a bunker, this Drape leaves a note about it in the Plot---the bolt's Sprite checks this and removes itself from the board if it's present. """ def update(self, actions, board, layers, backdrop, things, the_plot): # Where are the laser bolts? Bolts from players or marauders do damage. bolts = np.logical_or.reduce([layers[c] for c in _ALL_BOLT_CHARS], axis=0) hits = bolts & self.curtain # Any hits to a bunker? np.logical_xor(self.curtain, hits, self.curtain) # If so, erode the bunker... the_plot.add_reward(-np.sum(hits)) # ...and impose a penalty. # Save the identities of bunker-striking bolts in the Plot. the_plot['bunker_hitters'] = [chr(c) for c in board[hits]] class MarauderDrape(plab_things.Drape): """A `Drape` for the marauders descending downward toward the player. The Marauders all move in lockstep, which makes them an ideal application of a Drape. Bits of the Drape get eroded by laser bolts from the player; each hit earns ten points. If the Drape goes completely empty, or if any Marauder makes it down to row 10, the game terminates. As with `BunkerDrape`, if a laser bolt hits a Marauder, this Drape leaves a note about it in the Plot; the bolt's Sprite checks this and removes itself from the board if present. """ def __init__(self, curtain, character): # The constructor just sets the Marauder's initial horizontal direction. super(MarauderDrape, self).__init__(curtain, character) self._dx = -1 def update(self, actions, board, layers, backdrop, things, the_plot): # Where are the laser bolts? Only bolts from the player kill a Marauder. bolts = np.logical_or.reduce([layers[c] for c in UPWARD_BOLT_CHARS], axis=0) hits = bolts & self.curtain # Any hits to Marauders? np.logical_xor(self.curtain, hits, self.curtain) # If so, zap the marauder... the_plot.add_reward(np.sum(hits)*10) # ...and supply a reward. # Save the identities of marauder-striking bolts in the Plot. the_plot['marauder_hitters'] = [chr(c) for c in board[hits]] # If no Marauders are left, or if any are sitting on row 10, end the game. if (not self.curtain.any()) or self.curtain[10, :].any(): return the_plot.terminate_episode() # i.e. return None. # We move faster if there are fewer Marauders. The odd divisor causes speed # jumps to align on the high sides of multiples of 8; so, speed increases as # the number of Marauders decreases to 32 (or 24 etc.), not 31 (or 23 etc.). if the_plot.frame % max(1, np.sum(self.curtain)//8.0000001): return # If any Marauder reaches either side of the screen, reverse horizontal # motion and advance vertically one row. if np.any(self.curtain[:, 0] | self.curtain[:, -1]): self._dx = -self._dx self.curtain[:] = np.roll(self.curtain, shift=1, axis=0) self.curtain[:] = np.roll(self.curtain, shift=self._dx, axis=1) class PlayerSprite(prefab_sprites.MazeWalker): """A `Sprite` for our player. This `Sprite` simply ties actions to going left and right. In interactive settings, the user can also quit. """ def __init__(self, corner, position, character): """Simply indicates to the superclass that we can't walk off the board.""" super(PlayerSprite, self).__init__( corner, position, character, impassable='', confined_to_board=True) def update(self, actions, board, layers, backdrop, things, the_plot): del layers, backdrop, things # Unused. if actions == 0: # go leftward? self._west(board, the_plot) elif actions == 1: # go rightward? self._east(board, the_plot) elif actions == 4: # quit? the_plot.terminate_episode() class UpwardLaserBoltSprite(prefab_sprites.MazeWalker): """Laser bolts shot from the player toward Marauders.""" def __init__(self, corner, position, character): """Starts the Sprite in a hidden position off of the board.""" super(UpwardLaserBoltSprite, self).__init__( corner, position, character, impassable='') self._teleport((-1, -1)) def update(self, actions, board, layers, backdrop, things, the_plot): if self.visible: self._fly(board, layers, things, the_plot) elif actions == 2: self._fire(layers, things, the_plot) def _fly(self, board, layers, things, the_plot): """Handles the behaviour of visible bolts flying toward Marauders.""" # Disappear if we've hit a Marauder or a bunker. if (self.character in the_plot['bunker_hitters'] or self.character in the_plot['marauder_hitters']): return self._teleport((-1, -1)) # Otherwise, northward! self._north(board, the_plot) def _fire(self, layers, things, the_plot): """Launches a new bolt from the player.""" # We don't fire if the player fired another bolt just now. if the_plot.get('last_player_shot') == the_plot.frame: return the_plot['last_player_shot'] = the_plot.frame # We start just above the player. row, col = things['P'].position self._teleport((row-1, col)) class DownwardLaserBoltSprite(prefab_sprites.MazeWalker): """Laser bolts shot from Marauders toward the player.""" def __init__(self, corner, position, character): """Starts the Sprite in a hidden position off of the board.""" super(DownwardLaserBoltSprite, self).__init__( corner, position, character, impassable='') self._teleport((-1, -1)) def update(self, actions, board, layers, backdrop, things, the_plot): if self.visible: self._fly(board, layers, things, the_plot) else: self._fire(layers, the_plot) def _fly(self, board, layers, things, the_plot): """Handles the behaviour of visible bolts flying toward the player.""" # Disappear if we've hit a bunker. if self.character in the_plot['bunker_hitters']: return self._teleport((-1, -1)) # End the game if we've hit the player. if self.position == things['P'].position: the_plot.terminate_episode() self._south(board, the_plot) def _fire(self, layers, the_plot): """Launches a new bolt from a random Marauder.""" # We don't fire if another Marauder fired a bolt just now. if the_plot.get('last_marauder_shot') == the_plot.frame: return the_plot['last_marauder_shot'] = the_plot.frame # Which Marauder should fire the laser bolt? col = np.random.choice(np.nonzero(layers['X'].sum(axis=0))[0]) row = np.nonzero(layers['X'][:, col])[0][-1] + 1 # Move ourselves just below that Marauder. self._teleport((row, col)) def get_ui(): repainter = rendering.ObservationCharacterRepainter(LASER_REPAINT_MAPPING) # Make a CursesUi to play it with. ui = human_ui.CursesUi( keys_to_actions={curses.KEY_LEFT: 0, curses.KEY_RIGHT: 1, ' ': 2, # shoot -1: 3}, # no-op repainter=repainter, delay=300, colour_fg=COLOURS_FG, colour_bg=COLOURS_BG) return ui
1
0.865922
1
0.865922
game-dev
MEDIA
0.932266
game-dev
0.954516
1
0.954516
unresolved3169/Altay-Old
1,277
src/pocketmine/block/Carrot.php
<?php /* * * ____ _ _ __ __ _ __ __ ____ * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \ * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) | * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/ * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author PocketMine Team * @link http://www.pocketmine.net/ * * */ declare(strict_types=1); namespace pocketmine\block; use pocketmine\item\Item; use pocketmine\item\ItemFactory; class Carrot extends Crops{ protected $id = self::CARROT_BLOCK; public function __construct(int $meta = 0){ $this->meta = $meta; } public function getName() : string{ return "Carrot Block"; } public function getDropsForCompatibleTool(Item $item) : array{ return [ ItemFactory::get(Item::CARROT, 0, $this->meta >= 0x07 ? mt_rand(1, 4) : 1) ]; } public function getPickedItem() : Item{ return ItemFactory::get(Item::CARROT); } }
1
0.848549
1
0.848549
game-dev
MEDIA
0.539737
game-dev
0.86184
1
0.86184
ggnkua/Atari_ST_Sources
7,439
ASM/Various/Thomas Binder/VT52FIX/VT52FIX.S
;*********************************************** ;* Modulname : VT52FIX.S * ;* (c)1994 by MAXON-Computer * ;* Autor : Thomas Binder * ;* Zweck : TSR-Programm, das einige * ;* Fehler in der VT52-Emula- * ;* tion des Falcon030 behebt * ;* Compiler : Pure Assembler 03.02.1992 * ;* Erstellt am : 02.01.1994 * ;* Letzte nderung: 10.01.1994 * ;*********************************************** super mc68030 equ _longframe,$59e equ xconout,$57e text ; Ist VT52FIX bereits installiert? pea is_installed(pc) move.w #38,-(sp) ; Supexec trap #14 addq.l #6,sp tst.w d0 bne already_installed ; Ist der Rechner wirklich ein F030? pea check_f030(pc) move.w #38,-(sp) ; Supexec trap #14 addq.l #6,sp tst.w d0 beq no_falcon ; Routinen einklinken pea install(pc) move.w #38,-(sp) ; Supexec trap #14 addq.l #6,sp ; Anfangsadresse der Line-A-Variablen merken aline #0 move.l d0,lineavar ; Erfolgsmeldung ausgeben pea patch_text(pc) move.w #9,-(sp) ; Cconws trap #1 addq.l #6,sp ; Gre des resident zu haltenden Speicherbereichs ; berechnen und Programm mit Ptermres beenden move.l #$100,d0 move.l 4(sp),a0 add.l $c(a0),d0 add.l $14(a0),d0 add.l $1c(a0),d0 clr.w -(sp) move.l d0,-(sp) move.w #49,-(sp) ; Ptermres trap #1 ; Meldung ausgeben, da die Routine bereits in- ; stalliert ist already_installed: pea already_installed_text(pc) bra.s out ; Meldung ausgeben, da der Rechner kein Falcon ; ist no_falcon: pea no_falcon_text(pc) out: move.w #9,-(sp) ; Cconws trap #1 ; Programm verlassen clr.w -(sp) ; Pterm0 trap #1 ; Die neue conout-Routine dc.b "XBRAVTFX" old_conout: dc.l 0 new_conout: move.l sp,a0 ; wenn wir noch nicht in einer Escape-Sequenz ; sind, das Zeichen "normal" behandeln tst.w in_escape(pc) beq normal_char ; ansonsten prfen, ob mit diesem Zeichen die ; Sequenz festgelegt wird addq.w #1,escape_count cmpi.w #1,escape_count(pc) bne continue_escape ; Escape-Sequenz beginnt, ist es eine, die korri- ; giert werden mu? cmpi.b #'j',7(a0) ; save cursor position bne.s l1 ; Bei ESC j die aktuelle Cursorposition aus den ; negativen Line-A-Variablen auslesen move.l lineavar(pc),a1 move.l -$1c(a1),saved_curpos ; Jeweils 32 addieren, da ESC k spter durch ESC Y ; emuliert wird addi.l #$200020,saved_curpos clr.w 6(a0) clr.w in_escape bra back l1: cmpi.b #'k',7(a0) ; restore cursor position bne.s l2 ; Die gespeicherte Cursorposition wird per ESC Y ; angesprungen move.w #'Y',-(sp) move.w #2,-(sp) bsr old_out addq.l #4,sp move.w saved_curpos+2(pc),-(sp) move.w #2,-(sp) bsr old_out addq.l #4,sp move.w saved_curpos(pc),-(sp) move.w #2,-(sp) bsr.s old_out addq.l #4,sp ; Gespeicherte Position lschen, da nach VT52- ; Konvention die gesicherte Position durch ESC k ; verloren geht move.l #$200020,saved_curpos clr.w in_escape rts l2: cmpi.b #'b',7(a0) ; set foreground color bne.s l3 ; Hier nur das Flag setzen, da ESC b angefangen ; wurde und dafr sorgen, da die begonne Escape- ; Sequenz abgebrochen wird (einfach noch ein NUL ; senden, da ESC NUL wirkungslos ist) move.w #2,in_escape clr.w 6(a0) bra.s back l3: cmpi.b #'c',7(a0) ; set background color bne.s l4 ; Wie oben, nur fr ESC c move.w #3,in_escape clr.w 6(a0) bra.s back l4: cmpi.b #'Y',7(a0) ; position cursor beq.s back ; Wenn es nicht ESC Y war, das Escape-Sequenz-Flag ; lschen (nur ESC Y bentigt zustzliche Para- ; meter, ESC b und ESC c werden ja separat behan- ; delt clr.w in_escape bra.s back ; Normales Zeichen ausgeben, dabei vorher testen, ; ob die x-Cursorposition noch fehlerfrei ist ; (also kleiner oder gleich dem Maximalwert) ; Ist das Zeichen ein Escape, das entsprechende ; Flag setzen normal_char: cmpi.b #27,7(a0) bne.s no_escape move.w #1,in_escape clr.w escape_count no_escape: ; Ist x-Position auerhalb des zulssigen ; Bereichs? move.l lineavar(pc),a1 move.w -$1c(a1),d0 cmp.w -$2c(a1),d0 bls.s back ; wenn ja, X-Position auf 0 setzen (hchst ; unsauber, da Schreibzugriff auf negative ; Line-A-Variable, aber leider notwendig) clr.w -$1c(a1) ; Die alte conout-Routine aufrufen back: old_out: move.l old_conout(pc),a0 jmp (a0) ; Mit Escape-Sequenzen fortfahren, die mehr als ; einen Parameter erhalten (ESC b, ESC c und ; ESC Y, wobei letztere nicht korrigiert werden ; mu) continue_escape: ; Ist es ESC Y? cmpi.w #1,in_escape(pc) bne.s correction ; Wenn ja, ist dies das letzte Parameterzeichen? cmpi.w #3,escape_count(pc) bne.s back ; Ja, also Escape-Flag lschen clr.w in_escape bra.s back correction: ; ESC b bzw. ESC c ausfhren, leider mit Schreib- ; zugriff aus die negativen Line-A-Variablen :( move.l lineavar(pc),a1 cmpi.w #2,in_escape(pc) bne.s background_color clr.w in_escape move.w 6(a0),-$24(a1) rts background_color: clr.w in_escape move.w 6(a0),-$26(a1) rts ; Neue Routine fr RAWCON:; hier mu nur geprft ; werden, ob die x-Cursorposition im zulssigen ; Bereich liegt, da es ja hier keine Escape- ; Sequenzen gibt dc.b "XBRAVTFX" old_rawconout: dc.l 0 new_rawconout: ; siehe oben move.l lineavar(pc),a0 move.w -$1c(a0),d0 cmp.w -$2c(a0),d0 bls.s rawcon_back clr.w -$1c(a0) ; Die alte conout-Routine aufrufen rawcon_back: move.l old_rawconout(pc),a0 jmp (a0) ; Diese Routine prft anhand des _MCH-Cookies, ob ; der Rechner ein Falcon ist check_f030: clr.w d0 move.l $5a0,d1 beq.s back2 move.l d1,a0 loop2: tst.l (a0) beq.s back2 cmpi.l #'_MCH',(a0)+ bne.s goon2 cmpi.l #$30000,(a0) bne.s back2 moveq #1,d0 back2: rts goon2: addq.l #4,a0 bra.s loop2 ; Diese Routine prft, ob in der XBRA-Kette des ; xconout-Vektors die Limit-Routine bereits einge- ; klinkt ist is_installed: move.l xconout+8,a0 ; Xconout-Vektor loop: cmpi.l #'XBRA',-12(a0) bne.s not_installed cmpi.l #'VTFX',-8(a0) beq.s installed move.l -4(a0),a0 bra.s loop installed: moveq #1,d0 rts not_installed: clr.w d0 rts ; Neue conout/rawconout-Routinen einklinken install: move.l xconout+2*4,old_conout move.l #new_conout,xconout+2*4 move.l xconout+5*4,old_rawconout move.l #new_rawconout,xconout+5*4 ; Position fr ESC k initialisieren move.l #$200020,saved_curpos rts data no_falcon_text: dc.b 13,10,"Machine is not a Falcon030!" dc.b 13,10,0 even patch_text: dc.b 13,10,"VT52FIX installed!" dc.b 13,10,0 even already_installed_text: dc.b 13,10,"VT52FIX is already " dc.b "installed!",13,10,0 bss lineavar: ds.l 1 saved_curpos: ds.l 1 in_escape: ds.w 1 escape_count: ds.w 1
1
0.896182
1
0.896182
game-dev
MEDIA
0.733292
game-dev,embedded-firmware
0.983105
1
0.983105
gameplay3d/gameplay-deps
9,794
bullet-2.82-r2704/Extras/Serialize/ReadBulletSample/BulletDataExtractor.cpp
#include "BulletDataExtractor.h" #include "../BulletFileLoader/btBulletFile.h" #include <stdio.h> ///work-in-progress ///This ReadBulletSample is kept as simple as possible without dependencies to the Bullet SDK. ///It can be used to load .bullet data for other physics SDKs ///For a more complete example how to load and convert Bullet data using the Bullet SDK check out ///the Bullet/Demos/SerializeDemo and Bullet/Serialize/BulletWorldImporter using namespace Bullet; enum LocalBroadphaseNativeTypes { // polyhedral convex shapes BOX_SHAPE_PROXYTYPE, TRIANGLE_SHAPE_PROXYTYPE, TETRAHEDRAL_SHAPE_PROXYTYPE, CONVEX_TRIANGLEMESH_SHAPE_PROXYTYPE, CONVEX_HULL_SHAPE_PROXYTYPE, CONVEX_POINT_CLOUD_SHAPE_PROXYTYPE, CUSTOM_POLYHEDRAL_SHAPE_TYPE, //implicit convex shapes IMPLICIT_CONVEX_SHAPES_START_HERE, SPHERE_SHAPE_PROXYTYPE, MULTI_SPHERE_SHAPE_PROXYTYPE, CAPSULE_SHAPE_PROXYTYPE, CONE_SHAPE_PROXYTYPE, CONVEX_SHAPE_PROXYTYPE, CYLINDER_SHAPE_PROXYTYPE, UNIFORM_SCALING_SHAPE_PROXYTYPE, MINKOWSKI_SUM_SHAPE_PROXYTYPE, MINKOWSKI_DIFFERENCE_SHAPE_PROXYTYPE, BOX_2D_SHAPE_PROXYTYPE, CONVEX_2D_SHAPE_PROXYTYPE, CUSTOM_CONVEX_SHAPE_TYPE, //concave shapes CONCAVE_SHAPES_START_HERE, //keep all the convex shapetype below here, for the check IsConvexShape in broadphase proxy! TRIANGLE_MESH_SHAPE_PROXYTYPE, SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE, ///used for demo integration FAST/Swift collision library and Bullet FAST_CONCAVE_MESH_PROXYTYPE, //terrain TERRAIN_SHAPE_PROXYTYPE, ///Used for GIMPACT Trimesh integration GIMPACT_SHAPE_PROXYTYPE, ///Multimaterial mesh MULTIMATERIAL_TRIANGLE_MESH_PROXYTYPE, EMPTY_SHAPE_PROXYTYPE, STATIC_PLANE_PROXYTYPE, CUSTOM_CONCAVE_SHAPE_TYPE, CONCAVE_SHAPES_END_HERE, COMPOUND_SHAPE_PROXYTYPE, SOFTBODY_SHAPE_PROXYTYPE, HFFLUID_SHAPE_PROXYTYPE, HFFLUID_BUOYANT_CONVEX_SHAPE_PROXYTYPE, INVALID_SHAPE_PROXYTYPE, MAX_BROADPHASE_COLLISION_TYPES }; btBulletDataExtractor::btBulletDataExtractor() { } btBulletDataExtractor::~btBulletDataExtractor() { } void btBulletDataExtractor::convertAllObjects(bParse::btBulletFile* bulletFile2) { int i; for (i=0;i<bulletFile2->m_collisionShapes.size();i++) { btCollisionShapeData* shapeData = (btCollisionShapeData*)bulletFile2->m_collisionShapes[i]; if (shapeData->m_name) printf("converting shape %s\n", shapeData->m_name); void* shape = convertCollisionShape(shapeData); } } void* btBulletDataExtractor::convertCollisionShape( btCollisionShapeData* shapeData ) { void* shape = 0; switch (shapeData->m_shapeType) { case STATIC_PLANE_PROXYTYPE: { btStaticPlaneShapeData* planeData = (btStaticPlaneShapeData*)shapeData; void* shape = createPlaneShape(planeData->m_planeNormal,planeData->m_planeConstant, planeData->m_localScaling); break; } case CYLINDER_SHAPE_PROXYTYPE: case CAPSULE_SHAPE_PROXYTYPE: case BOX_SHAPE_PROXYTYPE: case SPHERE_SHAPE_PROXYTYPE: case MULTI_SPHERE_SHAPE_PROXYTYPE: case CONVEX_HULL_SHAPE_PROXYTYPE: { btConvexInternalShapeData* bsd = (btConvexInternalShapeData*)shapeData; switch (shapeData->m_shapeType) { case BOX_SHAPE_PROXYTYPE: { shape = createBoxShape(bsd->m_implicitShapeDimensions, bsd->m_localScaling,bsd->m_collisionMargin); break; } case SPHERE_SHAPE_PROXYTYPE: { shape = createSphereShape(bsd->m_implicitShapeDimensions.m_floats[0],bsd->m_localScaling, bsd->m_collisionMargin); break; } #if 0 case CAPSULE_SHAPE_PROXYTYPE: { btCapsuleShapeData* capData = (btCapsuleShapeData*)shapeData; switch (capData->m_upAxis) { case 0: { shape = createCapsuleShapeX(implicitShapeDimensions.getY(),2*implicitShapeDimensions.getX()); break; } case 1: { shape = createCapsuleShapeY(implicitShapeDimensions.getX(),2*implicitShapeDimensions.getY()); break; } case 2: { shape = createCapsuleShapeZ(implicitShapeDimensions.getX(),2*implicitShapeDimensions.getZ()); break; } default: { printf("error: wrong up axis for btCapsuleShape\n"); } }; break; } case CYLINDER_SHAPE_PROXYTYPE: { btCylinderShapeData* cylData = (btCylinderShapeData*) shapeData; btVector3 halfExtents = implicitShapeDimensions+margin; switch (cylData->m_upAxis) { case 0: { shape = createCylinderShapeX(halfExtents.getY(),halfExtents.getX()); break; } case 1: { shape = createCylinderShapeY(halfExtents.getX(),halfExtents.getY()); break; } case 2: { shape = createCylinderShapeZ(halfExtents.getX(),halfExtents.getZ()); break; } default: { printf("unknown Cylinder up axis\n"); } }; break; } case MULTI_SPHERE_SHAPE_PROXYTYPE: { btMultiSphereShapeData* mss = (btMultiSphereShapeData*)bsd; int numSpheres = mss->m_localPositionArraySize; int i; for ( i=0;i<numSpheres;i++) { tmpPos[i].deSerializeFloat(mss->m_localPositionArrayPtr[i].m_pos); radii[i] = mss->m_localPositionArrayPtr[i].m_radius; } shape = new btMultiSphereShape(&tmpPos[0],&radii[0],numSpheres); break; } case CONVEX_HULL_SHAPE_PROXYTYPE: { btConvexHullShapeData* convexData = (btConvexHullShapeData*)bsd; int numPoints = convexData->m_numUnscaledPoints; btAlignedObjectArray<btVector3> tmpPoints; tmpPoints.resize(numPoints); int i; for ( i=0;i<numPoints;i++) { if (convexData->m_unscaledPointsFloatPtr) tmpPoints[i].deSerialize(convexData->m_unscaledPointsFloatPtr[i]); if (convexData->m_unscaledPointsDoublePtr) tmpPoints[i].deSerializeDouble(convexData->m_unscaledPointsDoublePtr[i]); } shape = createConvexHullShape(); return shape; break; } #endif default: { printf("error: cannot create shape type (%d)\n",shapeData->m_shapeType); } } break; } #if 0 case TRIANGLE_MESH_SHAPE_PROXYTYPE: { btTriangleMeshShapeData* trimesh = (btTriangleMeshShapeData*)shapeData; btTriangleIndexVertexArray* meshInterface = createMeshInterface(trimesh->m_meshInterface); if (!meshInterface->getNumSubParts()) { return 0; } btVector3 scaling; scaling.deSerializeFloat(trimesh->m_meshInterface.m_scaling); meshInterface->setScaling(scaling); btOptimizedBvh* bvh = 0; btBvhTriangleMeshShape* trimeshShape = createBvhTriangleMeshShape(meshInterface,bvh); trimeshShape->setMargin(trimesh->m_collisionMargin); shape = trimeshShape; if (trimesh->m_triangleInfoMap) { btTriangleInfoMap* map = createTriangleInfoMap(); map->deSerialize(*trimesh->m_triangleInfoMap); trimeshShape->setTriangleInfoMap(map); #ifdef USE_INTERNAL_EDGE_UTILITY gContactAddedCallback = btAdjustInternalEdgeContactsCallback; #endif //USE_INTERNAL_EDGE_UTILITY } //printf("trimesh->m_collisionMargin=%f\n",trimesh->m_collisionMargin); break; } case COMPOUND_SHAPE_PROXYTYPE: { btCompoundShapeData* compoundData = (btCompoundShapeData*)shapeData; btCompoundShape* compoundShape = createCompoundShape(); btAlignedObjectArray<btCollisionShape*> childShapes; for (int i=0;i<compoundData->m_numChildShapes;i++) { btCollisionShape* childShape = convertCollisionShape(compoundData->m_childShapePtr[i].m_childShape); if (childShape) { btTransform localTransform; localTransform.deSerializeFloat(compoundData->m_childShapePtr[i].m_transform); compoundShape->addChildShape(localTransform,childShape); } else { printf("error: couldn't create childShape for compoundShape\n"); } } shape = compoundShape; break; } case GIMPACT_SHAPE_PROXYTYPE: { btGImpactMeshShapeData* gimpactData = (btGImpactMeshShapeData*) shapeData; if (gimpactData->m_gimpactSubType == CONST_GIMPACT_TRIMESH_SHAPE) { btTriangleIndexVertexArray* meshInterface = createMeshInterface(gimpactData->m_meshInterface); btGImpactMeshShape* gimpactShape = createGimpactShape(meshInterface); btVector3 localScaling; localScaling.deSerializeFloat(gimpactData->m_localScaling); gimpactShape->setLocalScaling(localScaling); gimpactShape->setMargin(btScalar(gimpactData->m_collisionMargin)); gimpactShape->updateBound(); shape = gimpactShape; } else { printf("unsupported gimpact sub type\n"); } break; } case SOFTBODY_SHAPE_PROXYTYPE: { return 0; } #endif default: { printf("unsupported shape type (%d)\n",shapeData->m_shapeType); } } return shape; } void* btBulletDataExtractor::createBoxShape( const Bullet::btVector3FloatData& halfDimensions, const Bullet::btVector3FloatData& localScaling, float collisionMargin) { printf("createBoxShape with halfDimensions %f,%f,%f\n",halfDimensions.m_floats[0], halfDimensions.m_floats[1],halfDimensions.m_floats[2]); return 0; } void* btBulletDataExtractor::createSphereShape( float radius, const Bullet::btVector3FloatData& localScaling, float collisionMargin) { printf("createSphereShape with radius %f\n",radius); return 0; } void* btBulletDataExtractor::createPlaneShape( const btVector3FloatData& planeNormal, float planeConstant, const Bullet::btVector3FloatData& localScaling) { printf("createPlaneShape with normal %f,%f,%f and planeConstant\n",planeNormal.m_floats[0], planeNormal.m_floats[1],planeNormal.m_floats[2],planeConstant); return 0; }
1
0.961609
1
0.961609
game-dev
MEDIA
0.860226
game-dev
0.969253
1
0.969253
ProjectIgnis/CardScripts
1,705
official/c49941059.lua
--奇跡のマジック・ゲート --Magic Gate of Miracles --Updated by Larry126 local s,id=GetID() function s.initial_effect(c) --Change 1 of opponent's attack positions to defense position, then take control of it local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_CONTROL+CATEGORY_POSITION) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCondition(s.condition) e1:SetTarget(s.target) e1:SetOperation(s.operation) c:RegisterEffect(e1) end function s.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.IsExistingMatchingCard(aux.FaceupFilter(Card.IsRace,RACE_SPELLCASTER),tp,LOCATION_MZONE,0,2,nil) end function s.filter(c) return c:IsControlerCanBeChanged() and c:IsAttackPos() and c:IsCanChangePosition() end function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chk==0 then return Duel.IsExistingMatchingCard(s.filter,tp,0,LOCATION_MZONE,1,nil) end Duel.SetOperationInfo(0,CATEGORY_POSITION,nil,1,1-tp,LOCATION_MZONE) Duel.SetOperationInfo(0,CATEGORY_CONTROL,nil,1,1-tp,LOCATION_MZONE) end function s.operation(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONTROL) local g=Duel.SelectMatchingCard(tp,s.filter,tp,0,LOCATION_MZONE,1,1,nil) if #g>0 and Duel.ChangePosition(g,POS_FACEUP_DEFENSE,POS_FACEDOWN_DEFENSE)>0 then Duel.BreakEffect() if Duel.GetControl(g,tp) then --Cannot be destroyed by battle local e1=Effect.CreateEffect(e:GetHandler()) e1:SetDescription(3000) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE+EFFECT_FLAG_CLIENT_HINT) e1:SetRange(LOCATION_MZONE) e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE) e1:SetValue(1) e1:SetReset(RESET_EVENT|RESETS_STANDARD) g:GetFirst():RegisterEffect(e1) end end end
1
0.934616
1
0.934616
game-dev
MEDIA
0.986004
game-dev
0.910051
1
0.910051
ABTSoftware/SciChart.Wpf.Examples
1,853
Sandbox/WPFChartPerformanceBenchmark/ChartProviders.Common/DataProviders/RandomPointsGenerator.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using ChartProviders.Common.Extensions; namespace ChartProviders.Common.DataProviders { public class RandomPointsGenerator { protected readonly double _xMin; protected readonly double _xMax; protected readonly double _yMin; protected readonly double _yMax; protected readonly Random _random; private int _i; public RandomPointsGenerator(double xMin, double xMax, double yMin, double yMax) { _xMin = xMin; _xMax = xMax; _yMin = yMin; _yMax = yMax; _random = new Random(); } public RandomPointsGenerator(int seed, double xMin, double xMax, double yMin, double yMax) { _xMin = xMin; _xMax = xMax; _yMin = yMin; _yMax = yMax; _random = new Random(seed); } public virtual XyData GetRandomPoints(int count) { var doubleSeries = new XyData(); doubleSeries.XData = new List<double>(); doubleSeries.YData = new List<double>(); // Generate a slightly positive biased random walk // y[i] = y[i-1] + random, // where random is in the range -0.5, +0.5 for (int i = 0; i < count; i++) { var next = Next(); ((IList<double>)doubleSeries.XData).Add(next.X); ((IList<double>)doubleSeries.YData).Add(next.Y); } return doubleSeries; } public Point Next() { double nextX = _random.NextDouble(_xMin, _xMax); double nextY = _random.NextDouble(_yMin, _yMax); return new Point(nextX, nextY); } } }
1
0.830354
1
0.830354
game-dev
MEDIA
0.247918
game-dev
0.878175
1
0.878175
mc-zhonghuang/Urticaria-Public
3,999
src/main/java/net/minecraft/entity/passive/EntityCow.java
package net.minecraft.entity.passive; import net.minecraft.block.Block; import net.minecraft.entity.EntityAgeable; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.*; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.pathfinding.PathNavigateGround; import net.minecraft.util.BlockPos; import net.minecraft.world.World; public class EntityCow extends EntityAnimal { public EntityCow(final World worldIn) { super(worldIn); this.setSize(0.9F, 1.3F); ((PathNavigateGround) this.getNavigator()).setAvoidsWater(true); this.tasks.addTask(0, new EntityAISwimming(this)); this.tasks.addTask(1, new EntityAIPanic(this, 2.0D)); this.tasks.addTask(2, new EntityAIMate(this, 1.0D)); this.tasks.addTask(3, new EntityAITempt(this, 1.25D, Items.wheat, false)); this.tasks.addTask(4, new EntityAIFollowParent(this, 1.25D)); this.tasks.addTask(5, new EntityAIWander(this, 1.0D)); this.tasks.addTask(6, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F)); this.tasks.addTask(7, new EntityAILookIdle(this)); } protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(10.0D); this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.20000000298023224D); } /** * Returns the sound this mob makes while it's alive. */ protected String getLivingSound() { return "mob.cow.say"; } /** * Returns the sound this mob makes when it is hurt. */ protected String getHurtSound() { return "mob.cow.hurt"; } /** * Returns the sound this mob makes on death. */ protected String getDeathSound() { return "mob.cow.hurt"; } protected void playStepSound(final BlockPos pos, final Block blockIn) { this.playSound("mob.cow.step", 0.15F, 1.0F); } /** * Returns the volume for the sounds this mob makes. */ protected float getSoundVolume() { return 0.4F; } protected Item getDropItem() { return Items.leather; } /** * Drop 0-2 items of this living's type */ protected void dropFewItems(final boolean p_70628_1_, final int p_70628_2_) { int i = this.rand.nextInt(3) + this.rand.nextInt(1 + p_70628_2_); for (int j = 0; j < i; ++j) { this.dropItem(Items.leather, 1); } i = this.rand.nextInt(3) + 1 + this.rand.nextInt(1 + p_70628_2_); for (int k = 0; k < i; ++k) { if (this.isBurning()) { this.dropItem(Items.cooked_beef, 1); } else { this.dropItem(Items.beef, 1); } } } /** * Called when a player interacts with a mob. e.g. gets milk from a cow, gets into the saddle on a pig. */ public boolean interact(final EntityPlayer player) { final ItemStack itemstack = player.inventory.getCurrentItem(); if (itemstack != null && itemstack.getItem() == Items.bucket && !player.capabilities.isCreativeMode && !this.isChild()) { if (itemstack.stackSize-- == 1) { player.inventory.setInventorySlotContents(player.inventory.currentItem, new ItemStack(Items.milk_bucket)); } else if (!player.inventory.addItemStackToInventory(new ItemStack(Items.milk_bucket))) { player.dropPlayerItemWithRandomChoice(new ItemStack(Items.milk_bucket, 1, 0), false); } return true; } else { return super.interact(player); } } public EntityCow createChild(final EntityAgeable ageable) { return new EntityCow(this.worldObj); } public float getEyeHeight() { return this.height; } }
1
0.733993
1
0.733993
game-dev
MEDIA
0.998074
game-dev
0.950691
1
0.950691
OpenViva/OpenViva-Unity
10,591
Assets/Scripts/AmbienceDirector.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace viva { public class AmbienceDirector : MonoBehaviour { [HideInInspector] [SerializeField] private List<AudioSource> windowSourcesA = new List<AudioSource>(); private List<AudioSource> windowSourcesB = new List<AudioSource>(); [HideInInspector] [SerializeField] private List<AudioSource> daytimeOnlySources = new List<AudioSource>(); [HideInInspector] [SerializeField] private List<AudioSource> nighttimeOnlySources = new List<AudioSource>(); private bool usingAmbienceSourcesA = true; [Header("Ambience")] [SerializeField] private Ambience defaultAmbience = null; [SerializeField] private List<AudioSource> globalAmbienceSourcesA = new List<AudioSource>(); [SerializeField] private List<AudioSource> globalAmbienceSourcesB = new List<AudioSource>(); private Coroutine ambienceChangeCoroutine = null; private Ambience currentAmbience = null; private int currentAmbienceEnterCount = 0; private Coroutine windowChangeCoroutine = null; private Coroutine randomSoundsCoroutine = null; private bool usingWindowSourcesA = true; public void InitializeAmbience() { foreach (var outdoorSource in windowSourcesA) { windowSourcesB.Add(CopyAudioSource(outdoorSource, outdoorSource.gameObject)); } foreach (var globalSource in globalAmbienceSourcesA) { globalAmbienceSourcesB.Add(CopyAudioSource(globalSource, globalSource.gameObject)); } if (currentAmbience == null) { EnterAmbience(null); } } private AudioSource CopyAudioSource(AudioSource source, GameObject parent) { AudioSource copy = parent.AddComponent<AudioSource>(); copy.priority = source.priority; copy.pitch = source.pitch; copy.panStereo = source.panStereo; copy.spatialBlend = source.spatialBlend; copy.reverbZoneMix = source.reverbZoneMix; copy.spread = source.spread; copy.dopplerLevel = source.dopplerLevel; copy.volume = 0.0f; copy.rolloffMode = source.rolloffMode; copy.minDistance = source.minDistance; copy.maxDistance = source.maxDistance; copy.SetCustomCurve(AudioSourceCurveType.CustomRolloff, source.GetCustomCurve(AudioSourceCurveType.CustomRolloff)); return copy; } public void EnterAmbience(Ambience ambience) { if (ambience == null) { ambience = defaultAmbience; } else { currentAmbienceEnterCount++; } Debug.Log("[Ambience] " + ambience.name); currentAmbience = ambience; FadeAmbience(); if (randomSoundsCoroutine != null) { GameDirector.instance.StopCoroutine(randomSoundsCoroutine); randomSoundsCoroutine = null; } if (currentAmbience.randomSounds != null) { randomSoundsCoroutine = GameDirector.instance.StartCoroutine(RandomSoundPlayer()); } } public void ExitAmbience(Ambience ambience) { if (ambience == currentAmbience) { if (--currentAmbienceEnterCount == 0) { EnterAmbience(null); } } } private IEnumerator RandomSoundPlayer() { while (true) { if (globalAmbienceSourcesA.Count > 0 && globalAmbienceSourcesB.Count > 0) { if (usingAmbienceSourcesA) { globalAmbienceSourcesA[0].PlayOneShot(currentAmbience.randomSounds.GetRandomAudioClip()); } else { globalAmbienceSourcesB[0].PlayOneShot(currentAmbience.randomSounds.GetRandomAudioClip()); } } yield return new WaitForSeconds(5.0f + Random.value * 10.0f); } } public void FadeAmbience() { FadeGlobalAmbience(); FadeLocaleAmbience(); } private void FadeGlobalAmbience() { if (ambienceChangeCoroutine != null) { GameDirector.instance.StopCoroutine(ambienceChangeCoroutine); } if (currentAmbience == null) { SetAudioSourcesVolume(globalAmbienceSourcesA, 0.0f); SetAudioSourcesVolume(globalAmbienceSourcesB, 0.0f); ambienceChangeCoroutine = null; return; } List<AudioSource> fadeInSources; List<AudioSource> fadeOutSources; if (usingAmbienceSourcesA) { fadeInSources = globalAmbienceSourcesB; fadeOutSources = globalAmbienceSourcesA; SetAndPlayLoopAudioSources(globalAmbienceSourcesB, currentAmbience.GetAudio(GameDirector.skyDirector.daySegment, GameDirector.instance.userIsIndoors)); } else { fadeInSources = globalAmbienceSourcesA; fadeOutSources = globalAmbienceSourcesB; SetAndPlayLoopAudioSources(globalAmbienceSourcesA, currentAmbience.GetAudio(GameDirector.skyDirector.daySegment, GameDirector.instance.userIsIndoors)); } usingAmbienceSourcesA = !usingAmbienceSourcesA; ambienceChangeCoroutine = GameDirector.instance.StartCoroutine(CrossFadeSound(fadeInSources, fadeOutSources, false, 2.0f)); } private void SetDaySegmentSounds(SkyDirector.DaySegment daySegment, float fadeVal) { //cross fade from expected previous daySegment state if (daySegment == SkyDirector.DaySegment.NIGHT) { SetAudioSourcesVolume(daytimeOnlySources, 1.0f - fadeVal); SetAudioSourcesVolume(nighttimeOnlySources, fadeVal); } else if (daySegment == SkyDirector.DaySegment.MORNING) { SetAudioSourcesVolume(daytimeOnlySources, fadeVal); SetAudioSourcesVolume(nighttimeOnlySources, 1.0f - fadeVal); } else { SetAudioSourcesVolume(daytimeOnlySources, 1.0f); SetAudioSourcesVolume(nighttimeOnlySources, 0.0f); } } private void FadeLocaleAmbience() { if (currentAmbience == null) { // Debug.LogError("[Ambience] currentAmbience is null"); return; } List<AudioSource> fadeInSources; List<AudioSource> fadeOutSources; if (usingWindowSourcesA) { fadeInSources = windowSourcesB; fadeOutSources = windowSourcesA; } else { fadeInSources = windowSourcesA; fadeOutSources = windowSourcesB; } usingWindowSourcesA = !usingWindowSourcesA; if (GameDirector.instance.userIsIndoors) { Debug.Log("[Ambience] Indoor"); //turn on outdoor window source sounds if now indoors SetAndPlayLoopAudioSources(fadeInSources, currentAmbience.GetAudio(GameDirector.skyDirector.daySegment, false)); } else { Debug.Log("[Ambience] Outdoor"); //turn off window source sounds if now outdoors SetAndPlayLoopAudioSources(fadeInSources, null); } if (windowChangeCoroutine != null) { GameDirector.instance.StopCoroutine(windowChangeCoroutine); } windowChangeCoroutine = GameDirector.instance.StartCoroutine(CrossFadeSound(fadeInSources, fadeOutSources, true, 2.0f)); } private float? GetFirstSourceVolume(List<AudioSource> sources) { if (sources == null) { return null; } foreach (AudioSource source in sources) { if (source) { return source.volume; } } return null; } private IEnumerator CrossFadeSound(List<AudioSource> fadeInSources, List<AudioSource> fadeOutSources, bool windowSources, float fadeDuration) { float? fadeInStartSound = GetFirstSourceVolume(fadeInSources); float? fadeOutStartSound = GetFirstSourceVolume(fadeOutSources); if (fadeInStartSound.HasValue && fadeOutStartSound.HasValue) { float interval = 0.2f; while (fadeInStartSound < 1.0f) { fadeInStartSound = Mathf.Min(1.0f, fadeInStartSound.Value + interval / fadeDuration); SetAudioSourcesVolume(fadeInSources, fadeInStartSound.Value); SetAudioSourcesVolume(fadeOutSources, 1.0f - fadeInStartSound.Value); SetDaySegmentSounds(GameDirector.skyDirector.daySegment, fadeInStartSound.Value); yield return new WaitForSeconds(interval); //don't update every frame } } if (windowSources) { windowChangeCoroutine = null; } else { ambienceChangeCoroutine = null; } } private void SetAndPlayLoopAudioSources(List<AudioSource> sources, AudioClip clip) { for (int i = 0; i < sources.Count; i++) { AudioSource source = sources[i]; source.clip = clip; source.loop = true; source.Play(); } } private void SetAudioSourcesVolume(List<AudioSource> sources, float volume) { for (int i = 0; i < sources.Count; i++) { sources[i].volume = volume; } } } }
1
0.683387
1
0.683387
game-dev
MEDIA
0.777669
game-dev,audio-video-media
0.972406
1
0.972406
GLX-ILLUSION/Unreal-Internal-Base
11,557
UnrealSDKBase/SDK/MagicLeapSharedWorld_Package.cpp
/** * Name: GreedIsGood * Version: fodase */ #include "pch.h" namespace CG { // -------------------------------------------------- // # Structs Functions // -------------------------------------------------- /** * Function: * RVA -> 0x00000000 * Name -> Function MagicLeapSharedWorld.MagicLeapSharedWorldGameMode.SendSharedWorldDataToClients * Flags -> () */ bool AMagicLeapSharedWorldGameMode::SendSharedWorldDataToClients() { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>("Function MagicLeapSharedWorld.MagicLeapSharedWorldGameMode.SendSharedWorldDataToClients"); AMagicLeapSharedWorldGameMode_SendSharedWorldDataToClients_Params params {}; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } /** * Function: * RVA -> 0x00000000 * Name -> Function MagicLeapSharedWorld.MagicLeapSharedWorldGameMode.SelectChosenOne * Flags -> () */ void AMagicLeapSharedWorldGameMode::SelectChosenOne() { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>("Function MagicLeapSharedWorld.MagicLeapSharedWorldGameMode.SelectChosenOne"); AMagicLeapSharedWorldGameMode_SelectChosenOne_Params params {}; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } /** * Function: * RVA -> 0x00000000 * Name -> DelegateFunction MagicLeapSharedWorld.MagicLeapSharedWorldGameMode.MagicLeapOnNewLocalDataFromClients__DelegateSignature * Flags -> () */ void AMagicLeapSharedWorldGameMode::MagicLeapOnNewLocalDataFromClients__DelegateSignature() { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>("DelegateFunction MagicLeapSharedWorld.MagicLeapSharedWorldGameMode.MagicLeapOnNewLocalDataFromClients__DelegateSignature"); AMagicLeapSharedWorldGameMode_MagicLeapOnNewLocalDataFromClients__DelegateSignature_Params params {}; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } /** * Function: * RVA -> 0x00000000 * Name -> Function MagicLeapSharedWorld.MagicLeapSharedWorldGameMode.DetermineSharedWorldData * Flags -> () * Parameters: * struct FMagicLeapSharedWorldSharedData NewSharedWorldData (Parm, OutParm, NativeAccessSpecifierPublic) */ void AMagicLeapSharedWorldGameMode::DetermineSharedWorldData(struct FMagicLeapSharedWorldSharedData* NewSharedWorldData) { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>("Function MagicLeapSharedWorld.MagicLeapSharedWorldGameMode.DetermineSharedWorldData"); AMagicLeapSharedWorldGameMode_DetermineSharedWorldData_Params params {}; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (NewSharedWorldData != nullptr) *NewSharedWorldData = params.NewSharedWorldData; } /** * Function: * RVA -> 0x00000000 * Name -> PredefinedFunction AMagicLeapSharedWorldGameMode.StaticClass * Flags -> (Predefined, Static) */ UClass* AMagicLeapSharedWorldGameMode::StaticClass() { static UClass* ptr = nullptr; if (!ptr) ptr = UObject::FindClass("Class MagicLeapSharedWorld.MagicLeapSharedWorldGameMode"); return ptr; } /** * Function: * RVA -> 0x00000000 * Name -> Function MagicLeapSharedWorld.MagicLeapSharedWorldGameState.OnReplicate_SharedWorldData * Flags -> () */ void AMagicLeapSharedWorldGameState::OnReplicate_SharedWorldData() { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>("Function MagicLeapSharedWorld.MagicLeapSharedWorldGameState.OnReplicate_SharedWorldData"); AMagicLeapSharedWorldGameState_OnReplicate_SharedWorldData_Params params {}; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } /** * Function: * RVA -> 0x00000000 * Name -> Function MagicLeapSharedWorld.MagicLeapSharedWorldGameState.OnReplicate_AlignmentTransforms * Flags -> () */ void AMagicLeapSharedWorldGameState::OnReplicate_AlignmentTransforms() { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>("Function MagicLeapSharedWorld.MagicLeapSharedWorldGameState.OnReplicate_AlignmentTransforms"); AMagicLeapSharedWorldGameState_OnReplicate_AlignmentTransforms_Params params {}; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } /** * Function: * RVA -> 0x00000000 * Name -> DelegateFunction MagicLeapSharedWorld.MagicLeapSharedWorldGameState.MagicLeapSharedWorldEvent__DelegateSignature * Flags -> () */ void AMagicLeapSharedWorldGameState::MagicLeapSharedWorldEvent__DelegateSignature() { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>("DelegateFunction MagicLeapSharedWorld.MagicLeapSharedWorldGameState.MagicLeapSharedWorldEvent__DelegateSignature"); AMagicLeapSharedWorldGameState_MagicLeapSharedWorldEvent__DelegateSignature_Params params {}; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } /** * Function: * RVA -> 0x00000000 * Name -> Function MagicLeapSharedWorld.MagicLeapSharedWorldGameState.CalculateXRCameraRootTransform * Flags -> () */ struct FTransform AMagicLeapSharedWorldGameState::CalculateXRCameraRootTransform() { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>("Function MagicLeapSharedWorld.MagicLeapSharedWorldGameState.CalculateXRCameraRootTransform"); AMagicLeapSharedWorldGameState_CalculateXRCameraRootTransform_Params params {}; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } /** * Function: * RVA -> 0x00000000 * Name -> PredefinedFunction AMagicLeapSharedWorldGameState.StaticClass * Flags -> (Predefined, Static) */ UClass* AMagicLeapSharedWorldGameState::StaticClass() { static UClass* ptr = nullptr; if (!ptr) ptr = UObject::FindClass("Class MagicLeapSharedWorld.MagicLeapSharedWorldGameState"); return ptr; } /** * Function: * RVA -> 0x00000000 * Name -> Function MagicLeapSharedWorld.MagicLeapSharedWorldPlayerController.ServerSetLocalWorldData * Flags -> () * Parameters: * struct FMagicLeapSharedWorldLocalData LocalWorldReplicationData (ConstParm, Parm, ReferenceParm, NativeAccessSpecifierPublic) */ void AMagicLeapSharedWorldPlayerController::ServerSetLocalWorldData(const struct FMagicLeapSharedWorldLocalData& LocalWorldReplicationData) { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>("Function MagicLeapSharedWorld.MagicLeapSharedWorldPlayerController.ServerSetLocalWorldData"); AMagicLeapSharedWorldPlayerController_ServerSetLocalWorldData_Params params {}; params.LocalWorldReplicationData = LocalWorldReplicationData; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } /** * Function: * RVA -> 0x00000000 * Name -> Function MagicLeapSharedWorld.MagicLeapSharedWorldPlayerController.ServerSetAlignmentTransforms * Flags -> () * Parameters: * struct FMagicLeapSharedWorldAlignmentTransforms InAlignmentTransforms (ConstParm, Parm, ReferenceParm, NativeAccessSpecifierPublic) */ void AMagicLeapSharedWorldPlayerController::ServerSetAlignmentTransforms(const struct FMagicLeapSharedWorldAlignmentTransforms& InAlignmentTransforms) { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>("Function MagicLeapSharedWorld.MagicLeapSharedWorldPlayerController.ServerSetAlignmentTransforms"); AMagicLeapSharedWorldPlayerController_ServerSetAlignmentTransforms_Params params {}; params.InAlignmentTransforms = InAlignmentTransforms; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } /** * Function: * RVA -> 0x00000000 * Name -> Function MagicLeapSharedWorld.MagicLeapSharedWorldPlayerController.IsChosenOne * Flags -> () */ bool AMagicLeapSharedWorldPlayerController::IsChosenOne() { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>("Function MagicLeapSharedWorld.MagicLeapSharedWorldPlayerController.IsChosenOne"); AMagicLeapSharedWorldPlayerController_IsChosenOne_Params params {}; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } /** * Function: * RVA -> 0x00000000 * Name -> Function MagicLeapSharedWorld.MagicLeapSharedWorldPlayerController.ClientSetChosenOne * Flags -> () * Parameters: * bool bChosenOne (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) */ void AMagicLeapSharedWorldPlayerController::ClientSetChosenOne(bool bChosenOne) { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>("Function MagicLeapSharedWorld.MagicLeapSharedWorldPlayerController.ClientSetChosenOne"); AMagicLeapSharedWorldPlayerController_ClientSetChosenOne_Params params {}; params.bChosenOne = bChosenOne; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } /** * Function: * RVA -> 0x00000000 * Name -> Function MagicLeapSharedWorld.MagicLeapSharedWorldPlayerController.ClientMarkReadyForSendingLocalData * Flags -> () */ void AMagicLeapSharedWorldPlayerController::ClientMarkReadyForSendingLocalData() { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>("Function MagicLeapSharedWorld.MagicLeapSharedWorldPlayerController.ClientMarkReadyForSendingLocalData"); AMagicLeapSharedWorldPlayerController_ClientMarkReadyForSendingLocalData_Params params {}; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } /** * Function: * RVA -> 0x00000000 * Name -> Function MagicLeapSharedWorld.MagicLeapSharedWorldPlayerController.CanSendLocalDataToServer * Flags -> () */ bool AMagicLeapSharedWorldPlayerController::CanSendLocalDataToServer() { static UFunction* fn = nullptr; if (!fn) fn = UObject::FindObject<UFunction>("Function MagicLeapSharedWorld.MagicLeapSharedWorldPlayerController.CanSendLocalDataToServer"); AMagicLeapSharedWorldPlayerController_CanSendLocalDataToServer_Params params {}; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } /** * Function: * RVA -> 0x00000000 * Name -> PredefinedFunction AMagicLeapSharedWorldPlayerController.StaticClass * Flags -> (Predefined, Static) */ UClass* AMagicLeapSharedWorldPlayerController::StaticClass() { static UClass* ptr = nullptr; if (!ptr) ptr = UObject::FindClass("Class MagicLeapSharedWorld.MagicLeapSharedWorldPlayerController"); return ptr; } }
1
0.728333
1
0.728333
game-dev
MEDIA
0.984002
game-dev
0.638409
1
0.638409
Scholarpei/SCUT-For_our_red_king
941
For_Our_Red_King/newanimationcomponent.h
#ifndef NEWANIMATIONCOMPONENT_H #define NEWANIMATIONCOMPONENT_H #include "animationComponent.h" #include "game.h" class NewAnimationComponent : public AnimationComponent { public: explicit NewAnimationComponent(class GameObject* gameObject=nullptr,int drawOrder = 200,Game* game = nullptr); ~NewAnimationComponent(); //相比于animationComponent有以下更改:初始化的时候可以设置相对于原先位置的偏移量、设置画的Width与Height而不是由GameObject决定 //图片非连续的动画,为了制作连续的效果而通过改变绘画的透明度实现动画效果 //其余部分保持一致 void Draw()override; void setOffset(float xoffset,float yoffset);//设置偏移量 void setRect(int w,int h);//设置宽高 void Update()override; void setTransformDirection(bool dir);//设置渐变方向 private: Game* mGame; short TICKS_PER_FRAME = SYSTEM::durationPerFrame; bool transformDirection = 1; //!<不透明度渐变方向 1为逐渐出现,0为逐渐消失 int mWidth,mHeight;//!<单独的绘制区域大小 float xOffset,yOffset;//!<绘制相比于GameObject原先的offset }; #endif // NEWANIMATIONCOMPONENT_H
1
0.766764
1
0.766764
game-dev
MEDIA
0.950295
game-dev
0.699165
1
0.699165
cortex-command-community/Cortex-Command-Community-Project
4,432
external/sources/SDL3-3.2.10/src/video/vita/SDL_vitamessagebox.c
/* Simple DirectMedia Layer Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "SDL_internal.h" #ifdef SDL_VIDEO_DRIVER_VITA #include "SDL_vitavideo.h" #include "SDL_vitamessagebox.h" #include <psp2/message_dialog.h> #ifdef SDL_VIDEO_RENDER_VITA_GXM #include "../../render/vitagxm/SDL_render_vita_gxm_tools.h" #endif // SDL_VIDEO_RENDER_VITA_GXM bool VITA_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonID) { #ifdef SDL_VIDEO_RENDER_VITA_GXM SceMsgDialogParam param; SceMsgDialogUserMessageParam msgParam; SceMsgDialogButtonsParam buttonParam; SceDisplayFrameBuf dispparam; char message[512]; SceMsgDialogResult dialog_result; SceCommonDialogErrorCode init_result; bool setup_minimal_gxm = false; if (messageboxdata->numbuttons > 3) { return false; } SDL_zero(param); sceMsgDialogParamInit(&param); param.mode = SCE_MSG_DIALOG_MODE_USER_MSG; SDL_zero(msgParam); SDL_snprintf(message, sizeof(message), "%s\r\n\r\n%s", messageboxdata->title, messageboxdata->message); msgParam.msg = (const SceChar8 *)message; SDL_zero(buttonParam); if (messageboxdata->numbuttons == 3) { msgParam.buttonType = SCE_MSG_DIALOG_BUTTON_TYPE_3BUTTONS; msgParam.buttonParam = &buttonParam; buttonParam.msg1 = messageboxdata->buttons[0].text; buttonParam.msg2 = messageboxdata->buttons[1].text; buttonParam.msg3 = messageboxdata->buttons[2].text; } else if (messageboxdata->numbuttons == 2) { msgParam.buttonType = SCE_MSG_DIALOG_BUTTON_TYPE_YESNO; } else if (messageboxdata->numbuttons == 1) { msgParam.buttonType = SCE_MSG_DIALOG_BUTTON_TYPE_OK; } param.userMsgParam = &msgParam; dispparam.size = sizeof(dispparam); init_result = sceMsgDialogInit(&param); // Setup display if it hasn't been initialized before if (init_result == SCE_COMMON_DIALOG_ERROR_GXM_IS_UNINITIALIZED) { gxm_minimal_init_for_common_dialog(); init_result = sceMsgDialogInit(&param); setup_minimal_gxm = true; } gxm_init_for_common_dialog(); if (init_result >= 0) { while (sceMsgDialogGetStatus() == SCE_COMMON_DIALOG_STATUS_RUNNING) { gxm_swap_for_common_dialog(); } SDL_zero(dialog_result); sceMsgDialogGetResult(&dialog_result); if (dialog_result.buttonId == SCE_MSG_DIALOG_BUTTON_ID_BUTTON1) { *buttonID = messageboxdata->buttons[0].buttonID; } else if (dialog_result.buttonId == SCE_MSG_DIALOG_BUTTON_ID_BUTTON2) { *buttonID = messageboxdata->buttons[1].buttonID; } else if (dialog_result.buttonId == SCE_MSG_DIALOG_BUTTON_ID_BUTTON3) { *buttonID = messageboxdata->buttons[2].buttonID; } else if (dialog_result.buttonId == SCE_MSG_DIALOG_BUTTON_ID_YES) { *buttonID = messageboxdata->buttons[0].buttonID; } else if (dialog_result.buttonId == SCE_MSG_DIALOG_BUTTON_ID_NO) { *buttonID = messageboxdata->buttons[1].buttonID; } else if (dialog_result.buttonId == SCE_MSG_DIALOG_BUTTON_ID_OK) { *buttonID = messageboxdata->buttons[0].buttonID; } sceMsgDialogTerm(); } else { return false; } gxm_term_for_common_dialog(); if (setup_minimal_gxm) { gxm_minimal_term_for_common_dialog(); } return true; #else (void)messageboxdata; (void)buttonID; return SDL_Unsupported(); #endif // SDL_VIDEO_RENDER_VITA_GXM } #endif // SDL_VIDEO_DRIVER_VITA
1
0.885394
1
0.885394
game-dev
MEDIA
0.344747
game-dev
0.913648
1
0.913648
foundryvtt/pf2e
1,877
src/module/system/action-macros/thievery/pick-a-lock.ts
import { ActionMacroHelpers, SkillActionOptions } from "../index.ts"; import { SingleCheckAction } from "@actor/actions/index.ts"; function pickALock(options: SkillActionOptions): void { const slug = options?.skill ?? "thievery"; const rollOptions = ["action:pick-a-lock"]; const modifiers = options?.modifiers; ActionMacroHelpers.simpleRollActionCheck({ actors: options.actors, actionGlyph: options.glyph ?? "D", title: "PF2E.Actions.PickALock.Title", checkContext: (opts) => ActionMacroHelpers.defaultCheckContext(opts, { modifiers, rollOptions, slug }), traits: ["manipulate"], event: options.event, callback: options.callback, difficultyClass: options.difficultyClass, extraNotes: (selector: string) => [ ActionMacroHelpers.note(selector, "PF2E.Actions.PickALock", "criticalSuccess"), ActionMacroHelpers.note(selector, "PF2E.Actions.PickALock", "success"), ActionMacroHelpers.note(selector, "PF2E.Actions.PickALock", "criticalFailure"), ], }).catch((error: Error) => { ui.notifications.error(error.message); throw error; }); } const action = new SingleCheckAction({ cost: 2, description: "PF2E.Actions.PickALock.Description", img: "systems/pf2e/icons/features/classes/thief.webp", name: "PF2E.Actions.PickALock.Title", notes: [ { outcome: ["criticalSuccess"], text: "PF2E.Actions.PickALock.Notes.criticalSuccess" }, { outcome: ["success"], text: "PF2E.Actions.PickALock.Notes.success" }, { outcome: ["criticalFailure"], text: "PF2E.Actions.PickALock.Notes.criticalFailure" }, ], rollOptions: ["action:pick-a-lock"], section: "skill", slug: "pick-a-lock", statistic: "thievery", traits: ["manipulate"], }); export { pickALock as legacy, action };
1
0.928711
1
0.928711
game-dev
MEDIA
0.741273
game-dev
0.952317
1
0.952317
AlmasB/FXGL
2,884
fxgl-samples/src/main/java/sandbox/circlegame/BlockCollisionComponent.java
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB (almaslvl@gmail.com). * See LICENSE for details. */ package sandbox.circlegame; import com.almasb.fxgl.core.math.FXGLMath; import com.almasb.fxgl.dsl.components.RandomMoveComponent; import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.entity.component.Component; import javafx.geometry.Point2D; import java.util.List; import static com.almasb.fxgl.dsl.FXGL.getGameWorld; import static com.almasb.fxgl.dsl.FXGL.random; /** * @author Almas Baimagambetov (almaslvl@gmail.com) */ public class BlockCollisionComponent extends Component { private RandomMoveComponent randomMove; private List<Entity> blocks; private Point2D prevPos; @Override public void onAdded() { randomMove = entity.getComponent(RandomMoveComponent.class); blocks = getGameWorld().getEntitiesByType(CircleNNType.BLOCK); prevPos = entity.getPosition(); } @Override public void onUpdate(double tpf) { for (var block : blocks) { if (block.isColliding(entity)) { entity.translate(randomMove.getVelocity().negateLocal()); changeDirection(); //var vel = randomMove.getVelocity(); //applyVelocityManually(); return; } } //entity.setPosition(prevPos); //prevPos = entity.getPosition(); } private void changeDirection() { var newDirectionVector = randomMove.getVelocity(); var angle = FXGLMath.toDegrees(Math.atan(newDirectionVector.y / newDirectionVector.x)) + random(-45, 45); randomMove.setDirectionAngle(newDirectionVector.x > 0 ? angle : 180 + angle); } private void applyVelocityManually() { var vel = randomMove.getVelocity(); var dx = Math.signum(vel.x); var dy = Math.signum(vel.y); for (int i = 0; i < (int) vel.x; i++) { entity.translateX(dx); boolean collision = false; for (Entity block : blocks) { if (block.isColliding(entity)) { collision = true; break; } } if (collision) { entity.translateX(-dx); break; } } for (int i = 0; i < (int) vel.y; i++) { entity.translateY(dy); boolean collision = false; for (Entity block : blocks) { if (block.isColliding(entity)) { collision = true; break; } } if (collision) { entity.translateY(-dy); break; } } } @Override public boolean isComponentInjectionRequired() { return false; } }
1
0.840778
1
0.840778
game-dev
MEDIA
0.813525
game-dev
0.948992
1
0.948992
ProjectEQ/projecteqquests
1,719
nadox/a_Luggald_High_Priest.pl
#BeginFile: nadox\a_Luggald_High_Priest.pl #Script for Crypt of Nadox - a Luggald High Priest #Spawns Innoruk if all apprentices are killed before the end of the ceremony my $counter; #Counter for dead apprentices my $begin; #Shows that event has started sub EVENT_SPAWN { $counter = 0; $begin = 0; } sub EVENT_SIGNAL { if (($signal == 1) && ($begin == 0)) { quest::shout("Innoruuk protect us from the invaders in our land."); quest::settimer("ceremony",600); #10 minute ceremony quest::signal(227082,0); #Signal apprentices to chant $begin = 1; } if ($signal == 2) { $counter += 1; #apprentice death if ($counter == 1) { quest::shout("As long as we have our numbers, Innoruuk will provide us with strength."); } if ($counter == 2) { quest::shout("Innoruuk protect us from the invaders in our land."); } if ($counter == 3) { quest::shout("As long as we have our numbers, Innoruuk will provide us with strength."); } if ($counter == 4) { quest::shout("Innoruuk protect us from the invaders in our land."); } if ($counter == 5) { quest::shout("'Master Innoruuk, the invaders have intruded into your sacred place of worship! We are in need of your wisdom and power!"); quest::stoptimer("ceremony"); quest::spawn2(227331,0,0,1714,669,-87,360); #Innoruk (Nadox) quest::depop_withtimer(); } } } sub EVENT_TIMER { if ($timer eq "ceremony") { #Ceremony failed, reset quest::stoptimer("ceremony"); quest::shout("The ceremony is complete!!"); $counter = 0; $begin = 0; } } sub EVENT_DEATH_COMPLETE { quest::stoptimer("ceremony"); } #EndFile nadox\a_Luggald_High_Priest.pl (227073)
1
0.824833
1
0.824833
game-dev
MEDIA
0.98574
game-dev
0.857908
1
0.857908
Emudofus/Dofus
2,700
com/ankamagames/dofus/network/messages/game/inventory/items/ObjectDeletedMessage.as
package com.ankamagames.dofus.network.messages.game.inventory.items { import com.ankamagames.jerakine.network.NetworkMessage; import com.ankamagames.jerakine.network.INetworkMessage; import flash.utils.ByteArray; import com.ankamagames.jerakine.network.CustomDataWrapper; import com.ankamagames.jerakine.network.ICustomDataOutput; import com.ankamagames.jerakine.network.ICustomDataInput; [Trusted] public class ObjectDeletedMessage extends NetworkMessage implements INetworkMessage { public static const protocolId:uint = 3024; private var _isInitialized:Boolean = false; public var objectUID:uint = 0; override public function get isInitialized():Boolean { return (this._isInitialized); } override public function getMessageId():uint { return (3024); } public function initObjectDeletedMessage(objectUID:uint=0):ObjectDeletedMessage { this.objectUID = objectUID; this._isInitialized = true; return (this); } override public function reset():void { this.objectUID = 0; this._isInitialized = false; } override public function pack(output:ICustomDataOutput):void { var data:ByteArray = new ByteArray(); this.serialize(new CustomDataWrapper(data)); writePacket(output, this.getMessageId(), data); } override public function unpack(input:ICustomDataInput, length:uint):void { this.deserialize(input); } public function serialize(output:ICustomDataOutput):void { this.serializeAs_ObjectDeletedMessage(output); } public function serializeAs_ObjectDeletedMessage(output:ICustomDataOutput):void { if (this.objectUID < 0) { throw (new Error((("Forbidden value (" + this.objectUID) + ") on element objectUID."))); }; output.writeVarInt(this.objectUID); } public function deserialize(input:ICustomDataInput):void { this.deserializeAs_ObjectDeletedMessage(input); } public function deserializeAs_ObjectDeletedMessage(input:ICustomDataInput):void { this.objectUID = input.readVarUhInt(); if (this.objectUID < 0) { throw (new Error((("Forbidden value (" + this.objectUID) + ") on element of ObjectDeletedMessage.objectUID."))); }; } } }//package com.ankamagames.dofus.network.messages.game.inventory.items
1
0.74592
1
0.74592
game-dev
MEDIA
0.26155
game-dev
0.770631
1
0.770631
Goob-Station/Goob-Station-MRP
1,204
Content.Shared/Tools/Components/ToolTileCompatibleComponent.cs
using Content.Shared.DoAfter; using Content.Shared.Tools.Systems; using Robust.Shared.GameStates; using Robust.Shared.Map; using Robust.Shared.Serialization; namespace Content.Shared.Tools.Components; /// <summary> /// This is used for entities with <see cref="ToolComponent"/> that are additionally /// able to modify tiles. /// </summary> [RegisterComponent, NetworkedComponent] [Access(typeof(SharedToolSystem))] public sealed partial class ToolTileCompatibleComponent : Component { /// <summary> /// The time it takes to modify the tile. /// </summary> [DataField, ViewVariables(VVAccess.ReadWrite)] public TimeSpan Delay = TimeSpan.FromSeconds(0.5); /// <summary> /// Whether or not the tile being modified must be unobstructed /// </summary> [DataField, ViewVariables(VVAccess.ReadWrite)] public bool RequiresUnobstructed = true; } [Serializable, NetSerializable] public sealed partial class TileToolDoAfterEvent : DoAfterEvent { public NetCoordinates Coordinates; public TileToolDoAfterEvent(NetCoordinates coordinates) { Coordinates = coordinates; } public override DoAfterEvent Clone() { return this; } }
1
0.761752
1
0.761752
game-dev
MEDIA
0.837653
game-dev
0.719732
1
0.719732
opentibiabr/otservbr-global
1,889
data/npc/gnomincia.lua
local internalNpcName = "Gnomincia" local npcType = Game.createNpcType(internalNpcName) local npcConfig = {} npcConfig.name = internalNpcName npcConfig.description = internalNpcName npcConfig.health = 100 npcConfig.maxHealth = npcConfig.health npcConfig.walkInterval = 2000 npcConfig.walkRadius = 2 npcConfig.outfit = { lookType = 507, lookHead = 79, lookBody = 94, lookLegs = 94, lookFeet = 52, lookAddons = 0 } npcConfig.flags = { floorchange = false } local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) npcType.onThink = function(npc, interval) npcHandler:onThink(npc, interval) end npcType.onAppear = function(npc, creature) npcHandler:onAppear(npc, creature) end npcType.onDisappear = function(npc, creature) npcHandler:onDisappear(npc, creature) end npcType.onMove = function(npc, creature, fromPosition, toPosition) npcHandler:onMove(npc, creature, fromPosition, toPosition) end npcType.onSay = function(npc, creature, type, message) npcHandler:onSay(npc, creature, type, message) end npcType.onCloseChannel = function(npc, creature) npcHandler:onCloseChannel(npc, creature) end npcHandler:addModule(FocusModule:new(), npcConfig.name, true, true, true) npcConfig.shop = { { itemName = "teleport crystal", clientId = 16167, buy = 150 } } -- On buy npc shop message npcType.onBuyItem = function(npc, player, itemId, subType, amount, ignore, inBackpacks, totalCost) npc:sellItem(player, itemId, amount, subType, 0, ignore, inBackpacks) end -- On sell npc shop message npcType.onSellItem = function(npc, player, itemId, subtype, amount, ignore, name, totalCost) player:sendTextMessage(MESSAGE_INFO_DESCR, string.format("Sold %ix %s for %i gold.", amount, name, totalCost)) end -- On check npc shop message (look item) npcType.onCheckItem = function(npc, player, clientId, subType) end npcType:register(npcConfig)
1
0.920795
1
0.920795
game-dev
MEDIA
0.968181
game-dev
0.794151
1
0.794151
ethaniccc/Mockingbird
6,919
src/ethaniccc/Mockingbird/detections/Detection.php
<?php namespace ethaniccc\Mockingbird\detections; use ethaniccc\Mockingbird\detections\movement\CancellableMovement; use ethaniccc\Mockingbird\Mockingbird; use ethaniccc\Mockingbird\tasks\BanTask; use ethaniccc\Mockingbird\tasks\KickTask; use ethaniccc\Mockingbird\user\User; use ethaniccc\Mockingbird\user\UserManager; use pocketmine\event\Event; use pocketmine\network\mcpe\protocol\DataPacket; use pocketmine\player\Player; use pocketmine\Server; use pocketmine\utils\TextFormat; abstract class Detection{ public mixed $maxVL; public float $preVL = 0; public mixed $alerts; public mixed $suppression; public mixed $punishType; public mixed $punishable; public mixed $enabled; public string $subType; public string $name; protected static array $settings = []; protected int $vlSecondCount = 2; protected float $lowMax; protected float $mediumMax; private array $violations = []; private array $cooldown = []; public const PROBABILITY_LOW = 1; public const PROBABILITY_MEDIUM = 2; public const PROBABILITY_HIGH = 3; public function __construct(string $name, ?array $settings){ $this->name = $name; $this->subType = substr($this->name, -1); self::$settings[$name] = $settings === null ? ['enabled' => true, 'punish' => false] : $settings; $this->enabled = $this->getSetting('enabled'); $this->punishable = $this->getSetting('punish'); $this->punishType = $this->getSetting('punishment_type') ?? 'kick'; $this->suppression = $this->getSetting('suppression') ?? false; $this->maxVL = $this->getSetting('max_violations') ?? 25; $this->alerts = Mockingbird::getInstance()->getConfig()->get('alerts_enabled') ?? true; $this->lowMax = floor(pow($this->vlSecondCount, 1 / 4) * 5); $this->mediumMax = floor(sqrt($this->vlSecondCount) * 5); } public function getSetting(string $setting){ return self::$settings[$this->name][$setting] ?? null; } public abstract function handleReceive(DataPacket $packet, User $user) : void; public abstract function handleSend(DataPacket $packet, User $user) : void; public function canHandleSend() : bool{ return false; } public abstract function handleEvent(Event $event, User $user) : void; public function getCheatProbability() : int{ $violations = count($this->violations); if($violations <= $this->lowMax){ return self::PROBABILITY_LOW; }elseif($violations <= $this->mediumMax){ return self::PROBABILITY_MEDIUM; }else{ return self::PROBABILITY_HIGH; } } public function probabilityColor(int $probability) : string{ switch($probability){ case self::PROBABILITY_LOW: return TextFormat::GREEN . "Low"; case self::PROBABILITY_MEDIUM: return TextFormat::GOLD . "Medium"; case self::PROBABILITY_HIGH: return TextFormat::RED . "High"; } return ""; } // TODO: This can probably cause some lag on servers, find a way to do this *better* protected function fail(User $user, ?string $debugData = null, ?string $detailData = null) : void{ if(!$user->loggedIn){ return; } if(!isset($user->violations[$this->name])){ $user->violations[$this->name] = 0; } ++$user->violations[$this->name]; $this->violations[] = microtime(true); $this->violations = array_filter($this->violations, function(float $lastTime) : bool{ return microtime(true) - $lastTime <= $this->vlSecondCount * (20 / Server::getInstance()->getTicksPerSecond()); }); $name = $user->player->getName(); $cheatName = $this->name; $violations = round($user->violations[$this->name], 2); $staff = array_filter(Server::getInstance()->getOnlinePlayers(), function(Player $p) : bool{ $user = UserManager::getInstance()->get($p); return $p->hasPermission('mockingbird.alerts') && $user->alerts; }); if($this->alerts){ $cooldownStaff = array_filter($staff, function(Player $p) : bool{ $user = UserManager::getInstance()->get($p); if(!isset($this->cooldown[$p->getId()])){ $this->cooldown[$p->getId()] = microtime(true); return true; } if(microtime(true) - $this->cooldown[$p->getId()] >= $user->alertCooldown){ $this->cooldown[$p->getId()] = microtime(true); return true; }else{ return false; } }); $message = $this->getPlugin()->getPrefix() . ' ' . str_replace(['{player}', '{check}', '{vl}', '{probability}', '{detail}'], [$name, $cheatName, $violations, $this->probabilityColor($this->getCheatProbability()), ($detailData !== null ? $detailData . " ping={$user->transactionLatency}" : "ping={$user->transactionLatency}")], $this->getPlugin()->getConfig()->get('fail_message')); Server::getInstance()->broadcastMessage($message, $cooldownStaff); } if($this instanceof CancellableMovement && $this->suppression){ if(!$user->moveData->onGround){ $user->player->teleport($user->moveData->lastOnGroundLocation); }else{ $user->player->teleport($user->moveData->lastLocation); } } if($this->punishable && $violations >= $this->maxVL){ switch($this->punishType){ case 'kick': $user->loggedIn = false; $this->debug($user->player->getName() . ' was kicked for ' . $cheatName); $this->getPlugin()->getScheduler()->scheduleDelayedTask(new KickTask($user, $this->getPlugin()->getPrefix() . " " . $this->getPlugin()->getConfig()->get("punish_message_player")), 1); break; case 'ban': $user->loggedIn = false; $this->debug($user->player->getName() . ' was banned for ' . $cheatName); $this->getPlugin()->getScheduler()->scheduleDelayedTask(new BanTask($user, $this->getPlugin()->getPrefix() . " " . $this->getPlugin()->getConfig()->get("punish_message_player")), 1); break; } $message = $this->getPlugin()->getPrefix() . ' ' . str_replace(['{player}', '{detection}'], [$name, $cheatName], $this->getPlugin()->getConfig()->get('punish_message_staff')); Server::getInstance()->broadcastMessage($message, Mockingbird::getInstance()->getConfig()->get('punish_message_global') ? Server::getInstance()->getOnlinePlayers() : $staff); } if($debugData !== null){ $nameKey = strtolower($this->name ?? ''); if(!isset($user->debugCache[$nameKey])){ $user->debugCache[$nameKey] = ''; } $user->debugCache[$nameKey] .= $debugData . PHP_EOL; $this->debug($user->player->getName() . ': ' . $debugData); } } protected function debug($debugData, bool $logWrite = true) : void{ if($logWrite){ Mockingbird::getInstance()->debugTask->addData($debugData); } Mockingbird::getInstance()->getLogger()->debug($debugData); } protected function isDebug(User $user) : bool{ return strtolower($user->debugChannel ?? '') === strtolower($this->name ?? ''); } protected function reward(User $user, float $num) : void{ if(isset($user->violations[$this->name])){ $user->violations[$this->name] = max($user->violations[$this->name] - $num, 0); } } protected function getPlugin() : Mockingbird{ return Mockingbird::getInstance(); } }
1
0.955415
1
0.955415
game-dev
MEDIA
0.467485
game-dev,web-backend
0.972289
1
0.972289
OpenXRay/xray-15
12,304
cs/engine/xrGame/ui/UIActorMenuTrade.cpp
#include "stdafx.h" #include "UIActorMenu.h" #include "UI3tButton.h" #include "UIDragDropListEx.h" #include "UICharacterInfo.h" #include "UIFrameLineWnd.h" #include "UICellItem.h" #include "UIInventoryUtilities.h" #include "UICellItemFactory.h" #include "InventoryOwner.h" #include "Inventory.h" #include "Trade.h" #include "Entity.h" #include "Actor.h" #include "Weapon.h" #include "trade_parameters.h" #include "inventory_item_object.h" #include "string_table.h" #include "AI/Monsters/BaseMonster/base_monster.h" // ------------------------------------------------- void CUIActorMenu::InitTradeMode() { m_pInventoryBagList->Show (false); m_PartnerCharacterInfo->Show (true); m_PartnerMoney->Show (true); m_pTradeActorBagList->Show (true); m_pTradeActorList->Show (true); m_pTradePartnerBagList->Show (true); m_pTradePartnerList->Show (true); m_RightDelimiter->Show (true); m_LeftDelimiter->Show (true); m_LeftBackground->Show (true); m_PartnerBottomInfo->Show (true); m_PartnerWeight->Show (true); m_trade_button->Show (true); VERIFY ( m_pPartnerInvOwner ); m_pPartnerInvOwner->StartTrading(); InitInventoryContents ( m_pTradeActorBagList ); InitPartnerInventoryContents (); m_actor_trade = m_pActorInvOwner->GetTrade(); m_partner_trade = m_pPartnerInvOwner->GetTrade(); VERIFY ( m_actor_trade ); VERIFY ( m_partner_trade ); m_actor_trade->StartTradeEx ( m_pPartnerInvOwner ); m_partner_trade->StartTradeEx ( m_pActorInvOwner ); UpdatePrices(); } void CUIActorMenu::InitPartnerInventoryContents() { m_pTradePartnerBagList->ClearAll( true ); TIItemContainer items_list; m_pPartnerInvOwner->inventory().AddAvailableItems(items_list, true); std::sort (items_list.begin(), items_list.end(),InventoryUtilities::GreaterRoomInRuck); TIItemContainer::iterator itb = items_list.begin(); TIItemContainer::iterator ite = items_list.end(); for( ; itb != ite; ++itb ) { CUICellItem* itm = create_cell_item( *itb ); m_pTradePartnerBagList->SetItem( itm ); } m_trade_partner_inventory_state = m_pPartnerInvOwner->inventory().ModifyFrame(); } void CUIActorMenu::ColorizeItem(CUICellItem* itm, bool colorize) { if( colorize ) { itm->SetColor( color_rgba(255,100,100,255) ); } else { itm->SetColor( color_rgba(255,255,255,255) ); } } void CUIActorMenu::DeInitTradeMode() { if ( m_actor_trade ) { m_actor_trade->StopTrade(); } if ( m_partner_trade ) { m_partner_trade->StopTrade(); } if ( m_pPartnerInvOwner ) { m_pPartnerInvOwner->StopTrading(); } m_pInventoryBagList->Show (true); m_PartnerCharacterInfo->Show (false); m_PartnerMoney->Show (false); m_pTradeActorBagList->Show (false); m_pTradeActorList->Show (false); m_pTradePartnerBagList->Show (false); m_pTradePartnerList->Show (false); m_RightDelimiter->Show (false); m_LeftDelimiter->Show (false); m_LeftBackground->Show (false); m_PartnerBottomInfo->Show (false); m_PartnerWeight->Show (false); m_trade_button->Show (false); } bool CUIActorMenu::ToActorTrade(CUICellItem* itm, bool b_use_cursor_pos) { PIItem iitem = (PIItem)itm->m_pData; if ( !CanMoveToPartner( iitem ) ) { return false; } // if(m_pActorInvOwner->inventory().CanPutInRuck(iitem)) { CUIDragDropListEx* old_owner = itm->OwnerList(); CUIDragDropListEx* new_owner = NULL; EDDListType old_owner_type = GetListType(old_owner); if(b_use_cursor_pos) { new_owner = CUIDragDropListEx::m_drag_item->BackList(); VERIFY (new_owner==m_pTradeActorList); }else new_owner = m_pTradeActorList; bool result = (old_owner_type!=iActorBag) ? m_pActorInvOwner->inventory().Ruck(iitem) : true; VERIFY (result); CUICellItem* i = old_owner->RemoveItem(itm, (old_owner==new_owner) ); if(b_use_cursor_pos) new_owner->SetItem (i,old_owner->GetDragItemPosition()); else new_owner->SetItem (i); if ( old_owner_type != iActorBag ) { SendEvent_Item2Ruck (iitem, m_pActorInvOwner->object_id()); } return true; } } bool CUIActorMenu::ToPartnerTrade(CUICellItem* itm, bool b_use_cursor_pos) { PIItem iitem = (PIItem)itm->m_pData; if ( !m_pPartnerInvOwner->AllowItemToTrade( iitem, eItemPlaceRuck ) ) { ///R_ASSERT2( 0, make_string( "Partner can`t cell item (%s)", iitem->NameItem() ) ); Msg( "! Partner can`t cell item (%s)", iitem->NameItem() ); return false; } CUIDragDropListEx* old_owner = itm->OwnerList(); CUIDragDropListEx* new_owner = NULL; if(b_use_cursor_pos) { new_owner = CUIDragDropListEx::m_drag_item->BackList(); VERIFY (new_owner==m_pTradePartnerList); }else new_owner = m_pTradePartnerList; CUICellItem* i = old_owner->RemoveItem(itm, (old_owner==new_owner) ); if(b_use_cursor_pos) new_owner->SetItem (i,old_owner->GetDragItemPosition()); else new_owner->SetItem (i); UpdatePrices(); return true; } bool CUIActorMenu::ToPartnerTradeBag(CUICellItem* itm, bool b_use_cursor_pos) { CUIDragDropListEx* old_owner = itm->OwnerList(); CUIDragDropListEx* new_owner = NULL; if(b_use_cursor_pos) { new_owner = CUIDragDropListEx::m_drag_item->BackList(); VERIFY (new_owner==m_pTradePartnerBagList); }else new_owner = m_pTradePartnerBagList; CUICellItem* i = old_owner->RemoveItem(itm, (old_owner==new_owner) ); if(b_use_cursor_pos) new_owner->SetItem (i,old_owner->GetDragItemPosition()); else new_owner->SetItem (i); return true; } float CUIActorMenu::CalcItemsWeight(CUIDragDropListEx* pList) { float res = 0.0f; for( u32 i = 0; i < pList->ItemsCount(); ++i ) { CUICellItem* itm = pList->GetItemIdx(i); PIItem iitem = (PIItem)itm->m_pData; res += iitem->Weight(); for( u32 j = 0; j < itm->ChildsCount(); ++j ) { PIItem jitem = (PIItem)itm->Child(j)->m_pData; res += jitem->Weight(); } } return res; } u32 CUIActorMenu::CalcItemsPrice(CUIDragDropListEx* pList, CTrade* pTrade, bool bBuying) { u32 res = 0; for( u32 i = 0; i < pList->ItemsCount(); ++i ) { CUICellItem* itm = pList->GetItemIdx(i); PIItem iitem = (PIItem)itm->m_pData; res += pTrade->GetItemPrice(iitem, bBuying); for( u32 j = 0; j < itm->ChildsCount(); ++j ) { PIItem jitem = (PIItem)itm->Child(j)->m_pData; res += pTrade->GetItemPrice(jitem, bBuying); } } return res; } bool CUIActorMenu::CanMoveToPartner(PIItem pItem) { if(!pItem->CanTrade()) return false; if ( !m_pPartnerInvOwner->trade_parameters().enabled( CTradeParameters::action_buy(0), pItem->object().cNameSect() ) ) { return false; } float r1 = CalcItemsWeight( m_pTradeActorList ); // actor float r2 = CalcItemsWeight( m_pTradePartnerList ); // partner float itmWeight = pItem->Weight(); float partner_inv_weight = m_pPartnerInvOwner->inventory().CalcTotalWeight(); float partner_max_weight = m_pPartnerInvOwner->MaxCarryWeight(); if ( partner_inv_weight - r2 + r1 + itmWeight > partner_max_weight ) { return false; } return true; } void CUIActorMenu::UpdateActor() { if ( IsGameTypeSingle() ) { string64 buf; sprintf_s( buf, "%d RU", m_pActorInvOwner->get_money() ); m_ActorMoney->SetText( buf ); } else { UpdateActorMP(); } CActor* actor = smart_cast<CActor*>( m_pActorInvOwner ); if ( actor ) { CWeapon* wp = smart_cast<CWeapon*>( actor->inventory().ActiveItem() ); if ( wp ) { wp->ForceUpdateAmmo(); } }//actor InventoryUtilities::UpdateWeightStr( *m_ActorWeight, *m_ActorWeightMax, m_pActorInvOwner ); m_ActorWeight->AdjustWidthToText(); m_ActorWeightMax->AdjustWidthToText(); m_ActorBottomInfo->AdjustWidthToText(); Fvector2 pos = m_ActorWeight->GetWndPos(); pos.x = m_ActorWeightMax->GetWndPos().x - m_ActorWeight->GetWndSize().x - 5.0f; m_ActorWeight->SetWndPos( pos ); pos.x = pos.x - m_ActorBottomInfo->GetWndSize().x - 5.0f; m_ActorBottomInfo->SetWndPos( pos ); } void CUIActorMenu::UpdatePartnerBag() { string64 buf; CBaseMonster* monster = smart_cast<CBaseMonster*>( m_pPartnerInvOwner ); if ( monster || m_pPartnerInvOwner->use_simplified_visual() ) { m_PartnerWeight->SetText( "" ); } else if ( m_pPartnerInvOwner->InfinitiveMoney() ) { m_PartnerMoney->SetText( "--- RU" ); } else { sprintf_s( buf, "%d RU", m_pPartnerInvOwner->get_money() ); m_PartnerMoney->SetText( buf ); } LPCSTR kg_str = CStringTable().translate( "st_kg" ).c_str(); float total = CalcItemsWeight( m_pTradePartnerBagList ); sprintf_s( buf, "%.1f %s", total, kg_str ); m_PartnerWeight->SetText( buf ); m_PartnerWeight->AdjustWidthToText(); Fvector2 pos = m_PartnerWeight->GetWndPos(); pos.x = m_PartnerWeight_end_x - m_PartnerWeight->GetWndSize().x - 5.0f; m_PartnerWeight->SetWndPos( pos ); pos.x = pos.x - m_PartnerBottomInfo->GetWndSize().x - 5.0f; m_PartnerBottomInfo->SetWndPos( pos ); } void CUIActorMenu::UpdatePrices() { LPCSTR kg_str = CStringTable().translate( "st_kg" ).c_str(); UpdateActor(); UpdatePartnerBag(); u32 actor_price = CalcItemsPrice( m_pTradeActorList, m_partner_trade, true ); u32 partner_price = CalcItemsPrice( m_pTradePartnerList, m_partner_trade, false ); string64 buf; sprintf_s( buf, "%d RU", actor_price ); m_ActorTradePrice->SetText( buf ); m_ActorTradePrice->AdjustWidthToText(); sprintf_s( buf, "%d RU", partner_price ); m_PartnerTradePrice->SetText( buf ); m_PartnerTradePrice->AdjustWidthToText(); float actor_weight = CalcItemsWeight( m_pTradeActorList ); float partner_weight = CalcItemsWeight( m_pTradePartnerList ); sprintf_s( buf, "(%.1f %s)", actor_weight, kg_str ); m_ActorTradeWeightMax->SetText( buf ); sprintf_s( buf, "(%.1f %s)", partner_weight, kg_str ); m_PartnerTradeWeightMax->SetText( buf ); Fvector2 pos = m_ActorTradePrice->GetWndPos(); pos.x = m_ActorTradeWeightMax->GetWndPos().x - m_ActorTradePrice->GetWndSize().x - 5.0f; m_ActorTradePrice->SetWndPos( pos ); pos.x = pos.x - m_ActorTradeCaption->GetWndSize().x - 5.0f; m_ActorTradeCaption->SetWndPos( pos ); pos = m_PartnerTradePrice->GetWndPos(); pos.x = m_PartnerTradeWeightMax->GetWndPos().x - m_PartnerTradePrice->GetWndSize().x - 5.0f; m_PartnerTradePrice->SetWndPos( pos ); pos.x = pos.x - m_PartnerTradeCaption->GetWndSize().x - 5.0f; m_PartnerTradeCaption->SetWndPos( pos ); } void CUIActorMenu::OnBtnPerformTrade(CUIWindow* w, void* d) { if ( m_pTradeActorList->ItemsCount() == 0 && m_pTradePartnerList->ItemsCount() == 0 ) { return; } int actor_money = (int)m_pActorInvOwner->get_money(); int partner_money = (int)m_pPartnerInvOwner->get_money(); int actor_price = (int)CalcItemsPrice( m_pTradeActorList, m_partner_trade, true ); int partner_price = (int)CalcItemsPrice( m_pTradePartnerList, m_partner_trade, false ); int delta_price = actor_price - partner_price; actor_money += delta_price; partner_money -= delta_price; if ( ( actor_money >= 0 ) && ( partner_money >= 0 ) && ( actor_price >= 0 || partner_price > 0 ) ) { m_partner_trade->OnPerformTrade( partner_price, actor_price ); TransferItems( m_pTradeActorList, m_pTradePartnerBagList, m_partner_trade, true ); TransferItems( m_pTradePartnerList, m_pTradeActorBagList, m_partner_trade, false ); } else { if ( actor_money < 0 ) { CallMessageBoxOK( "not_enough_money_actor" ); } else if ( partner_money < 0 ) { CallMessageBoxOK( "not_enough_money_partner" ); } else { CallMessageBoxOK( "trade_dont_make" ); } } SetCurrentItem ( NULL ); UpdateItemsPlace (); } void CUIActorMenu::TransferItems( CUIDragDropListEx* pSellList, CUIDragDropListEx* pBuyList, CTrade* pTrade, bool bBuying ) { while ( pSellList->ItemsCount() ) { CUICellItem* cell_item = pSellList->RemoveItem( pSellList->GetItemIdx(0), false ); PIItem item = (PIItem)cell_item->m_pData; pTrade->TransferItem( item, bBuying ); if ( bBuying ) { if ( pTrade->pThis.inv_owner->CInventoryOwner::AllowItemToTrade( item, eItemPlaceRuck ) ) { pBuyList->SetItem( cell_item ); } } else { pBuyList->SetItem( cell_item ); } } pTrade->pThis.inv_owner->set_money( pTrade->pThis.inv_owner->get_money(), true ); pTrade->pPartner.inv_owner->set_money( pTrade->pPartner.inv_owner->get_money(), true ); }
1
0.89623
1
0.89623
game-dev
MEDIA
0.585324
game-dev,desktop-app
0.938045
1
0.938045
kvoeten/UnrealBodyPlugin
16,273
Source/UnrealBody/Private/CharacterComponents/IKBodyComponent.cpp
/* * Copyright 2022 Kaz Voeten * * 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 "CharacterComponents/IKBodyComponent.h" #include "Kismet/KismetMathLibrary.h" DEFINE_LOG_CATEGORY(LogIKBodyComponent); // Sets default values for this component's properties UIKBodyComponent::UIKBodyComponent() { PrimaryComponentTick.bCanEverTick = true; PrimaryComponentTick.TickInterval = .01f; SetNetAddressable(); } void UIKBodyComponent::GetLifetimeReplicatedProps(TArray< FLifetimeProperty >& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(UIKBodyComponent, MovementThreshold); DOREPLIFETIME(UIKBodyComponent, RotationThreshold); DOREPLIFETIME(UIKBodyComponent, BodyRotationOffset); DOREPLIFETIME(UIKBodyComponent, PlayerHeight); DOREPLIFETIME(UIKBodyComponent, BodyOffset); } void UIKBodyComponent::BeginPlay() { Super::BeginPlay(); if (Body != nullptr && Camera != nullptr) { // Detach the body from it's parent so it doesn't automatically move with the players head movement. static FDetachmentTransformRules DetachRules = FDetachmentTransformRules(EDetachmentRule::KeepWorld, false); Body->DetachFromComponent(DetachRules); // Set body at camera position + offsets this->BodyTargetLocation = Camera->GetComponentLocation() + (UKismetMathLibrary::GetForwardVector(Camera->GetComponentRotation()) * BodyOffset); // 20 units back from cam to avoid clipping this->BodyTargetLocation.Z -= this->PlayerHeight; this->Body->SetWorldLocation(this->BodyTargetLocation); // Rotate Body to match this->BodyTargetRotation.Yaw = Camera->GetComponentRotation().Yaw + this->BodyRotationOffset; this->Body->SetWorldRotation(this->BodyTargetRotation); // Set current position to match target this->BodyCurrentLocation = this->BodyTargetLocation; this->BodyCurrentRotation = this->BodyTargetRotation; UE_LOG(LogIKBodyComponent, Log, TEXT("Succesfully initialized with body and camera!")); } else { // Body should be assigned in component owner's construction script! UE_LOG(LogIKBodyComponent, Warning, TEXT("Please ensure a body and camera reference are set before BeginPlay by setting it in the owner's construction script.")); } } void UIKBodyComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); if (Body != nullptr && Camera != nullptr) { this->TickBodyMovement(DeltaTime); this->TickFingerIK(DeltaTime); } } void UIKBodyComponent::TickBodyMovement(float DeltaTime) { FTransform CameraCurrentPosition = this->Camera->GetComponentTransform(); // Calculate the XY distance moved float DistanceMoved = FVector::Distance( FVector(CameraCurrentPosition.GetLocation().X, CameraCurrentPosition.GetLocation().Y, 0), FVector(LastCameraPosition.GetLocation().X, LastCameraPosition.GetLocation().Y, 0) ); // Calculate Yaw difference float YawDifference = UKismetMathLibrary::Abs( CameraCurrentPosition.GetRotation().Rotator().Yaw - LastCameraPosition.GetRotation().Rotator().Yaw ); // Update the camera position and movement if the player moved further away than threshold (enables leaning/ head tilt without moving the body) if (DistanceMoved > this->MovementThreshold) { // Set new body target location this->BodyTargetLocation = CameraCurrentPosition.GetLocation() + (UKismetMathLibrary::GetForwardVector(CameraCurrentPosition.GetRotation().Rotator()) * BodyOffset); // 20 units back from cam to avoid clipping // Update movement speed and direction this->MovementDirection = GetMovementDirection(&LastCameraPosition, &CameraCurrentPosition); this->MovementSpeed = UKismetMathLibrary::FFloor((DistanceMoved / DeltaTime) / 1000); // Save new position this->LastCameraPosition = CameraCurrentPosition; } // Apply new rotation to the body if turned far enough (allows head turning without rotating the whole body) if (YawDifference > this->RotationThreshold) { this->BodyTargetRotation.Yaw = Camera->GetComponentRotation().Yaw + this->BodyRotationOffset; this->MovementDirection = YawDifference; } // If the body hasn't reached it's target location yet we move it towards it. if (UKismetMathLibrary::NearlyEqual_FloatFloat(BodyCurrentLocation.X, BodyTargetLocation.X, 9.99997f) && UKismetMathLibrary::NearlyEqual_FloatFloat(BodyCurrentLocation.Y, BodyTargetLocation.Y, 9.99997f)) { this->MovementSpeed = 0; this->MovementDirection = 0; } else { // Tick towards location based on movement speed this->BodyCurrentLocation = UKismetMathLibrary::VInterpTo(this->BodyCurrentLocation, this->BodyTargetLocation, DeltaTime, MovementSpeed * this->MovementSpeedMultiplier); this->Body->SetWorldLocation(BodyCurrentLocation); } // If the body hasn't reached it's target rotation yet we interp towards it. if (!UKismetMathLibrary::NearlyEqual_FloatFloat(BodyCurrentRotation.Yaw, BodyTargetRotation.Yaw, 9.99997f)) { BodyCurrentRotation.Yaw = UKismetMathLibrary::FInterpTo(BodyCurrentRotation.Yaw, BodyTargetRotation.Yaw, DeltaTime, UKismetMathLibrary::Max(2.0f, MovementSpeed)); this->Body->SetWorldRotation(BodyCurrentRotation); } else this->MovementDirection = 0; // Always set Z to enable seamless crouching FVector BodyLocation = FVector(BodyCurrentLocation.X, BodyCurrentLocation.Y, CameraCurrentPosition.GetLocation().Z - this->PlayerHeight); this->Body->SetWorldLocation(BodyLocation); } /* * Sets the body target position to the camera position, rotating and moving it down so that the character eyes match the HMD position */ void UIKBodyComponent::SetBodyTargetPosition(FTransform* CameraTransform) { this->BodyTargetRotation.Yaw = CameraTransform->GetRotation().Z + this->BodyRotationOffset; this->BodyTargetLocation = CameraTransform->GetLocation() + (UKismetMathLibrary::GetRightVector(this->BodyTargetRotation) * -20); this->BodyTargetLocation.Z = BodyTargetLocation.Z - this->PlayerHeight; } /* * Find the (shortest) angle in degrees between two transforms on the XY axis * Huge thanks to Eprim at https://answers.unrealengine.com/ for showing a neat trick to resolve quaternion results */ float UIKBodyComponent::GetMovementDirection(FTransform* First, FTransform* Second) { float Rotation = 0.0f; FVector Axis; // Get rotational vecotors FVector FirstRotVec = First->GetRotation().Vector(); FVector SecondRotVec = Second->GetRotation().Vector(); // Find quat and angle const auto Quaternion = FQuat::FindBetweenNormals(FirstRotVec, SecondRotVec); Quaternion.ToAxisAndAngle(Axis, Rotation); // Convert to degrees and use axis.Z as left-right direction control to constrain angle between -180 and 180 return Axis.Z * FMath::RadiansToDegrees(Rotation); } // Helper function that resets the Finger states of the given hand. void UIKBodyComponent::ResetHandFingers(ECharacterIKHand Hand) { switch (Hand) { case ECharacterIKHand::Left: *FingerStates.StateMap.Find(EFingerBone::index_01_l) = false; *FingerStates.StateMap.Find(EFingerBone::index_02_l) = false; *FingerStates.StateMap.Find(EFingerBone::index_03_l) = false; *FingerStates.StateMap.Find(EFingerBone::middle_01_l) = false; *FingerStates.StateMap.Find(EFingerBone::middle_02_l) = false; *FingerStates.StateMap.Find(EFingerBone::middle_03_l) = false; *FingerStates.StateMap.Find(EFingerBone::ring_01_l) = false; *FingerStates.StateMap.Find(EFingerBone::ring_02_l) = false; *FingerStates.StateMap.Find(EFingerBone::ring_03_l) = false; *FingerStates.StateMap.Find(EFingerBone::pinky_01_l) = false; *FingerStates.StateMap.Find(EFingerBone::pinky_02_l) = false; *FingerStates.StateMap.Find(EFingerBone::pinky_03_l) = false; *FingerStates.StateMap.Find(EFingerBone::thumb_01_l) = false; *FingerStates.StateMap.Find(EFingerBone::thumb_02_l) = false; *FingerStates.StateMap.Find(EFingerBone::thumb_03_l) = false; break; case ECharacterIKHand::Right: *FingerStates.StateMap.Find(EFingerBone::index_01_r) = false; *FingerStates.StateMap.Find(EFingerBone::index_02_r) = false; *FingerStates.StateMap.Find(EFingerBone::index_03_r) = false; *FingerStates.StateMap.Find(EFingerBone::middle_01_r) = false; *FingerStates.StateMap.Find(EFingerBone::middle_02_r) = false; *FingerStates.StateMap.Find(EFingerBone::middle_03_r) = false; *FingerStates.StateMap.Find(EFingerBone::ring_01_r) = false; *FingerStates.StateMap.Find(EFingerBone::ring_02_r) = false; *FingerStates.StateMap.Find(EFingerBone::ring_03_r) = false; *FingerStates.StateMap.Find(EFingerBone::pinky_01_r) = false; *FingerStates.StateMap.Find(EFingerBone::pinky_02_r) = false; *FingerStates.StateMap.Find(EFingerBone::pinky_03_r) = false; *FingerStates.StateMap.Find(EFingerBone::thumb_01_r) = false; *FingerStates.StateMap.Find(EFingerBone::thumb_02_r) = false; *FingerStates.StateMap.Find(EFingerBone::thumb_03_r) = false; break; } } void UIKBodyComponent::StartFingerIK(AActor* Target, ECharacterIKHand Hand) { if (Target == nullptr) return; switch (Hand) { case ECharacterIKHand::Left: this->LeftGrip = Target; this->ResetHandFingers(Hand); break; case ECharacterIKHand::Right: this->RightGrip = Target; this->ResetHandFingers(Hand); break; } } void UIKBodyComponent::StopFingerIK(ECharacterIKHand Hand) { switch (Hand) { case ECharacterIKHand::Left: this->LeftGrip = nullptr; this->ResetHandFingers(Hand); break; case ECharacterIKHand::Right: this->RightGrip = nullptr; this->ResetHandFingers(Hand); break; } } void UIKBodyComponent::TickFingerIK(float DeltaTime) { for (auto& Element : FingerStates.StateMap) { const EFingerBone Bone = (EFingerBone) Element.Key; const bool Finished = (bool) Element.Value; if (!Finished) { AActor* GripTarget = nullptr; switch (Bone) { case EFingerBone::index_01_l: case EFingerBone::index_02_l: case EFingerBone::index_03_l: case EFingerBone::middle_01_l: case EFingerBone::middle_02_l: case EFingerBone::middle_03_l: case EFingerBone::ring_01_l: case EFingerBone::ring_02_l: case EFingerBone::ring_03_l: case EFingerBone::pinky_01_l: case EFingerBone::pinky_02_l: case EFingerBone::pinky_03_l: case EFingerBone::thumb_01_l: case EFingerBone::thumb_02_l: case EFingerBone::thumb_03_l: GripTarget = LeftGrip; break; case EFingerBone::index_01_r: case EFingerBone::index_02_r: case EFingerBone::index_03_r: case EFingerBone::middle_01_r: case EFingerBone::middle_02_r: case EFingerBone::middle_03_r: case EFingerBone::ring_01_r: case EFingerBone::ring_02_r: case EFingerBone::ring_03_r: case EFingerBone::pinky_01_r: case EFingerBone::pinky_02_r: case EFingerBone::pinky_03_r: case EFingerBone::thumb_01_r: case EFingerBone::thumb_02_r: case EFingerBone::thumb_03_r: GripTarget = RightGrip; break; } float TargetAlpha = GripTarget == nullptr ? 0 : 1.0f; float* CurrentAlpha = this->FingerIKValues.BlendMap.Find(Bone); // Check if ptr to capsule ptr is valid, and then get capsule ptr UCapsuleComponent** CapsulePtrPtr = this->FingerHitboxes.Find(Bone); UCapsuleComponent* Capsule = CapsulePtrPtr == nullptr ? nullptr : *CapsulePtrPtr; if (*CurrentAlpha == TargetAlpha) { // Target is already reached since moving previous tick *this->FingerStates.StateMap.Find(Bone) = true; continue; // Skip to next bone } else if (Capsule != nullptr && GripTarget != nullptr) { // Check if capsule is colliding with target actor since being moved previous tick if (Capsule->IsOverlappingActor(GripTarget)) { *this->FingerStates.StateMap.Find(Bone) = true; continue; // Skip to next bone } } // Finterp to target *CurrentAlpha = UKismetMathLibrary::FInterpTo(*CurrentAlpha, TargetAlpha, DeltaTime, 4.0f); } } } void UIKBodyComponent::UpdateMovementThreshold_Implementation(float Value) { this->MovementThreshold = Value; } void UIKBodyComponent::UpdateRotationThreshold_Implementation(float Value) { this->RotationThreshold = Value; } void UIKBodyComponent::UpdatePlayerHeight_Implementation(float Value) { this->PlayerHeight = Value; } void UIKBodyComponent::UpdateBodyOffset_Implementation(float Value) { this->BodyOffset = Value; } void UIKBodyComponent::SetAllHitBoxes( UCapsuleComponent* index_01_l, UCapsuleComponent* index_02_l, UCapsuleComponent* index_03_l, UCapsuleComponent* middle_01_l, UCapsuleComponent* middle_02_l, UCapsuleComponent* middle_03_l, UCapsuleComponent* ring_01_l, UCapsuleComponent* ring_02_l, UCapsuleComponent* ring_03_l, UCapsuleComponent* pinky_01_l, UCapsuleComponent* pinky_02_l, UCapsuleComponent* pinky_03_l, UCapsuleComponent* thumb_01_l, UCapsuleComponent* thumb_02_l, UCapsuleComponent* thumb_03_l, UCapsuleComponent* index_01_r, UCapsuleComponent* index_02_r, UCapsuleComponent* index_03_r, UCapsuleComponent* middle_01_r, UCapsuleComponent* middle_02_r, UCapsuleComponent* middle_03_r, UCapsuleComponent* ring_01_r, UCapsuleComponent* ring_02_r, UCapsuleComponent* ring_03_r, UCapsuleComponent* pinky_01_r, UCapsuleComponent* pinky_02_r, UCapsuleComponent* pinky_03_r, UCapsuleComponent* thumb_01_r, UCapsuleComponent* thumb_02_r, UCapsuleComponent* thumb_03_r ) { this->FingerHitboxes.Empty(); this->FingerHitboxes.Add(EFingerBone::index_01_l, index_01_l); this->FingerHitboxes.Add(EFingerBone::index_02_l, index_02_l); this->FingerHitboxes.Add(EFingerBone::index_03_l, index_03_l); this->FingerHitboxes.Add(EFingerBone::middle_01_l, middle_01_l); this->FingerHitboxes.Add(EFingerBone::middle_02_l, middle_02_l); this->FingerHitboxes.Add(EFingerBone::middle_03_l, middle_03_l); this->FingerHitboxes.Add(EFingerBone::ring_01_l, ring_01_l); this->FingerHitboxes.Add(EFingerBone::ring_02_l, ring_02_l); this->FingerHitboxes.Add(EFingerBone::ring_03_l, ring_03_l); this->FingerHitboxes.Add(EFingerBone::pinky_01_l, pinky_01_l); this->FingerHitboxes.Add(EFingerBone::pinky_02_l, pinky_02_l); this->FingerHitboxes.Add(EFingerBone::pinky_03_l, pinky_03_l); this->FingerHitboxes.Add(EFingerBone::thumb_01_l, thumb_01_l); this->FingerHitboxes.Add(EFingerBone::thumb_02_l, thumb_02_l); this->FingerHitboxes.Add(EFingerBone::thumb_03_l, thumb_03_l); this->FingerHitboxes.Add(EFingerBone::index_01_r, index_01_r); this->FingerHitboxes.Add(EFingerBone::index_02_r, index_02_r); this->FingerHitboxes.Add(EFingerBone::index_03_r, index_03_r); this->FingerHitboxes.Add(EFingerBone::middle_01_r, middle_01_r); this->FingerHitboxes.Add(EFingerBone::middle_02_r, middle_02_r); this->FingerHitboxes.Add(EFingerBone::middle_03_r, middle_03_r); this->FingerHitboxes.Add(EFingerBone::ring_01_r, ring_01_r); this->FingerHitboxes.Add(EFingerBone::ring_02_r, ring_02_r); this->FingerHitboxes.Add(EFingerBone::ring_03_r, ring_03_r); this->FingerHitboxes.Add(EFingerBone::pinky_01_r, pinky_01_r); this->FingerHitboxes.Add(EFingerBone::pinky_02_r, pinky_02_r); this->FingerHitboxes.Add(EFingerBone::pinky_03_r, pinky_03_r); this->FingerHitboxes.Add(EFingerBone::thumb_01_r, thumb_01_r); this->FingerHitboxes.Add(EFingerBone::thumb_02_r, thumb_02_r); this->FingerHitboxes.Add(EFingerBone::thumb_03_r, thumb_03_r); }
1
0.95687
1
0.95687
game-dev
MEDIA
0.984103
game-dev
0.983141
1
0.983141
ecmadao/algorithms
4,517
leetcode/JavaScript/No1487.making-file-names-unique.js
/* * Difficulty: * Medium * * Desc: * Given an array of strings names of size n. * You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i]. * Since two files cannot have the same name, if you enter a folder name which is previously used, the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer such that the obtained name remains unique. * Return an array of strings of length n where ans[i] is the actual name the system will assign to the ith folder when you create it. * * Example 1: * Input: names = ["pes","fifa","gta","pes(2019)"] * Output: ["pes","fifa","gta","pes(2019)"] * Explanation: * Let's see how the file system creates folder names: * "pes" --> not assigned before, remains "pes" * "fifa" --> not assigned before, remains "fifa" * "gta" --> not assigned before, remains "gta" * "pes(2019)" --> not assigned before, remains "pes(2019)" * * Example 2: * Input: names = ["gta","gta(1)","gta","avalon"] * Output: ["gta","gta(1)","gta(2)","avalon"] * Explanation: * Let's see how the file system creates folder names: * "gta" --> not assigned before, remains "gta" * "gta(1)" --> not assigned before, remains "gta(1)" * "gta" --> the name is reserved, system adds (k), since "gta(1)" is also reserved, systems put k = 2. it becomes "gta(2)" * "avalon" --> not assigned before, remains "avalon" * * Example 3: * Input: names = ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece"] * Output: ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece(4)"] * Explanation: When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4)". * * Example 4: * Input: names = ["wano","wano","wano","wano"] * Output: ["wano","wano(1)","wano(2)","wano(3)"] * Explanation: Just increase the value of k each time you create folder "wano". * * Example 5: * Input: names = ["kaido","kaido(1)","kaido","kaido(1)"] * Output: ["kaido","kaido(1)","kaido(2)","kaido(1)(1)"] * Explanation: Please note that system adds the suffix (k) to current name even it contained the same suffix before. * * Constraints: * 1 <= names.length <= 5 * 10^4 * 1 <= names[i].length <= 20 * names[i] consists of lower case English letters, digits and/or round brackets. */ /** * @param {string[]} names * @return {string[]} */ var getFolderNames = function(names) { const res = []; const dict = new Map(); const updateRange = (name) => { const match = name.match(/\(\d+\)$/); if (!match) return; const num = Number(match[0].slice(1, -1)); if (num === 0) return; const oldname = name.slice(0, match.index); const ranges = dict.get(oldname) || [[0, Infinity]]; const index = ranges.findIndex((range) => range[0] <= num && range[1] >= num); if (index < 0) { dict.set(oldname, ranges); return; } const range = ranges[index]; if (range[0] === num) { ranges[index][0] += 1; if (ranges[index][0] > ranges[index][1]) ranges.splice(index, 1); } else if (range[1] === num) { ranges[index][1] -= 1; if (ranges[index][0] > ranges[index][1]) ranges.splice(index, 1); } else { ranges.splice(index, 1, [range[0], num - 1], [num + 1, range[1]]) } dict.set(oldname, ranges); } for (const name of names) { if (dict.has(name)) { const ranges = dict.get(name); const newname = ranges[0][0] == 0 ? name : `${name}(${ranges[0][0]})`; if (ranges[0][0] == ranges[0][1]) { ranges.shift(); } else { ranges[0][0] += 1; } dict.set(name, ranges); if (dict.has(newname)) { if (name !== newname) { const ranges2 = dict.get(newname); ranges2[0][0] += 1; if (ranges2[0][0] > ranges2[0][1]) ranges2.shift(); dict.set(newname, ranges2); } } else { dict.set(newname, [[1, Infinity]]); } res.push(newname); } else { dict.set(name, [[1, Infinity]]); res.push(name); } updateRange(name); } return res; }; // ["r(2)(1)", "r", "r", "r", "r(2)", "r(2)", "r"]
1
0.625547
1
0.625547
game-dev
MEDIA
0.498962
game-dev
0.627934
1
0.627934
freeciv/freeciv
8,945
client/gui-sdl3/finddlg.c
/*********************************************************************** Freeciv - Copyright (C) 1996 - A Kjeldberg, L Gregersen, P Unold 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, 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. ***********************************************************************/ #ifdef HAVE_CONFIG_H #include <fc_config.h> #endif #include <stdlib.h> /* SDL3 */ #include <SDL3/SDL.h> /* utility */ #include "fcintl.h" #include "log.h" /* common */ #include "game.h" #include "nation.h" /* client */ #include "zoom.h" /* gui-sdl3 */ #include "colors.h" #include "graphics.h" #include "gui_id.h" #include "gui_main.h" #include "gui_tilespec.h" #include "mapctrl.h" #include "mapview.h" #include "sprite.h" #include "widget.h" #include "finddlg.h" /* ====================================================================== */ /* ============================= FIND CITY MENU ========================= */ /* ====================================================================== */ static struct advanced_dialog *find_city_dlg = NULL; /**********************************************************************//** User interacted with find city dialog window. **************************************************************************/ static int find_city_window_dlg_callback(struct widget *pwindow) { if (PRESSED_EVENT(main_data.event)) { move_window_group(find_city_dlg->begin_widget_list, pwindow); } return -1; } /**********************************************************************//** Close find city dialog. **************************************************************************/ static int exit_find_city_dlg_callback(struct widget *pwidget) { if (PRESSED_EVENT(main_data.event)) { int orginal_x = pwidget->data.cont->id0; int orginal_y = pwidget->data.cont->id1; popdown_find_dialog(); center_tile_mapcanvas(map_pos_to_tile(&(wld.map), orginal_x, orginal_y)); flush_dirty(); } return -1; } /**********************************************************************//** User has selected city to find. **************************************************************************/ static int find_city_callback(struct widget *pwidget) { if (PRESSED_EVENT(main_data.event)) { struct city *pcity = pwidget->data.city; if (pcity) { center_tile_mapcanvas(pcity->tile); if (main_data.event.button.button == SDL_BUTTON_RIGHT) { popdown_find_dialog(); } flush_dirty(); } } return -1; } /**********************************************************************//** Popdown a dialog to ask for a city to find. **************************************************************************/ void popdown_find_dialog(void) { if (find_city_dlg) { popdown_window_group_dialog(find_city_dlg->begin_widget_list, find_city_dlg->end_widget_list); FC_FREE(find_city_dlg->scroll); FC_FREE(find_city_dlg); enable_and_redraw_find_city_button(); } } /**********************************************************************//** Popup a dialog to ask for a city to find. **************************************************************************/ void popup_find_dialog(void) { struct widget *pwindow = NULL, *buf = NULL; SDL_Surface *logo = NULL; utf8_str *pstr; char cbuf[128]; int h = 0, n = 0, w = 0, units_h = 0; struct player *owner = NULL; struct tile *original; int window_x = 0, window_y = 0; bool mouse = (main_data.event.type == SDL_EVENT_MOUSE_BUTTON_DOWN); SDL_Rect area; /* check that there are any cities to find */ players_iterate(pplayer) { h = city_list_size(pplayer->cities); if (h > 0) { break; } } players_iterate_end; if (find_city_dlg && !h) { return; } original = canvas_pos_to_tile(main_data.map->w / 2, main_data.map->h / 2, map_zoom); find_city_dlg = fc_calloc(1, sizeof(struct advanced_dialog)); pstr = create_utf8_from_char_fonto(_("Find City"), FONTO_ATTENTION); pstr->style |= TTF_STYLE_BOLD; pwindow = create_window_skeleton(NULL, pstr, 0); pwindow->action = find_city_window_dlg_callback; set_wstate(pwindow , FC_WS_NORMAL); add_to_gui_list(ID_TERRAIN_ADV_DLG_WINDOW, pwindow); find_city_dlg->end_widget_list = pwindow; area = pwindow->area; /* ---------- */ /* Exit button */ buf = create_themeicon(current_theme->small_cancel_icon, pwindow->dst, WF_WIDGET_HAS_INFO_LABEL | WF_RESTORE_BACKGROUND | WF_FREE_DATA); buf->info_label = create_utf8_from_char_fonto(_("Close Dialog (Esc)"), FONTO_ATTENTION); area.w = MAX(area.w, buf->size.w + adj_size(10)); buf->action = exit_find_city_dlg_callback; set_wstate(buf, FC_WS_NORMAL); buf->key = SDLK_ESCAPE; buf->data.cont = fc_calloc(1, sizeof(struct container)); buf->data.cont->id0 = index_to_map_pos_x(tile_index(original)); buf->data.cont->id1 = index_to_map_pos_y(tile_index(original)); add_to_gui_list(ID_TERRAIN_ADV_DLG_EXIT_BUTTON, buf); /* ---------- */ players_iterate(pplayer) { city_list_iterate(pplayer->cities, pcity) { fc_snprintf(cbuf , sizeof(cbuf), "%s (%d)", city_name_get(pcity), city_size_get(pcity)); pstr = create_utf8_from_char_fonto(cbuf, FONTO_DEFAULT); pstr->style |= (TTF_STYLE_BOLD|SF_CENTER); if (!player_owns_city(owner, pcity)) { logo = get_nation_flag_surface(nation_of_player(city_owner(pcity))); logo = crop_visible_part_from_surface(logo); } buf = create_iconlabel(logo, pwindow->dst, pstr, (WF_RESTORE_BACKGROUND|WF_DRAW_TEXT_LABEL_WITH_SPACE)); if (!player_owns_city(owner, pcity)) { set_wflag(buf, WF_FREE_THEME); owner = city_owner(pcity); } buf->string_utf8->style &= ~SF_CENTER; buf->string_utf8->fgcol = *(get_player_color(tileset, city_owner(pcity))->color); buf->string_utf8->bgcol = (SDL_Color) {0, 0, 0, 0}; buf->data.city = pcity; buf->action = find_city_callback; set_wstate(buf, FC_WS_NORMAL); add_to_gui_list(ID_LABEL , buf); area.w = MAX(area.w, buf->size.w); area.h += buf->size.h; if (n > 19) { set_wflag(buf , WF_HIDDEN); } n++; } city_list_iterate_end; } players_iterate_end; find_city_dlg->begin_widget_list = buf; find_city_dlg->begin_active_widget_list = find_city_dlg->begin_widget_list; find_city_dlg->end_active_widget_list = pwindow->prev->prev; find_city_dlg->active_widget_list = find_city_dlg->end_active_widget_list; /* ---------- */ if (n > 20) { units_h = create_vertical_scrollbar(find_city_dlg, 1, 20, TRUE, TRUE); find_city_dlg->scroll->count = n; n = units_h; area.w += n; units_h = 20 * buf->size.h + adj_size(2); } else { units_h = area.h; } /* ---------- */ area.h = units_h; resize_window(pwindow , NULL, NULL, (pwindow->size.w - pwindow->area.w) + area.w, (pwindow->size.h - pwindow->area.h) + area.h); area = pwindow->area; if (!mouse) { window_x = adj_size(10); window_y = (main_window_height() - pwindow->size.h) / 2; } else { window_x = (main_data.event.motion.x + pwindow->size.w + adj_size(10) < main_window_width()) ? (main_data.event.motion.x + adj_size(10)) : (main_window_width() - pwindow->size.w - adj_size(10)); window_y = (main_data.event.motion.y - adj_size(2) + pwindow->size.h < main_window_height()) ? (main_data.event.motion.y - adj_size(2)) : (main_window_height() - pwindow->size.h - adj_size(10)); } widget_set_position(pwindow, window_x, window_y); w = area.w; if (find_city_dlg->scroll) { w -= n; } /* exit button */ buf = pwindow->prev; buf->size.x = area.x + area.w - buf->size.w - 1; buf->size.y = pwindow->size.y + adj_size(2); /* cities */ buf = buf->prev; setup_vertical_widgets_position(1, area.x, area.y, w, 0, find_city_dlg->begin_active_widget_list, buf); if (find_city_dlg->scroll) { setup_vertical_scrollbar_area(find_city_dlg->scroll, area.x + area.w, area.y, area.h, TRUE); } /* -------------------- */ /* redraw */ redraw_group(find_city_dlg->begin_widget_list, pwindow, 0); widget_mark_dirty(pwindow); flush_dirty(); }
1
0.885845
1
0.885845
game-dev
MEDIA
0.672391
game-dev,desktop-app
0.891029
1
0.891029
DarkstarProject/darkstar
2,491
scripts/zones/Bastok_Mines/npcs/Hemewmew.lua
----------------------------------- -- Area: Bastok Mines -- NPC: Hemewmew -- Type: Guildworker's Union Representative -- !pos 117.970 1.017 -10.438 234 ----------------------------------- local ID = require("scripts/zones/Bastok_Mines/IDs"); require("scripts/globals/keyitems"); require("scripts/globals/crafting"); local keyitems = { [0] = { id = dsp.ki.ANIMA_SYNTHESIS, rank = 3, cost = 20000 }, [1] = { id = dsp.ki.ALCHEMIC_PURIFICATION, rank = 3, cost = 40000 }, [2] = { id = dsp.ki.ALCHEMIC_ENSORCELLMENT, rank = 3, cost = 40000 }, [3] = { id = dsp.ki.TRITURATION, rank = 3, cost = 10000 }, [4] = { id = dsp.ki.CONCOCTION, rank = 3, cost = 20000 }, [5] = { id = dsp.ki.IATROCHEMISTRY, rank = 3, cost = 10000 }, [6] = { id = dsp.ki.WAY_OF_THE_ALCHEMIST, rank = 9, cost = 20000 } }; local items = { [0] = { id = 15450, -- Alchemist's Belt rank = 4, cost = 10000 }, [1] = { id = 17058, -- Caduceus rank = 5, cost = 70000 }, [2] = { id = 14398, -- Alchemist's Apron rank = 7, cost = 100000 }, [3] = { id = 134, -- copy of Emeralda rank = 9, cost = 150000 }, [4] = { id = 342, -- Alchemist's Signboard rank = 9, cost = 200000 }, [5] = { id = 15825, -- Alchemist's Ring rank = 6, cost = 80000 }, [6] = { id = 3674, -- Alembic rank = 7, cost = 50000 }, [7] = { id = 3332, -- Alchemist's Emblem rank = 9, cost = 15000 } }; function onTrade(player,npc,trade) unionRepresentativeTrade(player, npc, trade, 207, 7); end; function onTrigger(player,npc) unionRepresentativeTrigger(player, 7, 206, "guild_alchemy", keyitems); end; function onEventUpdate(player,csid,option,target) if (csid == 206) then unionRepresentativeTriggerFinish(player, option, target, 7, "guild_alchemy", keyitems, items); end end; function onEventFinish(player,csid,option,target) if (csid == 206) then unionRepresentativeTriggerFinish(player, option, target, 7, "guild_alchemy", keyitems, items); elseif (csid == 207) then player:messageSpecial(ID.text.GP_OBTAINED, option); end end;
1
0.719931
1
0.719931
game-dev
MEDIA
0.938875
game-dev
0.754737
1
0.754737
luna-rs/luna
1,758
src/main/kotlin/world/player/skill/herblore/makeUnfPotion/UnfPotion.kt
package world.player.skill.herblore.makeUnfPotion import api.predef.* import io.luna.game.model.item.Item /** * An enum representing an unfinished potion. */ enum class UnfPotion(val id: Int, val herb: Int, val level: Int) { GUAM(id = 91, herb = 249, level = 3), MARRENTILL(id = 93, herb = 251, level = 5), TARROMIN(id = 95, herb = 253, level = 8), HARRALANDER(id = 97, herb = 255, level = 15), RANARR(id = 99, herb = 257, level = 30), TOADFLAX(id = 3002, herb = 2998, level = 34), IRIT(id = 101, herb = 259, level = 45), AVANTOE(id = 103, herb = 261, level = 50), KWUARM(id = 105, herb = 263, level = 55), SNAPDRAGON(id = 3004, herb = 3000, level = 63), CADANTINE(id = 107, herb = 265, level = 66), LANTADYME(id = 2483, herb = 2481, level = 69), DWARF_WEED(id = 109, herb = 267, level = 72), TORSTOL(id = 111, herb = 269, level = 78); companion object { /** * Mappings of [UnfPotion.herb] to [UnfPotion] instances. */ val HERB_TO_UNF = values().associateBy { it.herb } /** * The vial of water identifier. */ const val VIAL_OF_WATER = 227 } /** * The herb item. */ val herbItem = Item(herb) /** * The unf. potion item. */ val idItem = Item(id) /** * The herb's name. */ val herbName = itemName(herb) }
1
0.769781
1
0.769781
game-dev
MEDIA
0.587941
game-dev,uncategorized
0.658519
1
0.658519
Render96/ModelPack
1,879
Render96/goomba/geo.inc.c
#include "src/game/envfx_snow.h" const GeoLayout goomba_000_switch_opt1[] = { GEO_NODE_START(), GEO_OPEN_NODE(), GEO_ANIMATED_PART(1, 48, 0, 0, goomba_000_offset_001_mesh_mat_override_blink_0), GEO_CLOSE_NODE(), GEO_RETURN(), }; const GeoLayout goomba_geo[] = { GEO_NODE_START(), GEO_OPEN_NODE(), GEO_SHADOW(0, 150, 100), GEO_OPEN_NODE(), GEO_SCALE(0, 16384), GEO_OPEN_NODE(), GEO_ANIMATED_PART(1, 0, 0, 0, NULL), GEO_OPEN_NODE(), GEO_ANIMATED_PART(1, 0, 0, 0, NULL), GEO_OPEN_NODE(), GEO_BILLBOARD_WITH_PARAMS(0, 0, 0, 0), GEO_OPEN_NODE(), GEO_DISPLAY_LIST(4, NULL), GEO_CLOSE_NODE(), GEO_SWITCH_CASE(2, geo_switch_anim_state), GEO_OPEN_NODE(), GEO_NODE_START(), GEO_OPEN_NODE(), GEO_ANIMATED_PART(1, 48, 0, 0, goomba_000_offset_001_mesh), GEO_CLOSE_NODE(), GEO_BRANCH(1, goomba_000_switch_opt1), GEO_CLOSE_NODE(), GEO_ANIMATED_PART(1, -60, -16, 45, NULL), GEO_OPEN_NODE(), GEO_ANIMATED_PART(1, 0, 0, 0, goomba_000_offset_002_mesh), GEO_CLOSE_NODE(), GEO_ANIMATED_PART(1, -60, -16, -45, NULL), GEO_OPEN_NODE(), GEO_ANIMATED_PART(1, 0, 0, 0, goomba_000_offset_003_mesh), GEO_CLOSE_NODE(), GEO_CLOSE_NODE(), GEO_CLOSE_NODE(), GEO_CLOSE_NODE(), GEO_CLOSE_NODE(), GEO_DISPLAY_LIST(0, goomba_material_revert_render_settings), GEO_DISPLAY_LIST(1, goomba_material_revert_render_settings), GEO_DISPLAY_LIST(2, goomba_material_revert_render_settings), GEO_DISPLAY_LIST(3, goomba_material_revert_render_settings), GEO_DISPLAY_LIST(4, goomba_material_revert_render_settings), GEO_DISPLAY_LIST(5, goomba_material_revert_render_settings), GEO_DISPLAY_LIST(6, goomba_material_revert_render_settings), GEO_DISPLAY_LIST(7, goomba_material_revert_render_settings), GEO_CLOSE_NODE(), GEO_END(), };
1
0.706379
1
0.706379
game-dev
MEDIA
0.711088
game-dev,graphics-rendering
0.649401
1
0.649401
hakan-krgn/hCore
5,847
hCore-bukkit/nms/v1_20_R2/src/main/java/com/hakan/core/hologram/line/text/TextLine_v1_20_R2.java
package com.hakan.core.hologram.line.text; import com.hakan.core.HCore; import com.hakan.core.hologram.Hologram; import com.hakan.core.utils.ReflectionUtils; import com.hakan.core.utils.Validate; import net.minecraft.network.protocol.game.PacketPlayOutEntityDestroy; import net.minecraft.network.protocol.game.PacketPlayOutEntityMetadata; import net.minecraft.network.protocol.game.PacketPlayOutEntityTeleport; import net.minecraft.network.protocol.game.PacketPlayOutSpawnEntity; import net.minecraft.world.entity.decoration.EntityArmorStand; import net.minecraft.world.level.World; import org.bukkit.Location; import org.bukkit.craftbukkit.v1_20_R2.CraftWorld; import org.bukkit.craftbukkit.v1_20_R2.util.CraftChatMessage; import org.bukkit.entity.Player; import javax.annotation.Nonnull; import java.util.List; /** * {@inheritDoc} */ public final class TextLine_v1_20_R2 implements TextLine { private String text; private final Hologram hologram; private final EntityArmorStand click; private final EntityArmorStand armorStand; /** * {@inheritDoc} */ private TextLine_v1_20_R2(@Nonnull Hologram hologram, @Nonnull Location location) { World world = ((CraftWorld) Validate.notNull(location.getWorld())).getHandle(); this.hologram = Validate.notNull(hologram, "hologram class cannot be null!"); this.click = new EntityArmorStand(world, location.getX(), location.getY(), location.getZ()); this.armorStand = new EntityArmorStand(world, location.getX(), location.getY(), location.getZ()); this.click.persistentInvisibility = true; //set invisibility to true this.click.b(5, true); //set invisibility to true this.click.n(false); //set custom name visibility to false this.click.r(false); //set arms to false this.click.s(true); //set no base-plate to true this.click.e(true); //set no gravity to true this.click.a(false); //set small to false this.click.c(114.13f); //set health to 114.13 float this.armorStand.persistentInvisibility = true; //set invisibility to true this.armorStand.b(5, true); //set invisibility to true this.armorStand.n(true); //set custom name visibility to true this.armorStand.t(true); //set marker to true this.armorStand.r(false); //set arms to false this.armorStand.s(true); //set no base-plate to true this.armorStand.e(true); //set no gravity to true this.armorStand.a(true); //set small to true this.armorStand.c(114.13f); //set health to 114.13 float } /** * {@inheritDoc} */ @Nonnull @Override public String getText() { return this.text; } /** * {@inheritDoc} */ @Override public void setText(@Nonnull String text) { this.text = Validate.notNull(text, "text cannot be null!"); this.armorStand.b(CraftChatMessage.fromStringOrNull(this.text)); HCore.sendPacket(this.hologram.getRenderer().getShownPlayers(), new PacketPlayOutEntityMetadata(this.armorStand.ah(), this.armorStand.al().c())); } /** * {@inheritDoc} */ @Nonnull @Override public Hologram getHologram() { return this.hologram; } /** * {@inheritDoc} */ @Override public int getEntityID() { return this.click.ah(); } /** * {@inheritDoc} */ @Nonnull @Override public Location getLocation() { return this.armorStand.getBukkitEntity().getLocation(); } /** * {@inheritDoc} */ @Override public void setLocation(@Nonnull Location location) { Validate.notNull(location, "location cannot be null!"); World world = ((CraftWorld) Validate.notNull(location.getWorld())).getHandle(); if (!world.equals(this.click.dL())) ReflectionUtils.setField(this.click, "t", world); if (!world.equals(this.armorStand.dL())) ReflectionUtils.setField(this.armorStand, "t", world); this.click.a(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); this.armorStand.a(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch()); HCore.sendPacket(this.hologram.getRenderer().getShownPlayers(), new PacketPlayOutEntityTeleport(this.armorStand), new PacketPlayOutEntityTeleport(this.click)); } /** * {@inheritDoc} */ @Override public void setMarker(boolean marker) { this.armorStand.t(marker); this.click.t(marker); HCore.sendPacket(this.hologram.getRenderer().getShownPlayers(), new PacketPlayOutEntityMetadata(this.click.ah(), this.click.al().c()), new PacketPlayOutEntityMetadata(this.armorStand.ah(), this.armorStand.al().c())); } /** * {@inheritDoc} */ @Override public void show(@Nonnull List<Player> players) { HCore.sendPacket(Validate.notNull(players, "players cannot be null!"), new PacketPlayOutSpawnEntity(this.armorStand), new PacketPlayOutEntityMetadata(this.armorStand.ah(), this.armorStand.al().c()), new PacketPlayOutEntityTeleport(this.armorStand), new PacketPlayOutSpawnEntity(this.click), new PacketPlayOutEntityMetadata(this.click.ah(), this.click.al().c()), new PacketPlayOutEntityTeleport(this.click)); } /** * {@inheritDoc} */ @Override public void hide(@Nonnull List<Player> players) { HCore.sendPacket(Validate.notNull(players, "players cannot be null!"), new PacketPlayOutEntityDestroy(this.armorStand.ah()), new PacketPlayOutEntityDestroy(this.click.ah())); } }
1
0.900726
1
0.900726
game-dev
MEDIA
0.977838
game-dev
0.661306
1
0.661306
SnowLeopardEngine/SnowLeopardEngine
7,925
Examples/PhysicsSystem/main.cpp
#include "SnowLeopardEngine/Core/Reflection/TypeFactory.h" #include "SnowLeopardEngine/Engine/Debug.h" #include "SnowLeopardEngine/Function/Geometry/GeometryFactory.h" #include "SnowLeopardEngine/Function/NativeScripting/NativeScriptInstance.h" #include "SnowLeopardEngine/Function/Physics/PhysicsMaterial.h" #include "SnowLeopardEngine/Function/Scene/Components.h" #include <SnowLeopardEngine/Core/Time/Time.h> #include <SnowLeopardEngine/Engine/DesktopApp.h> #include <SnowLeopardEngine/Function/Scene/Entity.h> using namespace SnowLeopardEngine; class SphereScript : public NativeScriptInstance { public: virtual void OnColliderEnter() override { SNOW_LEOPARD_INFO("[SphereScript] OnColliderEnter"); g_EngineContext->AudioSys->Play("sounds/jump.mp3"); } virtual void OnTick(float) override { auto& inputSystem = g_EngineContext->InputSys; if (inputSystem->GetKey(KeyCode::Escape)) { DesktopApp::GetInstance()->Quit(); } } }; class CustomLifeTime final : public LifeTimeComponent { public: void OnTick(float) override { if (m_EngineContext->InputSys->GetKeyDown(KeyCode::Space)) { auto scene = m_EngineContext->SceneMngr->GetActiveScene(); // Create a sphere with RigidBodyComponent & SphereColliderComponent auto normalMaterial = CreateRef<PhysicsMaterial>(0.4, 0.4, 0.4); Entity sphere = scene->CreateEntity("Sphere"); auto& sphereTransform = sphere.GetComponent<TransformComponent>(); sphereTransform.Position = {5, 20, 0}; sphereTransform.Scale *= 3; sphere.AddComponent<RigidBodyComponent>(); sphere.AddComponent<SphereColliderComponent>(normalMaterial); auto& sphereMeshFilter = sphere.AddComponent<MeshFilterComponent>(); sphereMeshFilter.PrimitiveType = MeshPrimitiveType::Sphere; auto& sphereMeshRenderer = sphere.AddComponent<MeshRendererComponent>(); sphereMeshRenderer.MaterialFilePath = "Assets/Materials/Blue.dzmaterial"; sphere.AddComponent<NativeScriptingComponent>(NAME_OF_TYPE(SphereScript)); scene->TriggerEntityCreate(sphere); } } virtual void OnLoad() override final { m_EngineContext = DesktopApp::GetInstance()->GetEngine()->GetContext(); // Hide mouse cursor m_EngineContext->WindowSys->SetHideCursor(true); // Create a scene and set active auto scene = m_EngineContext->SceneMngr->CreateScene("PhysicsSystem", true); // Create a camera Entity camera = scene->CreateEntity("MainCamera"); camera.GetComponent<TransformComponent>().Position = {0, 10, 30}; auto& cameraComponent = camera.AddComponent<CameraComponent>(); cameraComponent.ClearFlags = CameraClearFlags::Skybox; // Enable skybox camera.AddComponent<FreeMoveCameraControllerComponent>(); // Create a smooth material // https://forum.unity.com/threads/bounciness-1-0-conservation-of-energy-doesnt-work.143472/ auto smoothMaterial = CreateRef<PhysicsMaterial>(0, 0, 0.98); auto normalMaterial = CreateRef<PhysicsMaterial>(0.4, 0.4, 0.4); // Create a sphere with RigidBodyComponent & SphereColliderComponent Entity sphere = scene->CreateEntity("Sphere"); auto& sphereTransform = sphere.GetComponent<TransformComponent>(); sphereTransform.Position = {0, 15, 0}; sphereTransform.Scale *= 3; sphere.AddComponent<RigidBodyComponent>(); sphere.AddComponent<SphereColliderComponent>(normalMaterial); sphere.AddComponent<CharacterControllerComponent>(); auto& sphereMeshFilter = sphere.AddComponent<MeshFilterComponent>(); sphereMeshFilter.PrimitiveType = MeshPrimitiveType::Sphere; auto& sphereMeshRenderer = sphere.AddComponent<MeshRendererComponent>(); sphereMeshRenderer.MaterialFilePath = "Assets/Materials/Next/Blue.dzmaterial"; sphere.AddComponent<NativeScriptingComponent>(NAME_OF_TYPE(SphereScript)); // create a testSphere to test MeshColliderComponent Entity testSphere = scene->CreateEntity("TestSphere"); auto& testSphereTransform = testSphere.GetComponent<TransformComponent>(); testSphereTransform.Position = {5, 15, 0}; testSphereTransform.Scale *= 3; testSphere.AddComponent<RigidBodyComponent>(1.0f, 0.0f, 0.5f, false); auto& testSphereMeshFilter = testSphere.AddComponent<MeshFilterComponent>(); testSphereMeshFilter.PrimitiveType = MeshPrimitiveType::Sphere; auto& testSphereMeshCollider = testSphere.AddComponent<MeshColliderComponent>(); auto& testSphereMeshRenderer = testSphere.AddComponent<MeshRendererComponent>(); testSphereMeshRenderer.MaterialFilePath = "Assets/Materials/Next/Red.dzmaterial"; // // Create a floor with RigidBodyComponent & BoxColliderComponent // Entity floor = scene->CreateEntity("Floor"); // auto& floorTransform = floor.GetComponent<TransformComponent>(); // floorTransform.Scale = {50, 1, 50}; // // set it to static, so that rigidBody will be static. // floor.GetComponent<EntityStatusComponent>().IsStatic = true; // floor.AddComponent<RigidBodyComponent>(); // floor.AddComponent<BoxColliderComponent>(smoothMaterial); // auto& floorMeshFilter = floor.AddComponent<MeshFilterComponent>(); // floorMeshFilter.PrimitiveType = MeshPrimitiveType::Cube; // auto& floorMeshRenderer = floor.AddComponent<MeshRendererComponent>(); // Create a terrain int heightMapWidth = 1000; int heightMapHeight = 1000; float xScale = 1; float yScale = 1; float zScale = 1; Entity terrain = scene->CreateEntity("Terrain"); terrain.GetComponent<TransformComponent>().Position = { -heightMapWidth * 0.5f * xScale, 0, -heightMapHeight * 0.5f * zScale}; // fix center auto& terrainComponent = terrain.AddComponent<TerrainComponent>(); terrainComponent.TerrainHeightMap = Utils::GenerateRandomHeightMap(heightMapWidth, heightMapHeight, 40); terrainComponent.XScale = xScale; terrainComponent.YScale = yScale; terrainComponent.ZScale = zScale; terrain.AddComponent<TerrainColliderComponent>(normalMaterial); auto& terrainRenderer = terrain.AddComponent<TerrainRendererComponent>(); terrainRenderer.MaterialFilePath = "Assets/Materials/Next/DefaultTerrain.dzmaterial"; } private: EngineContext* m_EngineContext; }; int main(int argc, char** argv) TRY { REGISTER_TYPE(SphereScript); DesktopAppInitInfo initInfo {}; initInfo.Engine.Window.Title = "Example - PhysicsSystem"; initInfo.Engine.Window.Fullscreen = true; DesktopApp app(argc, argv); if (!app.Init(initInfo)) { std::cerr << "Failed to initialize the application!" << std::endl; return 1; } // add a custom lifeTimeComponent to the engine app.GetEngine()->AddLifeTimeComponent(CreateRef<CustomLifeTime>()); if (!app.PostInit()) { std::cerr << "Failed to post initialize the application!" << std::endl; return 1; } app.Run(); return 0; } CATCH
1
0.762531
1
0.762531
game-dev
MEDIA
0.895122
game-dev
0.7623
1
0.7623
lua9520/source-engine-2018-hl2_src
2,117
replay/managertest.h
//========= Copyright Valve Corporation, All rights reserved. ============// // //=======================================================================================// #ifndef MANAGERTEST_H #define MANAGERTEST_H #ifdef _WIN32 #pragma once #endif //---------------------------------------------------------------------------------------- #include "genericpersistentmanager.h" #include "replay/replayhandle.h" #include "replay/irecordingsessionblockmanager.h" #include "utlstring.h" #include "baserecordingsession.h" #include "replay/basereplayserializeable.h" #include "baserecordingsessionblock.h" //---------------------------------------------------------------------------------------- class CTestObj : public CBaseReplaySerializeable { typedef CBaseReplaySerializeable BaseClass; public: CTestObj(); ~CTestObj(); virtual const char *GetSubKeyTitle() const; virtual const char *GetPath() const; virtual void OnDelete(); virtual bool Read( KeyValues *pIn ); virtual void Write( KeyValues *pOut ); CUtlString m_strTest; int m_nTest; int *m_pTest; }; //---------------------------------------------------------------------------------------- class ITestManager : public IBaseInterface { public: virtual void SomeTest() = 0; }; //---------------------------------------------------------------------------------------- class CTestManager : public CGenericPersistentManager< CTestObj >, public ITestManager { typedef CGenericPersistentManager< CTestObj > BaseClass; public: CTestManager(); static void Test(); // // CGenericPersistentManager // virtual CTestObj *Create(); virtual bool ShouldSerializeToIndividualFiles() const { return true; } virtual const char *GetIndexPath() const; virtual const char *GetDebugName() const { return "test manager"; } virtual int GetVersion() const; virtual const char *GetIndexFilename() const { return "test_index." GENERIC_FILE_EXTENSION; } // // ITestManager // virtual void SomeTest() {} }; //---------------------------------------------------------------------------------------- #endif // MANAGERTEST_H
1
0.750348
1
0.750348
game-dev
MEDIA
0.73348
game-dev,networking
0.522712
1
0.522712
Kaedrin/nwn2cc
1,231
NWN2 WIP/Source/ScriptMaster_146/cmi_s2_fotfunarmed.NSS
//:://///////////////////////////////////////////// //:: Fist of the Forest - Unarmed Damage Increase //:: cmi_s2_fotfunarmed //:: Purpose: //:: Created By: Kaedrin (Matt) //:: Created On: Aug 16, 2009 //::////////////////////////////////////////////// #include "X0_I0_SPELLS" #include "x2_inc_spellhook" #include "cmi_ginc_chars" #include "cmi_ginc_spells" void main() { object oPC = OBJECT_SELF; int nSpellId = SPELLABILITY_FOTF_UNARMED_BONUS; int bHasFOTFUnarmed = GetHasSpellEffect(nSpellId,oPC); RemoveSpellEffects(nSpellId, oPC, oPC); object oWeapon = GetItemInSlot(INVENTORY_SLOT_RIGHTHAND,OBJECT_SELF); if (oWeapon == OBJECT_INVALID) { effect eLink = EffectDamageIncrease(DAMAGE_BONUS_1d6, DAMAGE_TYPE_BLUDGEONING); eLink = SetEffectSpellId(eLink,nSpellId); eLink = SupernaturalEffect(eLink); if (!bHasFOTFUnarmed) SendMessageToPC(oPC,"Fist of the Forest Unarmed Damage Increase is now active."); DelayCommand(0.1f, cmi_ApplyEffectToObject(nSpellId, DURATION_TYPE_TEMPORARY, eLink, OBJECT_SELF, HoursToSeconds(48))); } else { if (bHasFOTFUnarmed) { SendMessageToPC(oPC,"Fist of the Forest Unarmed Damage Increase is for unarmed strikes only."); } } }
1
0.863814
1
0.863814
game-dev
MEDIA
0.995496
game-dev
0.915668
1
0.915668
DarkstarProject/darkstar
1,207
scripts/globals/spells/breakga.lua
----------------------------------------- -- Spell: Breakga -- Petrifies enemies within area of effect, preventing them from acting. ----------------------------------------- require("scripts/globals/magic") require("scripts/globals/msg") require("scripts/globals/status") ----------------------------------------- function onMagicCastingCheck(caster, target, spell) return 0 end function onSpellCast(caster, target, spell) -- Pull base stats. local dINT = caster:getStat(dsp.mod.INT) - target:getStat(dsp.mod.INT) local duration = calculateDuration(30, spell:getSkillType(), spell:getSpellGroup(), caster, target) local params = {} params.diff = dINT params.skillType = dsp.skill.ENFEEBLING_MAGIC params.bonus = 0 params.effect = dsp.effect.PETRIFICATION local resist = applyResistanceEffect(caster, target, spell, params) if resist >= 0.5 then if target:addStatusEffect(params.effect, 1, 0, duration * resist) then spell:setMsg(dsp.msg.basic.MAGIC_ENFEEB_IS) else spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) end else spell:setMsg(dsp.msg.basic.MAGIC_RESIST) end return params.effect end
1
0.527432
1
0.527432
game-dev
MEDIA
0.972622
game-dev
0.912097
1
0.912097
dingjs/javaagent
9,460
agent/src/main/java/com/wenshuo/agent/javassist/compiler/AccessorMaker.java
/* * Javassist, a Java-bytecode translator toolkit. * Copyright (C) 1999- Shigeru Chiba. All Rights Reserved. * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. Alternatively, the contents of this file may be used under * the terms of the GNU Lesser General Public License Version 2.1 or later, * or the Apache License Version 2.0. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. */ package com.wenshuo.agent.javassist.compiler; import com.wenshuo.agent.javassist.*; import com.wenshuo.agent.javassist.bytecode.*; import java.util.HashMap; /** * AccessorMaker maintains accessors to private members of an enclosing * class. It is necessary for compiling a method in an inner class. */ public class AccessorMaker { private CtClass clazz; private int uniqueNumber; private HashMap accessors; static final String lastParamType = "javassist.runtime.Inner"; public AccessorMaker(CtClass c) { clazz = c; uniqueNumber = 1; accessors = new HashMap(); } public String getConstructor(CtClass c, String desc, MethodInfo orig) throws CompileError { String key = "<init>:" + desc; String consDesc = (String)accessors.get(key); if (consDesc != null) return consDesc; // already exists. consDesc = Descriptor.appendParameter(lastParamType, desc); ClassFile cf = clazz.getClassFile(); // turn on the modified flag. try { ConstPool cp = cf.getConstPool(); ClassPool pool = clazz.getClassPool(); MethodInfo minfo = new MethodInfo(cp, MethodInfo.nameInit, consDesc); minfo.setAccessFlags(0); minfo.addAttribute(new SyntheticAttribute(cp)); ExceptionsAttribute ea = orig.getExceptionsAttribute(); if (ea != null) minfo.addAttribute(ea.copy(cp, null)); CtClass[] params = Descriptor.getParameterTypes(desc, pool); Bytecode code = new Bytecode(cp); code.addAload(0); int regno = 1; for (int i = 0; i < params.length; ++i) regno += code.addLoad(regno, params[i]); code.setMaxLocals(regno + 1); // the last parameter is added. code.addInvokespecial(clazz, MethodInfo.nameInit, desc); code.addReturn(null); minfo.setCodeAttribute(code.toCodeAttribute()); cf.addMethod(minfo); } catch (CannotCompileException e) { throw new CompileError(e); } catch (NotFoundException e) { throw new CompileError(e); } accessors.put(key, consDesc); return consDesc; } /** * Returns the name of the method for accessing a private method. * * @param name the name of the private method. * @param desc the descriptor of the private method. * @param accDesc the descriptor of the accessor method. The first * parameter type is <code>clazz</code>. * If the private method is static, * <code>accDesc</code> must be identical to <code>desc</code>. * * @param orig the method info of the private method. * @return */ public String getMethodAccessor(String name, String desc, String accDesc, MethodInfo orig) throws CompileError { String key = name + ":" + desc; String accName = (String)accessors.get(key); if (accName != null) return accName; // already exists. ClassFile cf = clazz.getClassFile(); // turn on the modified flag. accName = findAccessorName(cf); try { ConstPool cp = cf.getConstPool(); ClassPool pool = clazz.getClassPool(); MethodInfo minfo = new MethodInfo(cp, accName, accDesc); minfo.setAccessFlags(AccessFlag.STATIC); minfo.addAttribute(new SyntheticAttribute(cp)); ExceptionsAttribute ea = orig.getExceptionsAttribute(); if (ea != null) minfo.addAttribute(ea.copy(cp, null)); CtClass[] params = Descriptor.getParameterTypes(accDesc, pool); int regno = 0; Bytecode code = new Bytecode(cp); for (int i = 0; i < params.length; ++i) regno += code.addLoad(regno, params[i]); code.setMaxLocals(regno); if (desc == accDesc) code.addInvokestatic(clazz, name, desc); else code.addInvokevirtual(clazz, name, desc); code.addReturn(Descriptor.getReturnType(desc, pool)); minfo.setCodeAttribute(code.toCodeAttribute()); cf.addMethod(minfo); } catch (CannotCompileException e) { throw new CompileError(e); } catch (NotFoundException e) { throw new CompileError(e); } accessors.put(key, accName); return accName; } /** * Returns the method_info representing the added getter. */ public MethodInfo getFieldGetter(FieldInfo finfo, boolean is_static) throws CompileError { String fieldName = finfo.getName(); String key = fieldName + ":getter"; Object res = accessors.get(key); if (res != null) return (MethodInfo)res; // already exists. ClassFile cf = clazz.getClassFile(); // turn on the modified flag. String accName = findAccessorName(cf); try { ConstPool cp = cf.getConstPool(); ClassPool pool = clazz.getClassPool(); String fieldType = finfo.getDescriptor(); String accDesc; if (is_static) accDesc = "()" + fieldType; else accDesc = "(" + Descriptor.of(clazz) + ")" + fieldType; MethodInfo minfo = new MethodInfo(cp, accName, accDesc); minfo.setAccessFlags(AccessFlag.STATIC); minfo.addAttribute(new SyntheticAttribute(cp)); Bytecode code = new Bytecode(cp); if (is_static) { code.addGetstatic(Bytecode.THIS, fieldName, fieldType); } else { code.addAload(0); code.addGetfield(Bytecode.THIS, fieldName, fieldType); code.setMaxLocals(1); } code.addReturn(Descriptor.toCtClass(fieldType, pool)); minfo.setCodeAttribute(code.toCodeAttribute()); cf.addMethod(minfo); accessors.put(key, minfo); return minfo; } catch (CannotCompileException e) { throw new CompileError(e); } catch (NotFoundException e) { throw new CompileError(e); } } /** * Returns the method_info representing the added setter. */ public MethodInfo getFieldSetter(FieldInfo finfo, boolean is_static) throws CompileError { String fieldName = finfo.getName(); String key = fieldName + ":setter"; Object res = accessors.get(key); if (res != null) return (MethodInfo)res; // already exists. ClassFile cf = clazz.getClassFile(); // turn on the modified flag. String accName = findAccessorName(cf); try { ConstPool cp = cf.getConstPool(); ClassPool pool = clazz.getClassPool(); String fieldType = finfo.getDescriptor(); String accDesc; if (is_static) accDesc = "(" + fieldType + ")V"; else accDesc = "(" + Descriptor.of(clazz) + fieldType + ")V"; MethodInfo minfo = new MethodInfo(cp, accName, accDesc); minfo.setAccessFlags(AccessFlag.STATIC); minfo.addAttribute(new SyntheticAttribute(cp)); Bytecode code = new Bytecode(cp); int reg; if (is_static) { reg = code.addLoad(0, Descriptor.toCtClass(fieldType, pool)); code.addPutstatic(Bytecode.THIS, fieldName, fieldType); } else { code.addAload(0); reg = code.addLoad(1, Descriptor.toCtClass(fieldType, pool)) + 1; code.addPutfield(Bytecode.THIS, fieldName, fieldType); } code.addReturn(null); code.setMaxLocals(reg); minfo.setCodeAttribute(code.toCodeAttribute()); cf.addMethod(minfo); accessors.put(key, minfo); return minfo; } catch (CannotCompileException e) { throw new CompileError(e); } catch (NotFoundException e) { throw new CompileError(e); } } private String findAccessorName(ClassFile cf) { String accName; do { accName = "access$" + uniqueNumber++; } while (cf.getMethod(accName) != null); return accName; } }
1
0.912821
1
0.912821
game-dev
MEDIA
0.38822
game-dev,compilers-parsers
0.964199
1
0.964199
smokku/soldank
5,986
client/src/game/systems/soldier.rs
use super::*; use crate::{ engine::{input::InputState, world::WorldCameraExt}, game, physics::*, Config, EmitterItem, Soldier, }; use ::resources::Resources; use std::collections::HashMap; pub fn update_soldiers(world: &mut World, resources: &Resources, config: &Config) { let mut emitter = Vec::new(); for (_entity, (mut soldier, input, rb_pos)) in world .query::<(&mut Soldier, Option<&Input>, Option<&RigidBodyPosition>)>() .iter() { if let Some(input) = input { soldier.control.left = input.state.contains(InputState::MoveLeft); soldier.control.right = input.state.contains(InputState::MoveRight); soldier.control.up = input.state.contains(InputState::Jump); soldier.control.down = input.state.contains(InputState::Crouch); soldier.control.fire = input.state.contains(InputState::Fire); soldier.control.jets = input.state.contains(InputState::Jet); // soldier.control.grenade = input.state.contains(InputState::); soldier.control.change = input.state.contains(InputState::ChangeWeapon); soldier.control.throw = input.state.contains(InputState::ThrowGrenade); soldier.control.drop = input.state.contains(InputState::DropWeapon); soldier.control.reload = input.state.contains(InputState::Reload); soldier.control.prone = input.state.contains(InputState::Prone); // soldier.control.flag_throw = input.state.contains(InputState::); } soldier.update(resources, &mut emitter, config); if let Some(rb_pos) = rb_pos { soldier.particle.pos = Vec2::from(rb_pos.next_position.translation) * config.phys.scale; soldier.particle.pos.y += 9.; } } for item in emitter.drain(..) { match item { EmitterItem::Bullet(_params) => {} }; } } pub fn soldier_movement( world: &mut World, resources: &Resources, config: &Config, mouse: (f32, f32), now: f64, ) { let mut legs_parents = HashMap::new(); for (entity, parent) in world .query::<With<game::components::Legs, &Parent>>() .iter() { legs_parents.insert(**parent, entity); } for (body, (mut soldier, input, pawn, mut body_vel, mut body_forces, body_mp)) in world .query::<( &mut Soldier, &Input, Option<&Pawn>, &mut RigidBodyVelocity, &mut RigidBodyForces, &RigidBodyMassProps, )>() .iter() { if pawn.is_some() { let (camera, camera_position) = world.get_camera_and_camera_position(); let (x, y) = camera.mouse_to_world(*camera_position, mouse.0, mouse.1); soldier.control.mouse_aim_x = x as i32; soldier.control.mouse_aim_y = y as i32; } if let Some(legs) = legs_parents.get(&body) { const RUNSPEED: f32 = 0.118; const RUNSPEEDUP: f32 = RUNSPEED / 6.0; const MAX_VELOCITY: f32 = 11.0; const COYOTE_TIME: f64 = 0.3; let mut ground_contact = false; if let Ok(contact) = world.get::<game::physics::Contact>(*legs) { ground_contact |= !contact.entities.is_empty(); } if let Ok(phys) = world.get::<game::physics::PreviousPhysics>(*legs) { ground_contact |= (now - phys.last_contact) < COYOTE_TIME; } let radius = if ground_contact { body_vel.linvel.x.abs().clamp(3.5, 6.5) } else { 3.5 } / config.phys.scale; if let Ok(mut shape) = world.get_mut::<ColliderShape>(*legs) { if let Some(ball) = shape.make_mut().as_ball_mut() { ball.radius = radius; } let mut joint_set = resources.get_mut::<JointSet>().unwrap(); for (_, joint_handle) in world.query::<&JointHandleComponent>().iter() { if joint_handle.entity1() == *legs && joint_handle.entity2() == body {} if let Some(joint) = joint_set.get_mut(joint_handle.handle()) { joint.params = BallJoint::new( Vec2::new(0.0, 0.0).into(), Vec2::new(0.0, 10.5 / config.phys.scale - radius).into(), ) .into(); } } } if let Ok(mut legs_vel) = world.get_mut::<RigidBodyVelocity>(*legs) { legs_vel.angvel = 0.0; if input.state.contains(InputState::MoveLeft) && !input.state.contains(InputState::MoveRight) { // enable only when JETting // body_forces.force.x = -RUNSPEED * config.phys.scale; // body_forces.force.y = -RUNSPEEDUP * config.phys.scale; legs_vel.angvel = -10. * RUNSPEED * config.phys.scale; } if input.state.contains(InputState::MoveRight) && !input.state.contains(InputState::MoveLeft) { // enable only when JETting // body_forces.force.x = RUNSPEED * config.phys.scale; // body_forces.force.y = -RUNSPEEDUP * config.phys.scale; legs_vel.angvel = 10. * RUNSPEED * config.phys.scale; } // FIXME: allow only when in contact with ground if input.state.contains(InputState::Jump) { body_vel.apply_impulse(body_mp, Vec2::new(0.0, -RUNSPEED).into()); body_vel.linvel.y = f32::max(body_vel.linvel.y, -MAX_VELOCITY); body_vel.linvel.y = f32::min(body_vel.linvel.y, 0.); } } } } }
1
0.873532
1
0.873532
game-dev
MEDIA
0.991443
game-dev
0.963854
1
0.963854
CalamityTeam/CalamityModPublic
1,814
Projectiles/Typeless/PendantProjectile3.cs
using CalamityMod.Buffs.StatDebuffs; using Microsoft.Xna.Framework; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace CalamityMod.Projectiles.Typeless { public class PendantProjectile3 : ModProjectile, ILocalizedModType { public new string LocalizationCategory => "Projectiles.Typeless"; public override void SetStaticDefaults() => ProjectileID.Sets.CultistIsResistantTo[Type] = true; public override void SetDefaults() { Projectile.width = 14; Projectile.height = 14; Projectile.friendly = true; Projectile.ignoreWater = true; Projectile.timeLeft = 220; Projectile.penetrate = 1; Projectile.tileCollide = false; } public override void AI() { CalamityUtils.HomeInOnNPC(Projectile, true, 200f, 10f, 20f); Lighting.AddLight(Projectile.Center, (255 - Projectile.alpha) * 0f / 255f, (255 - Projectile.alpha) * 0.2f / 255f, (255 - Projectile.alpha) * 0.2f / 255f); Projectile.rotation += Projectile.velocity.X * 1.25f; for (int i = 0; i < 5; i++) { int dust = Dust.NewDust(Projectile.position, Projectile.width, Projectile.height, DustID.Flare_Blue, 0f, 0f, 100, default, 0.6f); Main.dust[dust].noGravity = true; Main.dust[dust].velocity *= 0.5f; Main.dust[dust].velocity += Projectile.velocity * 0.1f; } } public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType<Eutrophication>(), 60); public override void OnHitPlayer(Player target, Player.HurtInfo info) => target.AddBuff(ModContent.BuffType<Eutrophication>(), 60); } }
1
0.678459
1
0.678459
game-dev
MEDIA
0.993937
game-dev
0.952153
1
0.952153
Boolector/boolector
9,410
src/preprocess/btorskel.c
/* Boolector: Satisfiability Modulo Theories (SMT) solver. * * Copyright (C) 2007-2021 by the authors listed in the AUTHORS file. * * This file is part of Boolector. * See COPYING for more information on using this software. */ #ifdef BTOR_USE_LINGELING #include "preprocess/btorskel.h" #include "btorcore.h" #include "btordbg.h" #include "btorlog.h" #include "lglib.h" #include "utils/btorhashint.h" #include "utils/btorutil.h" static int32_t fixed_exp (Btor *btor, BtorNode *exp) { BtorNode *real_exp; BtorSATMgr *smgr; BtorAIG *aig; int32_t res, id; real_exp = btor_node_real_addr (exp); assert (btor_node_bv_get_width (btor, real_exp) == 1); if (!btor_node_is_synth (real_exp)) return 0; assert (real_exp->av); assert (real_exp->av->width == 1); assert (real_exp->av->aigs); aig = real_exp->av->aigs[0]; if (aig == BTOR_AIG_TRUE) res = 1; else if (aig == BTOR_AIG_FALSE) res = -1; else { id = btor_aig_get_cnf_id (aig); if (!id) return 0; smgr = btor_get_sat_mgr (btor); res = btor_sat_fixed (smgr, id); } if (btor_node_is_inverted (exp)) res = -res; return res; } static int32_t process_skeleton_tseitin_lit (BtorPtrHashTable *ids, BtorNode *exp) { BtorPtrHashBucket *b; BtorNode *real_exp; int32_t res; real_exp = btor_node_real_addr (exp); assert (btor_node_bv_get_width (real_exp->btor, real_exp) == 1); b = btor_hashptr_table_get (ids, real_exp); if (!b) { b = btor_hashptr_table_add (ids, real_exp); b->data.as_int = (int32_t) ids->count; } res = b->data.as_int; assert (res > 0); if (btor_node_is_inverted (exp)) res = -res; return res; } static void process_skeleton_tseitin (Btor *btor, LGL *lgl, BtorNodePtrStack *work_stack, BtorIntHashTable *mark, BtorPtrHashTable *ids, BtorNode *root) { assert (btor); int32_t i, lhs, rhs[3], fixed; BtorNode *exp; BtorHashTableData *d; BTOR_PUSH_STACK (*work_stack, root); do { exp = BTOR_POP_STACK (*work_stack); assert (exp); exp = btor_node_real_addr (exp); d = btor_hashint_map_get (mark, exp->id); if (!d) { btor_hashint_map_add (mark, exp->id); BTOR_PUSH_STACK (*work_stack, exp); for (i = exp->arity - 1; i >= 0; i--) BTOR_PUSH_STACK (*work_stack, exp->e[i]); } else if (d->as_int == 0) { d->as_int = 1; if (btor_node_is_fun (exp) || btor_node_is_args (exp) || exp->parameterized || btor_node_bv_get_width (btor, exp) != 1) continue; #ifndef NDEBUG BtorNode *child; for (i = 0; i < exp->arity; i++) { child = btor_node_real_addr (exp->e[i]); d = btor_hashint_map_get (mark, child->id); assert (d->as_int == 1); if (!btor_node_is_fun (child) && !btor_node_is_args (child) && !child->parameterized && btor_node_bv_get_width (btor, child) == 1) assert (btor_hashptr_table_get (ids, child)); } #endif lhs = process_skeleton_tseitin_lit (ids, exp); fixed = fixed_exp (btor, exp); if (fixed) { lgladd (lgl, (fixed > 0) ? lhs : -lhs); lgladd (lgl, 0); } switch (exp->kind) { case BTOR_BV_AND_NODE: rhs[0] = process_skeleton_tseitin_lit (ids, exp->e[0]); rhs[1] = process_skeleton_tseitin_lit (ids, exp->e[1]); lgladd (lgl, -lhs); lgladd (lgl, rhs[0]); lgladd (lgl, 0); lgladd (lgl, -lhs); lgladd (lgl, rhs[1]); lgladd (lgl, 0); lgladd (lgl, lhs); lgladd (lgl, -rhs[0]); lgladd (lgl, -rhs[1]); lgladd (lgl, 0); break; case BTOR_BV_EQ_NODE: if (btor_node_bv_get_width (btor, exp->e[0]) != 1) break; assert (btor_node_bv_get_width (btor, exp->e[1]) == 1); rhs[0] = process_skeleton_tseitin_lit (ids, exp->e[0]); rhs[1] = process_skeleton_tseitin_lit (ids, exp->e[1]); lgladd (lgl, -lhs); lgladd (lgl, -rhs[0]); lgladd (lgl, rhs[1]); lgladd (lgl, 0); lgladd (lgl, -lhs); lgladd (lgl, rhs[0]); lgladd (lgl, -rhs[1]); lgladd (lgl, 0); lgladd (lgl, lhs); lgladd (lgl, rhs[0]); lgladd (lgl, rhs[1]); lgladd (lgl, 0); lgladd (lgl, lhs); lgladd (lgl, -rhs[0]); lgladd (lgl, -rhs[1]); lgladd (lgl, 0); break; #if 0 // can not happen, skeleton preprocessing is enabled when // rewrite level > 2, Boolean condition are rewritten when // rewrite level > 0 case BTOR_COND_NODE: assert (btor_node_bv_get_width (btor, exp->e[0]) == 1); if (btor_node_bv_get_width (btor, exp->e[1]) != 1) break; assert (btor_node_bv_get_width (btor, exp->e[2]) == 1); rhs[0] = process_skeleton_tseitin_lit (ids, exp->e[0]); rhs[1] = process_skeleton_tseitin_lit (ids, exp->e[1]); rhs[2] = process_skeleton_tseitin_lit (ids, exp->e[2]); lgladd (lgl, -lhs); lgladd (lgl, -rhs[0]); lgladd (lgl, rhs[1]); lgladd (lgl, 0); lgladd (lgl, -lhs); lgladd (lgl, rhs[0]); lgladd (lgl, rhs[2]); lgladd (lgl, 0); lgladd (lgl, lhs); lgladd (lgl, -rhs[0]); lgladd (lgl, -rhs[1]); lgladd (lgl, 0); lgladd (lgl, lhs); lgladd (lgl, rhs[0]); lgladd (lgl, -rhs[2]); lgladd (lgl, 0); break; #endif default: assert (!btor_node_is_cond (exp)); assert (!btor_node_is_proxy (exp)); break; } } } while (!BTOR_EMPTY_STACK (*work_stack)); } void btor_process_skeleton (Btor *btor) { BtorPtrHashTable *ids; uint32_t count, fixed; BtorNodePtrStack work_stack, new_assertions; BtorMemMgr *mm = btor->mm; BtorPtrHashTableIterator it; double start, delta; int32_t res, lit, val; size_t i; BtorNode *exp; LGL *lgl; BtorIntHashTable *mark; start = btor_util_time_stamp (); ids = btor_hashptr_table_new (mm, (BtorHashPtr) btor_node_hash_by_id, (BtorCmpPtr) btor_node_compare_by_id); lgl = lglinit (); lglsetprefix (lgl, "[lglskel] "); if (btor_opt_get (btor, BTOR_OPT_VERBOSITY) >= 2) { lglsetopt (lgl, "verbose", btor_opt_get (btor, BTOR_OPT_VERBOSITY) - 1); lglbnr ("Lingeling", "[lglskel] ", stdout); fflush (stdout); } else lglsetopt (lgl, "verbose", -1); count = 0; BTOR_INIT_STACK (mm, work_stack); BTOR_INIT_STACK (mm, new_assertions); mark = btor_hashint_map_new (mm); btor_iter_hashptr_init (&it, btor->synthesized_constraints); btor_iter_hashptr_queue (&it, btor->unsynthesized_constraints); while (btor_iter_hashptr_has_next (&it)) { count++; exp = btor_iter_hashptr_next (&it); assert (btor_node_bv_get_width (btor, exp) == 1); process_skeleton_tseitin (btor, lgl, &work_stack, mark, ids, exp); lgladd (lgl, process_skeleton_tseitin_lit (ids, exp)); lgladd (lgl, 0); } BTOR_RELEASE_STACK (work_stack); btor_hashint_map_delete (mark); BTOR_MSG (btor->msg, 1, "found %u skeleton literals in %u constraints", ids->count, count); res = lglsimp (lgl, 0); if (btor_opt_get (btor, BTOR_OPT_VERBOSITY)) { BTOR_MSG (btor->msg, 1, "skeleton preprocessing result %d", res); lglstats (lgl); } fixed = 0; if (res == 20) { BTOR_MSG (btor->msg, 1, "skeleton inconsistent"); btor->inconsistent = true; } else { assert (res == 0 || res == 10); btor_iter_hashptr_init (&it, ids); while (btor_iter_hashptr_has_next (&it)) { exp = btor_iter_hashptr_next (&it); assert (!btor_node_is_inverted (exp)); lit = process_skeleton_tseitin_lit (ids, exp); val = lglfixed (lgl, lit); if (val) { if (val < 0) exp = btor_node_invert (exp); if (!btor_hashptr_table_get (btor->synthesized_constraints, exp) && !btor_hashptr_table_get (btor->unsynthesized_constraints, exp)) { BTORLOG (1, "found constraint (skeleton): %s", btor_util_node2string (exp)); BTOR_PUSH_STACK (new_assertions, exp); btor->stats.skeleton_constraints++; fixed++; } } else { assert (!btor_hashptr_table_get (btor->synthesized_constraints, exp)); assert (!btor_hashptr_table_get (btor->unsynthesized_constraints, exp)); } } } btor_hashptr_table_delete (ids); lglrelease (lgl); for (i = 0; i < BTOR_COUNT_STACK (new_assertions); i++) { btor_assert_exp (btor, BTOR_PEEK_STACK (new_assertions, i)); } BTOR_RELEASE_STACK (new_assertions); delta = btor_util_time_stamp () - start; btor->time.skel += delta; BTOR_MSG ( btor->msg, 1, "skeleton preprocessing produced %u new constraints in %.1f seconds", fixed, delta); assert (btor_dbg_check_all_hash_tables_proxy_free (btor)); assert (btor_dbg_check_all_hash_tables_simp_free (btor)); assert (btor_dbg_check_unique_table_children_proxy_free (btor)); } #endif
1
0.921694
1
0.921694
game-dev
MEDIA
0.527555
game-dev
0.942712
1
0.942712
spacechase0/StardewValleyMods
2,332
_archived/LuckSkill/docs/README.md
**Luck Skill** is a [Stardew Valley](http://stardewvalley.net/) mod which reimplements the game's unimplemented luck skill and adds professions for it. ## Install 1. Install the latest version of... * [SMAPI](https://smapi.io); * and [SpaceCore](https://www.nexusmods.com/stardewvalley/mods/1348). 2. Install [this mod from Nexus Mods](http://www.nexusmods.com/stardewvalley/mods/521). 3. Run the game using SMAPI. ## Use Just like the normal skills, the luck skill appears on the player tab of the game menu, and you can level it up and choose professions. You get luck skill based on your daily luck (what the fortune teller TV channel mentions), when you fish up treasure, and when you crack open a geode. ### Available professions * Level 5: Fortunate (better daily luck). * Level 10: Lucky (20% chance for max daily luck). * Level 10: Un-unlucky (Never have bad luck). * Level 5: Popular Helper (Daily quests occur three times as often). * Level 10: Shooting Star (Nightly events occur twice as often). * Level 10: Spirit Child (Giving gifts makes Junimos happy; 15% chance for some form of farm advancement). ### Effects The luck skill affects... * fishing treasure (chance of treasure appearing, larger stack sizes, and better rings); * panning; * something to do with lightning; * items you get from mineshaft stones; * chance of getting gold-star fish; * the wheel spin minigame at the Stardew Valley Fair; * the slots minigame at the Casino; * the chance to get buff from warrior ring; * the amount of wood from cutting trees; * extra harvests from non-scythe crops (?); * stuff dropped on death in mines (?); * items dropped on death resulting in hospital (?); * Level 8: Lucky lunch recipe (?) and cooking channel in spring 28 of year 2); * yoba ring buff; * crit chance; * ore dropped; * random coal drops; * chance of spouse finding out you gave someone else dateable of the same gender a gift (-30 relation points). Food that buffs luck affects most (but not all) of this. ## Compatibility Compatible with Stardew Valley 1.5.5+ on Linux/macOS/Windows, both single-player and multiplayer. Compatible with [Experience Bars](https://www.nexusmods.com/stardewvalley/mods/509) and [All Professions](https://www.nexusmods.com/stardewvalley/mods/174). ## See also * [Release notes](release-notes.md)
1
0.733534
1
0.733534
game-dev
MEDIA
0.996463
game-dev
0.594302
1
0.594302
PerpetuumOnline/PerpetuumServer
1,705
src/Perpetuum/Zones/Terrains/Materials/Minerals/Generators/RandomWalkMineralNodeGenerator.cs
using System.Collections.Generic; using System.Drawing; using System.Linq; namespace Perpetuum.Zones.Terrains.Materials.Minerals.Generators { public class RandomWalkMineralNodeGenerator : MineralNodeGeneratorBase { public RandomWalkMineralNodeGenerator(IZone zone) : base(zone) { BrushSize = 4; } private int BrushSize { get; set; } protected override Dictionary<Point,double> GenerateNoise(Position startPosition) { var closed = new HashSet<Point>(); var tiles = new Dictionary<Point,double>(); var q = new Queue<Point>(); q.Enqueue(startPosition); var i = 0; while (q.TryDequeue(out Point current) && i < 50000) { i++; foreach (var point in current.FloodFill(IsValid).Take(BrushSize * BrushSize)) { tiles.AddOrUpdate(point,1,c => c + 1); if (tiles.Count >= MaxTiles) return tiles; } var r = new List<Point>(); foreach (var np in current.GetNeighbours()) { if (closed.Contains(np)) continue; if (!IsValid(np)) { closed.Add(np); continue; } r.Add(np); } if (r.Count == 0) q.Enqueue(tiles.Keys.RandomElement()); else q.Enqueue(r.RandomElement()); } return tiles; } } }
1
0.940924
1
0.940924
game-dev
MEDIA
0.763495
game-dev
0.98932
1
0.98932
onyx-intl/boox-opensource
24,837
third_party/gtest/include/gtest/internal/gtest-param-util.h
// Copyright 2008 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. // // Author: vladl@google.com (Vlad Losev) // Type and function utilities for implementing parameterized tests. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ #include <iterator> #include <utility> #include <vector> #include <gtest/internal/gtest-port.h> #if GTEST_HAS_PARAM_TEST #if GTEST_HAS_RTTI #include <typeinfo> #endif // GTEST_HAS_RTTI #include <gtest/internal/gtest-linked_ptr.h> #include <gtest/internal/gtest-internal.h> namespace testing { namespace internal { // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Outputs a message explaining invalid registration of different // fixture class for the same test case. This may happen when // TEST_P macro is used to define two tests with the same name // but in different namespaces. void ReportInvalidTestCaseType(const char* test_case_name, const char* file, int line); // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Downcasts the pointer of type Base to Derived. // Derived must be a subclass of Base. The parameter MUST // point to a class of type Derived, not any subclass of it. // When RTTI is available, the function performs a runtime // check to enforce this. template <class Derived, class Base> Derived* CheckedDowncastToActualType(Base* base) { #if GTEST_HAS_RTTI GTEST_CHECK_(typeid(*base) == typeid(Derived)); Derived* derived = dynamic_cast<Derived*>(base); // NOLINT #else Derived* derived = static_cast<Derived*>(base); // Poor man's downcast. #endif // GTEST_HAS_RTTI return derived; } template <typename> class ParamGeneratorInterface; template <typename> class ParamGenerator; // Interface for iterating over elements provided by an implementation // of ParamGeneratorInterface<T>. template <typename T> class ParamIteratorInterface { public: virtual ~ParamIteratorInterface() {} // A pointer to the base generator instance. // Used only for the purposes of iterator comparison // to make sure that two iterators belong to the same generator. virtual const ParamGeneratorInterface<T>* BaseGenerator() const = 0; // Advances iterator to point to the next element // provided by the generator. The caller is responsible // for not calling Advance() on an iterator equal to // BaseGenerator()->End(). virtual void Advance() = 0; // Clones the iterator object. Used for implementing copy semantics // of ParamIterator<T>. virtual ParamIteratorInterface* Clone() const = 0; // Dereferences the current iterator and provides (read-only) access // to the pointed value. It is the caller's responsibility not to call // Current() on an iterator equal to BaseGenerator()->End(). // Used for implementing ParamGenerator<T>::operator*(). virtual const T* Current() const = 0; // Determines whether the given iterator and other point to the same // element in the sequence generated by the generator. // Used for implementing ParamGenerator<T>::operator==(). virtual bool Equals(const ParamIteratorInterface& other) const = 0; }; // Class iterating over elements provided by an implementation of // ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T> // and implements the const forward iterator concept. template <typename T> class ParamIterator { public: typedef T value_type; typedef const T& reference; typedef ptrdiff_t difference_type; // ParamIterator assumes ownership of the impl_ pointer. ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {} ParamIterator& operator=(const ParamIterator& other) { if (this != &other) impl_.reset(other.impl_->Clone()); return *this; } const T& operator*() const { return *impl_->Current(); } const T* operator->() const { return impl_->Current(); } // Prefix version of operator++. ParamIterator& operator++() { impl_->Advance(); return *this; } // Postfix version of operator++. ParamIterator operator++(int /*unused*/) { ParamIteratorInterface<T>* clone = impl_->Clone(); impl_->Advance(); return ParamIterator(clone); } bool operator==(const ParamIterator& other) const { return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_); } bool operator!=(const ParamIterator& other) const { return !(*this == other); } private: friend class ParamGenerator<T>; explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {} scoped_ptr<ParamIteratorInterface<T> > impl_; }; // ParamGeneratorInterface<T> is the binary interface to access generators // defined in other translation units. template <typename T> class ParamGeneratorInterface { public: typedef T ParamType; virtual ~ParamGeneratorInterface() {} // Generator interface definition virtual ParamIteratorInterface<T>* Begin() const = 0; virtual ParamIteratorInterface<T>* End() const = 0; }; // Wraps ParamGeneratorInetrface<T> and provides general generator syntax // compatible with the STL Container concept. // This class implements copy initialization semantics and the contained // ParamGeneratorInterface<T> instance is shared among all copies // of the original object. This is possible because that instance is immutable. template<typename T> class ParamGenerator { public: typedef ParamIterator<T> iterator; explicit ParamGenerator(ParamGeneratorInterface<T>* impl) : impl_(impl) {} ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {} ParamGenerator& operator=(const ParamGenerator& other) { impl_ = other.impl_; return *this; } iterator begin() const { return iterator(impl_->Begin()); } iterator end() const { return iterator(impl_->End()); } private: ::testing::internal::linked_ptr<const ParamGeneratorInterface<T> > impl_; }; // Generates values from a range of two comparable values. Can be used to // generate sequences of user-defined types that implement operator+() and // operator<(). // This class is used in the Range() function. template <typename T, typename IncrementT> class RangeGenerator : public ParamGeneratorInterface<T> { public: RangeGenerator(T begin, T end, IncrementT step) : begin_(begin), end_(end), step_(step), end_index_(CalculateEndIndex(begin, end, step)) {} virtual ~RangeGenerator() {} virtual ParamIteratorInterface<T>* Begin() const { return new Iterator(this, begin_, 0, step_); } virtual ParamIteratorInterface<T>* End() const { return new Iterator(this, end_, end_index_, step_); } private: class Iterator : public ParamIteratorInterface<T> { public: Iterator(const ParamGeneratorInterface<T>* base, T value, int index, IncrementT step) : base_(base), value_(value), index_(index), step_(step) {} virtual ~Iterator() {} virtual const ParamGeneratorInterface<T>* BaseGenerator() const { return base_; } virtual void Advance() { value_ = value_ + step_; index_++; } virtual ParamIteratorInterface<T>* Clone() const { return new Iterator(*this); } virtual const T* Current() const { return &value_; } virtual bool Equals(const ParamIteratorInterface<T>& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const int other_index = CheckedDowncastToActualType<const Iterator>(&other)->index_; return index_ == other_index; } private: Iterator(const Iterator& other) : base_(other.base_), value_(other.value_), index_(other.index_), step_(other.step_) {} // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface<T>* const base_; T value_; int index_; const IncrementT step_; }; // class RangeGenerator::Iterator static int CalculateEndIndex(const T& begin, const T& end, const IncrementT& step) { int end_index = 0; for (T i = begin; i < end; i = i + step) end_index++; return end_index; } // No implementation - assignment is unsupported. void operator=(const RangeGenerator& other); const T begin_; const T end_; const IncrementT step_; // The index for the end() iterator. All the elements in the generated // sequence are indexed (0-based) to aid iterator comparison. const int end_index_; }; // class RangeGenerator // Generates values from a pair of STL-style iterators. Used in the // ValuesIn() function. The elements are copied from the source range // since the source can be located on the stack, and the generator // is likely to persist beyond that stack frame. template <typename T> class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> { public: template <typename ForwardIterator> ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end) : container_(begin, end) {} virtual ~ValuesInIteratorRangeGenerator() {} virtual ParamIteratorInterface<T>* Begin() const { return new Iterator(this, container_.begin()); } virtual ParamIteratorInterface<T>* End() const { return new Iterator(this, container_.end()); } private: typedef typename ::std::vector<T> ContainerType; class Iterator : public ParamIteratorInterface<T> { public: Iterator(const ParamGeneratorInterface<T>* base, typename ContainerType::const_iterator iterator) : base_(base), iterator_(iterator) {} virtual ~Iterator() {} virtual const ParamGeneratorInterface<T>* BaseGenerator() const { return base_; } virtual void Advance() { ++iterator_; value_.reset(); } virtual ParamIteratorInterface<T>* Clone() const { return new Iterator(*this); } // We need to use cached value referenced by iterator_ because *iterator_ // can return a temporary object (and of type other then T), so just // having "return &*iterator_;" doesn't work. // value_ is updated here and not in Advance() because Advance() // can advance iterator_ beyond the end of the range, and we cannot // detect that fact. The client code, on the other hand, is // responsible for not calling Current() on an out-of-range iterator. virtual const T* Current() const { if (value_.get() == NULL) value_.reset(new T(*iterator_)); return value_.get(); } virtual bool Equals(const ParamIteratorInterface<T>& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; return iterator_ == CheckedDowncastToActualType<const Iterator>(&other)->iterator_; } private: Iterator(const Iterator& other) // The explicit constructor call suppresses a false warning // emitted by gcc when supplied with the -Wextra option. : ParamIteratorInterface<T>(), base_(other.base_), iterator_(other.iterator_) {} const ParamGeneratorInterface<T>* const base_; typename ContainerType::const_iterator iterator_; // A cached value of *iterator_. We keep it here to allow access by // pointer in the wrapping iterator's operator->(). // value_ needs to be mutable to be accessed in Current(). // Use of scoped_ptr helps manage cached value's lifetime, // which is bound by the lifespan of the iterator itself. mutable scoped_ptr<const T> value_; }; // class ValuesInIteratorRangeGenerator::Iterator // No implementation - assignment is unsupported. void operator=(const ValuesInIteratorRangeGenerator& other); const ContainerType container_; }; // class ValuesInIteratorRangeGenerator // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Stores a parameter value and later creates tests parameterized with that // value. template <class TestClass> class ParameterizedTestFactory : public TestFactoryBase { public: typedef typename TestClass::ParamType ParamType; explicit ParameterizedTestFactory(ParamType parameter) : parameter_(parameter) {} virtual Test* CreateTest() { TestClass::SetParam(&parameter_); return new TestClass(); } private: const ParamType parameter_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory); }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // TestMetaFactoryBase is a base class for meta-factories that create // test factories for passing into MakeAndRegisterTestInfo function. template <class ParamType> class TestMetaFactoryBase { public: virtual ~TestMetaFactoryBase() {} virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0; }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // TestMetaFactory creates test factories for passing into // MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives // ownership of test factory pointer, same factory object cannot be passed // into that method twice. But ParameterizedTestCaseInfo is going to call // it for each Test/Parameter value combination. Thus it needs meta factory // creator class. template <class TestCase> class TestMetaFactory : public TestMetaFactoryBase<typename TestCase::ParamType> { public: typedef typename TestCase::ParamType ParamType; TestMetaFactory() {} virtual TestFactoryBase* CreateTestFactory(ParamType parameter) { return new ParameterizedTestFactory<TestCase>(parameter); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory); }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // ParameterizedTestCaseInfoBase is a generic interface // to ParameterizedTestCaseInfo classes. ParameterizedTestCaseInfoBase // accumulates test information provided by TEST_P macro invocations // and generators provided by INSTANTIATE_TEST_CASE_P macro invocations // and uses that information to register all resulting test instances // in RegisterTests method. The ParameterizeTestCaseRegistry class holds // a collection of pointers to the ParameterizedTestCaseInfo objects // and calls RegisterTests() on each of them when asked. class ParameterizedTestCaseInfoBase { public: virtual ~ParameterizedTestCaseInfoBase() {} // Base part of test case name for display purposes. virtual const String& GetTestCaseName() const = 0; // Test case id to verify identity. virtual TypeId GetTestCaseTypeId() const = 0; // UnitTest class invokes this method to register tests in this // test case right before running them in RUN_ALL_TESTS macro. // This method should not be called more then once on any single // instance of a ParameterizedTestCaseInfoBase derived class. virtual void RegisterTests() = 0; protected: ParameterizedTestCaseInfoBase() {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfoBase); }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // ParameterizedTestCaseInfo accumulates tests obtained from TEST_P // macro invocations for a particular test case and generators // obtained from INSTANTIATE_TEST_CASE_P macro invocations for that // test case. It registers tests with all values generated by all // generators when asked. template <class TestCase> class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { public: // ParamType and GeneratorCreationFunc are private types but are required // for declarations of public methods AddTestPattern() and // AddTestCaseInstantiation(). typedef typename TestCase::ParamType ParamType; // A function that returns an instance of appropriate generator type. typedef ParamGenerator<ParamType>(GeneratorCreationFunc)(); explicit ParameterizedTestCaseInfo(const char* name) : test_case_name_(name) {} // Test case base name for display purposes. virtual const String& GetTestCaseName() const { return test_case_name_; } // Test case id to verify identity. virtual TypeId GetTestCaseTypeId() const { return GetTypeId<TestCase>(); } // TEST_P macro uses AddTestPattern() to record information // about a single test in a LocalTestInfo structure. // test_case_name is the base name of the test case (without invocation // prefix). test_base_name is the name of an individual test without // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is // test case base name and DoBar is test base name. void AddTestPattern(const char* test_case_name, const char* test_base_name, TestMetaFactoryBase<ParamType>* meta_factory) { tests_.push_back(linked_ptr<TestInfo>(new TestInfo(test_case_name, test_base_name, meta_factory))); } // INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information // about a generator. int AddTestCaseInstantiation(const char* instantiation_name, GeneratorCreationFunc* func, const char* /* file */, int /* line */) { instantiations_.push_back(::std::make_pair(instantiation_name, func)); return 0; // Return value used only to run this method in namespace scope. } // UnitTest class invokes this method to register tests in this test case // test cases right before running tests in RUN_ALL_TESTS macro. // This method should not be called more then once on any single // instance of a ParameterizedTestCaseInfoBase derived class. // UnitTest has a guard to prevent from calling this method more then once. virtual void RegisterTests() { for (typename TestInfoContainer::iterator test_it = tests_.begin(); test_it != tests_.end(); ++test_it) { linked_ptr<TestInfo> test_info = *test_it; for (typename InstantiationContainer::iterator gen_it = instantiations_.begin(); gen_it != instantiations_.end(); ++gen_it) { const String& instantiation_name = gen_it->first; ParamGenerator<ParamType> generator((*gen_it->second)()); Message test_case_name_stream; if ( !instantiation_name.empty() ) test_case_name_stream << instantiation_name.c_str() << "/"; test_case_name_stream << test_info->test_case_base_name.c_str(); int i = 0; for (typename ParamGenerator<ParamType>::iterator param_it = generator.begin(); param_it != generator.end(); ++param_it, ++i) { Message test_name_stream; test_name_stream << test_info->test_base_name.c_str() << "/" << i; ::testing::internal::MakeAndRegisterTestInfo( test_case_name_stream.GetString().c_str(), test_name_stream.GetString().c_str(), "", // test_case_comment "", // comment; TODO(vladl@google.com): provide parameter value // representation. GetTestCaseTypeId(), TestCase::SetUpTestCase, TestCase::TearDownTestCase, test_info->test_meta_factory->CreateTestFactory(*param_it)); } // for param_it } // for gen_it } // for test_it } // RegisterTests private: // LocalTestInfo structure keeps information about a single test registered // with TEST_P macro. struct TestInfo { TestInfo(const char* test_case_base_name, const char* test_base_name, TestMetaFactoryBase<ParamType>* test_meta_factory) : test_case_base_name(test_case_base_name), test_base_name(test_base_name), test_meta_factory(test_meta_factory) {} const String test_case_base_name; const String test_base_name; const scoped_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory; }; typedef ::std::vector<linked_ptr<TestInfo> > TestInfoContainer; // Keeps pairs of <Instantiation name, Sequence generator creation function> // received from INSTANTIATE_TEST_CASE_P macros. typedef ::std::vector<std::pair<String, GeneratorCreationFunc*> > InstantiationContainer; const String test_case_name_; TestInfoContainer tests_; InstantiationContainer instantiations_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfo); }; // class ParameterizedTestCaseInfo // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // ParameterizedTestCaseRegistry contains a map of ParameterizedTestCaseInfoBase // classes accessed by test case names. TEST_P and INSTANTIATE_TEST_CASE_P // macros use it to locate their corresponding ParameterizedTestCaseInfo // descriptors. class ParameterizedTestCaseRegistry { public: ParameterizedTestCaseRegistry() {} ~ParameterizedTestCaseRegistry() { for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); it != test_case_infos_.end(); ++it) { delete *it; } } // Looks up or creates and returns a structure containing information about // tests and instantiations of a particular test case. template <class TestCase> ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder( const char* test_case_name, const char* file, int line) { ParameterizedTestCaseInfo<TestCase>* typed_test_info = NULL; for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); it != test_case_infos_.end(); ++it) { if ((*it)->GetTestCaseName() == test_case_name) { if ((*it)->GetTestCaseTypeId() != GetTypeId<TestCase>()) { // Complain about incorrect usage of Google Test facilities // and terminate the program since we cannot guaranty correct // test case setup and tear-down in this case. ReportInvalidTestCaseType(test_case_name, file, line); abort(); } else { // At this point we are sure that the object we found is of the same // type we are looking for, so we downcast it to that type // without further checks. typed_test_info = CheckedDowncastToActualType< ParameterizedTestCaseInfo<TestCase> >(*it); } break; } } if (typed_test_info == NULL) { typed_test_info = new ParameterizedTestCaseInfo<TestCase>(test_case_name); test_case_infos_.push_back(typed_test_info); } return typed_test_info; } void RegisterTests() { for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); it != test_case_infos_.end(); ++it) { (*it)->RegisterTests(); } } private: typedef ::std::vector<ParameterizedTestCaseInfoBase*> TestCaseInfoContainer; TestCaseInfoContainer test_case_infos_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseRegistry); }; } // namespace internal } // namespace testing #endif // GTEST_HAS_PARAM_TEST #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
1
0.939799
1
0.939799
game-dev
MEDIA
0.150565
game-dev
0.938425
1
0.938425
emoose/Arise-SDK
10,633
src/SDK/PhysXVehicles_parameters.h
#pragma once #include "../SDK.h" // Name: Arise, Version: 1.0.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function PhysXVehicles.WheeledVehicleMovementComponent.SetUseAutoGears struct UWheeledVehicleMovementComponent_SetUseAutoGears_Params { bool bUseAuto; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.SetThrottleInput struct UWheeledVehicleMovementComponent_SetThrottleInput_Params { float Throttle; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.SetTargetGear struct UWheeledVehicleMovementComponent_SetTargetGear_Params { int GearNum; // (Parm, ZeroConstructor, IsPlainOldData) bool bImmediate; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.SetSteeringInput struct UWheeledVehicleMovementComponent_SetSteeringInput_Params { float Steering; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.SetHandbrakeInput struct UWheeledVehicleMovementComponent_SetHandbrakeInput_Params { bool bNewHandbrake; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.SetGroupsToIgnoreMask struct UWheeledVehicleMovementComponent_SetGroupsToIgnoreMask_Params { struct FNavAvoidanceMask GroupMask; // (ConstParm, Parm, OutParm, ReferenceParm, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.SetGroupsToIgnore struct UWheeledVehicleMovementComponent_SetGroupsToIgnore_Params { int GroupFlags; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.SetGroupsToAvoidMask struct UWheeledVehicleMovementComponent_SetGroupsToAvoidMask_Params { struct FNavAvoidanceMask GroupMask; // (ConstParm, Parm, OutParm, ReferenceParm, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.SetGroupsToAvoid struct UWheeledVehicleMovementComponent_SetGroupsToAvoid_Params { int GroupFlags; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.SetGearUp struct UWheeledVehicleMovementComponent_SetGearUp_Params { bool bNewGearUp; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.SetGearDown struct UWheeledVehicleMovementComponent_SetGearDown_Params { bool bNewGearDown; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.SetBrakeInput struct UWheeledVehicleMovementComponent_SetBrakeInput_Params { float Brake; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.SetAvoidanceGroupMask struct UWheeledVehicleMovementComponent_SetAvoidanceGroupMask_Params { struct FNavAvoidanceMask GroupMask; // (ConstParm, Parm, OutParm, ReferenceParm, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.SetAvoidanceGroup struct UWheeledVehicleMovementComponent_SetAvoidanceGroup_Params { int GroupFlags; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.SetAvoidanceEnabled struct UWheeledVehicleMovementComponent_SetAvoidanceEnabled_Params { bool bEnable; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.ServerUpdateState struct UWheeledVehicleMovementComponent_ServerUpdateState_Params { float InSteeringInput; // (Parm, ZeroConstructor, IsPlainOldData) float InThrottleInput; // (Parm, ZeroConstructor, IsPlainOldData) float InBrakeInput; // (Parm, ZeroConstructor, IsPlainOldData) float InHandbrakeInput; // (Parm, ZeroConstructor, IsPlainOldData) int CurrentGear; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.GetUseAutoGears struct UWheeledVehicleMovementComponent_GetUseAutoGears_Params { bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.GetTargetGear struct UWheeledVehicleMovementComponent_GetTargetGear_Params { int ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.GetForwardSpeed struct UWheeledVehicleMovementComponent_GetForwardSpeed_Params { float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.GetEngineRotationSpeed struct UWheeledVehicleMovementComponent_GetEngineRotationSpeed_Params { float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.GetEngineMaxRotationSpeed struct UWheeledVehicleMovementComponent_GetEngineMaxRotationSpeed_Params { float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function PhysXVehicles.WheeledVehicleMovementComponent.GetCurrentGear struct UWheeledVehicleMovementComponent_GetCurrentGear_Params { int ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function PhysXVehicles.SimpleWheeledVehicleMovementComponent.SetSteerAngle struct USimpleWheeledVehicleMovementComponent_SetSteerAngle_Params { float SteerAngle; // (Parm, ZeroConstructor, IsPlainOldData) int WheelIndex; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function PhysXVehicles.SimpleWheeledVehicleMovementComponent.SetDriveTorque struct USimpleWheeledVehicleMovementComponent_SetDriveTorque_Params { float DriveTorque; // (Parm, ZeroConstructor, IsPlainOldData) int WheelIndex; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function PhysXVehicles.SimpleWheeledVehicleMovementComponent.SetBrakeTorque struct USimpleWheeledVehicleMovementComponent_SetBrakeTorque_Params { float BrakeTorque; // (Parm, ZeroConstructor, IsPlainOldData) int WheelIndex; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function PhysXVehicles.VehicleAnimInstance.GetVehicle struct UVehicleAnimInstance_GetVehicle_Params { class AWheeledVehicle* ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function PhysXVehicles.VehicleWheel.IsInAir struct UVehicleWheel_IsInAir_Params { bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function PhysXVehicles.VehicleWheel.GetSuspensionOffset struct UVehicleWheel_GetSuspensionOffset_Params { float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function PhysXVehicles.VehicleWheel.GetSteerAngle struct UVehicleWheel_GetSteerAngle_Params { float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function PhysXVehicles.VehicleWheel.GetRotationAngle struct UVehicleWheel_GetRotationAngle_Params { float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
1
0.673944
1
0.673944
game-dev
MEDIA
0.945802
game-dev
0.625131
1
0.625131
onitama/OpenHSP
8,450
src/hsp3dish/gameplay/src/TileSet.cpp
#include "Base.h" #include "TileSet.h" #include "Matrix.h" #include "Scene.h" namespace gameplay { TileSet::TileSet() : Drawable(), _tiles(NULL), _tileWidth(0), _tileHeight(0), _rowCount(0), _columnCount(0), _width(0), _height(0), _opacity(1.0f), _color(Vector4::one()), _batch(NULL) { } TileSet::~TileSet() { SAFE_DELETE_ARRAY(_tiles); SAFE_DELETE(_batch); } TileSet& TileSet::operator=(const TileSet& set) { return *this; } TileSet* TileSet::create(const char* imagePath, float tileWidth, float tileHeight, unsigned int rowCount, unsigned int columnCount) { GP_ASSERT(imagePath); GP_ASSERT(tileWidth > 0 && tileHeight > 0); GP_ASSERT(rowCount > 0 && columnCount > 0); SpriteBatch* batch = SpriteBatch::create(imagePath); batch->getSampler()->setWrapMode(Texture::CLAMP, Texture::CLAMP); batch->getSampler()->setFilterMode(Texture::Filter::NEAREST, Texture::Filter::NEAREST); batch->getStateBlock()->setDepthWrite(false); batch->getStateBlock()->setDepthTest(true); TileSet* tileset = new TileSet(); tileset->_batch = batch; tileset->_tiles = new Vector2[rowCount * columnCount]; memset(tileset->_tiles, -1, sizeof(float) * rowCount * columnCount * 2); tileset->_tileWidth = tileWidth; tileset->_tileHeight = tileHeight; tileset->_rowCount = rowCount; tileset->_columnCount = columnCount; tileset->_width = tileWidth * columnCount; tileset->_height = tileHeight * rowCount; return tileset; } TileSet* TileSet::create(Properties* properties) { // Check if the Properties is valid and has a valid namespace. if (!properties || strcmp(properties->getNamespace(), "tileset") != 0) { GP_ERROR("Properties object must be non-null and have namespace equal to 'tileset'."); return NULL; } // Get image path. const char* imagePath = properties->getString("path"); if (imagePath == NULL || strlen(imagePath) == 0) { GP_ERROR("TileSet is missing required image file path."); return NULL; } // Get set size int rows = properties->getInt("rows"); if (rows <= 0) { GP_ERROR("TileSet row count must be greater then zero."); return NULL; } int columns = properties->getInt("columns"); if (columns <= 0) { GP_ERROR("TileSet column count must be greater then zero."); return NULL; } // Get tile size float tileWidth = properties->getFloat("tileWidth"); if (tileWidth <= 0) { GP_ERROR("TileSet tile width must be greater then zero."); return NULL; } float tileHeight = properties->getFloat("tileHeight"); if (tileHeight <= 0) { GP_ERROR("TileSet tile height must be greater then zero."); return NULL; } // Create tile set TileSet* set = TileSet::create(imagePath, tileWidth, tileHeight, rows, columns); // Get color if (properties->exists("color")) { Vector4 color; switch (properties->getType("color")) { case Properties::VECTOR3: color.w = 1.0f; properties->getVector3("color", (Vector3*)&color); break; case Properties::VECTOR4: properties->getVector4("color", &color); break; case Properties::STRING: default: properties->getColor("color", &color); break; } set->setColor(color); } // Get opacity if (properties->exists("opacity")) { set->setOpacity(properties->getFloat("opacity")); } // Get tile sources properties->rewind(); Properties* tileProperties = NULL; while ((tileProperties = properties->getNextNamespace())) { if (strcmp(tileProperties->getNamespace(), "tile") == 0) { Vector2 cell; Vector2 source; if (tileProperties->getVector2("cell", &cell) && tileProperties->getVector2("source", &source) && (cell.x >= 0 && cell.y >= 0 && cell.x < set->_columnCount && cell.y < set->_rowCount)) { set->_tiles[(int)cell.y * set->_columnCount + (int)cell.x] = source; } } } return set; } void TileSet::setTileSource(unsigned int column, unsigned int row, const Vector2& source) { GP_ASSERT(column < _columnCount); GP_ASSERT(row < _rowCount); _tiles[row * _columnCount + column] = source; } void TileSet::getTileSource(unsigned int column, unsigned int row, Vector2* source) { GP_ASSERT(column < _columnCount); GP_ASSERT(row < _rowCount); GP_ASSERT(source); source->x = _tiles[row * _columnCount + column].x; source->y = _tiles[row * _columnCount + column].y; } float TileSet::getTileWidth() const { return _tileWidth; } float TileSet::getTileHeight() const { return _tileHeight; } unsigned int TileSet::getRowCount() const { return _rowCount; } unsigned int TileSet::getColumnCount() const { return _columnCount; } float TileSet::getWidth() const { return _width; } float TileSet::getHeight() const { return _height; } void TileSet::setOpacity(float opacity) { _opacity = opacity; } float TileSet::getOpacity() const { return _opacity; } void TileSet::setColor(const Vector4& color) { _color = color; } const Vector4& TileSet::getColor() const { return _color; } unsigned int TileSet::draw(bool wireframe) { // Apply scene camera projection and translation offsets Vector3 position = Vector3::zero(); if (_node && _node->getScene()) { Camera* activeCamera = _node->getScene()->getActiveCamera(); if (activeCamera) { Node* cameraNode = _node->getScene()->getActiveCamera()->getNode(); if (cameraNode) { // Scene projection Matrix projectionMatrix; projectionMatrix = _node->getProjectionMatrix(); _batch->setProjectionMatrix(projectionMatrix); position.x -= cameraNode->getTranslationWorld().x; position.y -= cameraNode->getTranslationWorld().y; } } // Apply node translation offsets Vector3 translation = _node->getTranslationWorld(); position.x += translation.x; position.y += translation.y; position.z += translation.z; } // Draw each cell in the tile set position.y += _tileHeight * (_rowCount - 1); float xStart = position.x; _batch->start(); for (unsigned int row = 0; row < _rowCount; row++) { for (unsigned int col = 0; col < _columnCount; col++) { Vector2 scale = Vector2(_tileWidth, _tileHeight); // Negative values are skipped to allow blank tiles if (_tiles[row * _columnCount + col].x >= 0 && _tiles[row * _columnCount + col].y >= 0) { Rectangle source = Rectangle(_tiles[row * _columnCount + col].x, _tiles[row * _columnCount + col].y, _tileWidth, _tileHeight); _batch->draw(position, source, scale, Vector4(_color.x, _color.y, _color.z, _color.w * _opacity), Vector2(0.5f, 0.5f), 0); } position.x += _tileWidth; } position.x = xStart; position.y -= _tileHeight; } _batch->finish(); return 1; } Drawable* TileSet::clone(NodeCloneContext& context) { TileSet* tilesetClone = new TileSet(); // Clone properties tilesetClone->_tiles = new Vector2[tilesetClone->_rowCount * tilesetClone->_columnCount]; memset(tilesetClone->_tiles, -1, sizeof(float) * tilesetClone->_rowCount * tilesetClone->_columnCount * 2); memcpy(tilesetClone->_tiles, _tiles, sizeof(Vector2) * tilesetClone->_rowCount * tilesetClone->_columnCount); tilesetClone->_tileWidth = _tileWidth; tilesetClone->_tileHeight = _tileHeight; tilesetClone->_rowCount = _rowCount; tilesetClone->_columnCount = _columnCount; tilesetClone->_width = _tileWidth * _columnCount; tilesetClone->_height = _tileHeight * _rowCount; tilesetClone->_opacity = _opacity; tilesetClone->_color = _color; tilesetClone->_batch = _batch; return tilesetClone; } }
1
0.902992
1
0.902992
game-dev
MEDIA
0.632162
game-dev,graphics-rendering
0.967047
1
0.967047
micahflee/TM-SGNL-iOS
1,925
SignalServiceKit/Util/NSTimer+OWS.swift
// // Copyright 2024 Signal Messenger, LLC // SPDX-License-Identifier: AGPL-3.0-only // import Foundation private class TimerProxy { weak var target: AnyObject? let selector: Selector init(target: AnyObject?, selector: Selector) { self.target = target self.selector = selector } @objc func timerFired(_ timer: Timer) { guard let target else { timer.invalidate() return } _ = target.perform(selector, with: timer) } } extension Timer { /// This method avoids the classic NSTimer retain cycle bug by using a weak reference to the target. @objc @available(swift, obsoleted: 1) public static func weakScheduledTimer(withTimeInterval timeInterval: TimeInterval, target: AnyObject, selector: Selector, userInfo: Any?, repeats: Bool) -> Timer { let proxy = TimerProxy(target: target, selector: selector) return Timer.scheduledTimer(timeInterval: timeInterval, target: proxy, selector: #selector(TimerProxy.timerFired(_:)), userInfo: userInfo, repeats: repeats) } /// This method avoids the classic NSTimer retain cycle bug by using a weak reference to the target. @objc @available(swift, obsoleted: 1) public static func weakTimer(withTimeInterval timeInterval: TimeInterval, target: AnyObject, selector: Selector, userInfo: Any?, repeats: Bool) -> Timer { let proxy = TimerProxy(target: target, selector: selector) return Timer(timeInterval: timeInterval, target: proxy, selector: #selector(TimerProxy.timerFired(_:)), userInfo: userInfo, repeats: repeats) } }
1
0.87016
1
0.87016
game-dev
MEDIA
0.624231
game-dev
0.849425
1
0.849425
reeseschultz/ReeseUnityDemos
7,516
Assets/Scripts/Path/PathQuadrantSystem.cs
using Reese.Path; using Unity.Collections; using Unity.Entities; using Unity.Mathematics; using Unity.Transforms; using static Reese.Demo.PathFlockingSettingsSystem; namespace Reese.Demo { public struct QuadrantData { public LocalToWorld LocalToWorld; public Entity Entity; } [UpdateInGroup(typeof(FixedStepSimulationSystemGroup))] [UpdateAfter(typeof(Path.PathDestinationSystem))] public partial class PathQuadrantSystem : SystemBase { public static NativeParallelMultiHashMap<int, QuadrantData> QuadrantHashMap; PathFlockingSettingsSystem flockingSettingsSystem => World.GetOrCreateSystem<PathFlockingSettingsSystem>(); protected override void OnCreate() => QuadrantHashMap = new NativeParallelMultiHashMap<int, QuadrantData>(0, Allocator.Persistent); protected override void OnDestroy() => QuadrantHashMap.Dispose(); protected override void OnUpdate() { QuadrantHashMap.Clear(); var flockingSettings = flockingSettingsSystem.FlockingSettings; var entityCount = GetEntityQuery(typeof(PathAgent)).CalculateEntityCount(); if (entityCount > QuadrantHashMap.Capacity) QuadrantHashMap.Capacity = entityCount; var parallelHashMap = QuadrantHashMap.AsParallelWriter(); Entities .WithAll<PathAgent>() .ForEach((Entity entity, in LocalToWorld localToWorld) => { parallelHashMap.Add( HashPosition(localToWorld.Position, flockingSettings), new QuadrantData { LocalToWorld = localToWorld } ); } ) .WithName("PathHashPositionJob") .ScheduleParallel(); } public static int HashPosition(float3 position, PathFlockingSettings flockingSettings) => (int)(math.floor(position.x / flockingSettings.QuadrantCellSize) + flockingSettings.QuadrantZMultiplier * math.floor(position.z / flockingSettings.QuadrantCellSize)); public static void SearchQuadrantNeighbors( in NativeParallelMultiHashMap<int, QuadrantData> quadrantHashMap, in int key, in Entity currentEntity, in PathFlocking flocking, in float3 pos, in PathFlockingSettings flockingSettings, ref int separationNeighbors, ref int alignmentNeighbors, ref int cohesionNeighbors, ref float3 cohesionPos, ref float3 alignmentVec, ref float3 separationVec, ref QuadrantData closestQuadrantData ) { var closestDistance = float.PositiveInfinity; // Current quadrant: SearchQuadrantNeighbor(quadrantHashMap, key, currentEntity, flocking, pos, ref separationNeighbors, ref alignmentNeighbors, ref cohesionNeighbors, ref cohesionPos, ref alignmentVec, ref separationVec, ref closestQuadrantData, ref closestDistance); // Adjacent quadrants: SearchQuadrantNeighbor(quadrantHashMap, key + 1, currentEntity, flocking, pos, ref separationNeighbors, ref alignmentNeighbors, ref cohesionNeighbors, ref cohesionPos, ref alignmentVec, ref separationVec, ref closestQuadrantData, ref closestDistance); SearchQuadrantNeighbor(quadrantHashMap, key - 1, currentEntity, flocking, pos, ref separationNeighbors, ref alignmentNeighbors, ref cohesionNeighbors, ref cohesionPos, ref alignmentVec, ref separationVec, ref closestQuadrantData, ref closestDistance); SearchQuadrantNeighbor(quadrantHashMap, key + flockingSettings.QuadrantZMultiplier, currentEntity, flocking, pos, ref separationNeighbors, ref alignmentNeighbors, ref cohesionNeighbors, ref cohesionPos, ref alignmentVec, ref separationVec, ref closestQuadrantData, ref closestDistance); SearchQuadrantNeighbor(quadrantHashMap, key - flockingSettings.QuadrantZMultiplier, currentEntity, flocking, pos, ref separationNeighbors, ref alignmentNeighbors, ref cohesionNeighbors, ref cohesionPos, ref alignmentVec, ref separationVec, ref closestQuadrantData, ref closestDistance); // Diagonal quadrants: SearchQuadrantNeighbor(quadrantHashMap, key + 1 + flockingSettings.QuadrantZMultiplier, currentEntity, flocking, pos, ref separationNeighbors, ref alignmentNeighbors, ref cohesionNeighbors, ref cohesionPos, ref alignmentVec, ref separationVec, ref closestQuadrantData, ref closestDistance); SearchQuadrantNeighbor(quadrantHashMap, key + 1 - flockingSettings.QuadrantZMultiplier, currentEntity, flocking, pos, ref separationNeighbors, ref alignmentNeighbors, ref cohesionNeighbors, ref cohesionPos, ref alignmentVec, ref separationVec, ref closestQuadrantData, ref closestDistance); SearchQuadrantNeighbor(quadrantHashMap, key - 1 + flockingSettings.QuadrantZMultiplier, currentEntity, flocking, pos, ref separationNeighbors, ref alignmentNeighbors, ref cohesionNeighbors, ref cohesionPos, ref alignmentVec, ref separationVec, ref closestQuadrantData, ref closestDistance); SearchQuadrantNeighbor(quadrantHashMap, key - 1 - flockingSettings.QuadrantZMultiplier, currentEntity, flocking, pos, ref separationNeighbors, ref alignmentNeighbors, ref cohesionNeighbors, ref cohesionPos, ref alignmentVec, ref separationVec, ref closestQuadrantData, ref closestDistance); } static void SearchQuadrantNeighbor( in NativeParallelMultiHashMap<int, QuadrantData> quadrantHashMap, in int key, in Entity entity, in PathFlocking flocking, in float3 pos, ref int separationNeighbors, ref int alignmentNeighbors, ref int cohesionNeighbors, ref float3 cohesionPos, ref float3 alignmentVec, ref float3 separationVec, ref QuadrantData closestQuadrantData, ref float closestDistance ) { if (!quadrantHashMap.TryGetFirstValue(key, out var quadrantData, out var iterator)) return; do { if (entity == quadrantData.Entity || quadrantData.LocalToWorld.Position.Equals(pos)) continue; var distance = math.distance(pos, quadrantData.LocalToWorld.Position); var nearest = distance < closestDistance; closestDistance = math.select(closestDistance, distance, nearest); if (nearest) closestQuadrantData = quadrantData; if (distance < flocking.SeparationPerceptionRadius) { ++separationNeighbors; separationVec += (pos - quadrantData.LocalToWorld.Position) / distance; } if (distance < flocking.AlignmentPerceptionRadius) { ++alignmentNeighbors; alignmentVec += quadrantData.LocalToWorld.Up; } if (distance < flocking.CohesionPerceptionRadius) { ++cohesionNeighbors; cohesionPos += quadrantData.LocalToWorld.Position; } } while (quadrantHashMap.TryGetNextValue(out quadrantData, ref iterator)); } } }
1
0.782687
1
0.782687
game-dev
MEDIA
0.472876
game-dev
0.846427
1
0.846427
BigfootACA/simple-init
3,809
src/lua/fdisk/fdisk_parttype.c
/* * * Copyright (C) 2021 BigfootACA <bigfoot@classfun.cn> * * SPDX-License-Identifier: LGPL-3.0-or-later * */ #include"fdisk.h" void lua_fdisk_parttype_to_lua( lua_State*L, bool allocated, struct fdisk_parttype*data ){ if(!data){ lua_pushnil(L); return; } if(!allocated)fdisk_ref_parttype(data); struct lua_fdisk_parttype*e; e=lua_newuserdata(L,sizeof(struct lua_fdisk_parttype)); luaL_getmetatable(L,LUA_FDISK_PARTTYPE); lua_setmetatable(L,-2); memset(e,0,sizeof(struct lua_fdisk_parttype)); e->data=data; } static int lua_fdisk_parttype_set_name(lua_State*L){ LUA_ARG_MAX(2); struct lua_fdisk_parttype*data=luaL_checkudata(L,1,LUA_FDISK_PARTTYPE); if(!data||!data->data)return luaL_argerror(L,1,"invalid part type"); fdisk_parttype_set_name(data->data,luaL_checkstring(L,2)); return 0; } static int lua_fdisk_parttype_set_typestr(lua_State*L){ LUA_ARG_MAX(2); struct lua_fdisk_parttype*data=luaL_checkudata(L,1,LUA_FDISK_PARTTYPE); if(!data||!data->data)return luaL_argerror(L,1,"invalid part type"); fdisk_parttype_set_typestr(data->data,luaL_checkstring(L,2)); return 0; } static int lua_fdisk_parttype_set_code(lua_State*L){ LUA_ARG_MAX(2); struct lua_fdisk_parttype*data=luaL_checkudata(L,1,LUA_FDISK_PARTTYPE); if(!data||!data->data)return luaL_argerror(L,1,"invalid part type"); fdisk_parttype_set_code(data->data,luaL_checkinteger(L,2)); return 0; } static int lua_fdisk_parttype_copy(lua_State*L){ LUA_ARG_MAX(1); struct lua_fdisk_parttype*data=luaL_checkudata(L,1,LUA_FDISK_PARTTYPE); if(!data||!data->data)return luaL_argerror(L,1,"invalid part type"); struct fdisk_parttype*parttype=fdisk_copy_parttype(data->data); if(!parttype)lua_pushnil(L); else lua_fdisk_parttype_to_lua(L,true,parttype); return 1; } static int lua_fdisk_parttype_get_string(lua_State*L){ LUA_ARG_MAX(1); struct lua_fdisk_parttype*data=luaL_checkudata(L,1,LUA_FDISK_PARTTYPE); if(!data||!data->data)return luaL_argerror(L,1,"invalid part type"); const char*string=fdisk_parttype_get_string(data->data); if(!string)lua_pushnil(L); else lua_pushstring(L,string); return 1; } static int lua_fdisk_parttype_get_code(lua_State*L){ LUA_ARG_MAX(1); struct lua_fdisk_parttype*data=luaL_checkudata(L,1,LUA_FDISK_PARTTYPE); if(!data||!data->data)return luaL_argerror(L,1,"invalid part type"); lua_pushinteger(L,fdisk_parttype_get_code(data->data)); return 1; } static int lua_fdisk_parttype_get_name(lua_State*L){ LUA_ARG_MAX(1); struct lua_fdisk_parttype*data=luaL_checkudata(L,1,LUA_FDISK_PARTTYPE); if(!data||!data->data)return luaL_argerror(L,1,"invalid part type"); const char*name=fdisk_parttype_get_name(data->data); if(!name)lua_pushnil(L); else lua_pushstring(L,name); return 1; } static int lua_fdisk_parttype_is_unknown(lua_State*L){ LUA_ARG_MAX(1); struct lua_fdisk_parttype*data=luaL_checkudata(L,1,LUA_FDISK_PARTTYPE); if(!data||!data->data)return luaL_argerror(L,1,"invalid part type"); lua_pushboolean(L,fdisk_parttype_is_unknown(data->data)); return 1; } static int lua_fdisk_parttype_gc(lua_State*L){ struct lua_fdisk_parttype*data=NULL; data=luaL_checkudata(L,1,LUA_FDISK_PARTTYPE); if(!data||!data->data)return 0; fdisk_unref_parttype(data->data); data->data=NULL; return 0; } struct lua_fdisk_meta_table lua_fdisk_parttype={ .name=LUA_FDISK_PARTTYPE, .reg=(luaL_Reg[]){ {"set_name", lua_fdisk_parttype_set_name}, {"set_typestr", lua_fdisk_parttype_set_typestr}, {"set_code", lua_fdisk_parttype_set_code}, {"copy", lua_fdisk_parttype_copy}, {"get_string", lua_fdisk_parttype_get_string}, {"get_code", lua_fdisk_parttype_get_code}, {"get_name", lua_fdisk_parttype_get_name}, {"is_unknown", lua_fdisk_parttype_is_unknown}, {NULL, NULL} }, .tostring=NULL, .gc=lua_fdisk_parttype_gc, };
1
0.846034
1
0.846034
game-dev
MEDIA
0.459768
game-dev
0.84499
1
0.84499
xerohour/windows_10_shared_source_kit
6,716
windows_10_shared_source_kit/windows_10_shared_source_kit/unknown_version/Source/Audio/Test/uaatest/SetupDi.cpp
/* * Copyright (c) Microsoft Corporation. All rights reserved. */ #include <windows.h> #include <setupapi.h> #include <newdev.h> #include <tchar.h> #include <shell98.h> #include <module98.h> #include <dvmodule.h> #include "log.h" #include "setupdi.h" BOOL FindIdMatch (LPCTSTR * Array, LPCTSTR Enumerator) /*++ Routine Description: Compares all strings in Array against Id Use WildCardMatch to do real compare Arguments: Array - pointer returned by GetDevMultiSz MatchEntry - string to compare against Return Value: TRUE if any match, otherwise FALSE --*/ { if(Array) { while(Array[0]) { if (_tcsnicmp (Array[0], Enumerator, lstrlen(Enumerator)) == 0) return TRUE; Array++; } } return FALSE; } LPCTSTR * GetMultiSzIndexArray(LPCTSTR MultiSz) /*++ Routine Description: Get an index array pointing to the MultiSz passed in Arguments: MultiSz - well formed multi-sz string Return Value: array of n strings array[0] points to original MultiSz array[n] == NULL returns NULL on failure --*/ { LPCTSTR scan; LPCTSTR * array; int elements; for(scan = MultiSz, elements = 0; scan[0] ;elements++) { scan += lstrlen(scan)+1; } array = new LPCTSTR[elements+1]; if(!array) { return NULL; } if(elements) { for(scan = MultiSz, elements = 0; scan[0]; elements++) { array[elements] = scan; scan += lstrlen(scan)+1; } } array[elements] = NULL; return array; } LPCTSTR * GetDevMultiSz(HDEVINFO Devs,PSP_DEVINFO_DATA DevInfo,DWORD Prop) /*++ Routine Description: Get a multi-sz device property and return as an array of strings Arguments: Devs - HDEVINFO containing DevInfo DevInfo - Specific device Prop - SPDRP_HARDWAREID or SPDRP_COMPATIBLEIDS Return Value: array of strings. last entry+1 of array contains NULL returns NULL on failure --*/ { LPTSTR buffer; DWORD size; DWORD reqSize; DWORD dataType; LPCTSTR * array; DWORD szChars; size = 8192; // initial guess, nothing magic about this buffer = new TCHAR[(size/sizeof(TCHAR))+2]; if(!buffer) { return NULL; } while(!SetupDiGetDeviceRegistryProperty(Devs,DevInfo,Prop,&dataType,(LPBYTE)buffer,size,&reqSize)) { if(GetLastError() != ERROR_INSUFFICIENT_BUFFER) { goto failed; } if(dataType != REG_MULTI_SZ) { goto failed; } size = reqSize; delete [] buffer; buffer = new TCHAR[(size/sizeof(TCHAR))+2]; if(!buffer) { goto failed; } } szChars = reqSize/sizeof(TCHAR); buffer[szChars] = TEXT('\0'); buffer[szChars+1] = TEXT('\0'); array = GetMultiSzIndexArray(buffer); if(array) { return array; } failed: if(buffer) { delete [] buffer; } return NULL; } void DelMultiSz(LPCTSTR *MultiSz) { // first delete the original buffer if (MultiSz) { delete [] MultiSz[0]; } // then delete the array of pointers delete [] MultiSz; } // // EnumerateDevices // // Flags: SetupDi flags // Class: class to enumerate, can be NULL // Enumerator: Full or partial PnP ID or device interface name // Partial: Specifies if the Enumerator is partial or full ID // Callback: Once something is found the callback is called // Context: callback context BOOL EnumerateDevices (DWORD Flags, LPCGUID Class, LPCTSTR Enumerator, CallbackFunc Callback, LPVOID Context) { HDEVINFO devs = INVALID_HANDLE_VALUE; SP_DEVINFO_LIST_DETAIL_DATA devInfoListDetail; SP_DEVINFO_DATA devInfo; // // add all id's to list // if there's a class, filter on specified class // devs = SetupDiGetClassDevs (Class, NULL, NULL, (Class ? 0 : DIGCF_ALLCLASSES) | Flags); if (devs == INVALID_HANDLE_VALUE) return FALSE; devInfoListDetail.cbSize = sizeof(devInfoListDetail); if(!SetupDiGetDeviceInfoListDetail (devs, &devInfoListDetail)) { SetupDiDestroyDeviceInfoList (devs); return FALSE; } devInfo.cbSize = sizeof(devInfo); for(int devIndex = 0; SetupDiEnumDeviceInfo (devs, devIndex, &devInfo); devIndex++) { LPCTSTR *hwIds = NULL; LPCTSTR *compatIds = NULL; // // determine hardware ID's // and search for matches // hwIds = GetDevMultiSz (devs, &devInfo, SPDRP_HARDWAREID); compatIds = GetDevMultiSz (devs, &devInfo, SPDRP_COMPATIBLEIDS); if (FindIdMatch (hwIds, Enumerator) || FindIdMatch (compatIds, Enumerator)) { Callback (devs, &devInfo, devIndex, Context); } DelMultiSz (hwIds); DelMultiSz (compatIds); } SetupDiDestroyDeviceInfoList (devs); return TRUE; } BOOL UpdateDevice (LPCTSTR InfFile, LPCTSTR PnpID, BOOL *Reboot) /*++ Routine Description: UPDATE update driver for existing device(s) Arguments: InfFile - INF file name with or without path PnpID - PnP ID of device to be updated Return Value: EXIT_xxxx --*/ { UpdateDriverForPlugAndPlayDevicesProto UpdateFn; TCHAR InfPath[MAX_PATH]; DWORD res, flags = INSTALLFLAG_FORCE; HMODULE newdevMod = NULL; // // Inf must be a full pathname // res = GetFullPathName (InfFile, MAX_PATH, InfPath, NULL); if ((res >= MAX_PATH) || (res == 0)) { SLOG(eError, "GetFullPathName returned unexpected value %u", res); return FALSE; } // // inf doesn't exist? // if (GetFileAttributes (InfPath) == (DWORD)(-1)) { SLOG(eError, "Could not find file %s", InfPath); return FALSE; } // // make use of UpdateDriverForPlugAndPlayDevices // newdevMod = LoadLibrary(TEXT("newdev.dll")); if(!newdevMod) { SLOG(eError, "LoadLibrary(newdev.dll) failed: GetLastError = %u", GetLastError()); return FALSE; } UpdateFn = (UpdateDriverForPlugAndPlayDevicesProto)GetProcAddress (newdevMod, UPDATEDRIVERFORPLUGANDPLAYDEVICES); if(!UpdateFn) { SLOG(eError, "GetProcAddress() failed: GetLastError = %u", GetLastError()); FreeLibrary(newdevMod); return FALSE; } if (!UpdateFn (NULL, PnpID, InfPath, flags, Reboot)) { SLOG(eError, "UpdateDriverForPlugAndPlayDevices failed: GetLastError() = %u", GetLastError()); FreeLibrary(newdevMod); return FALSE; } // allow the newly installed device time to initialize Sleep(10 * 1000); FreeLibrary(newdevMod); return TRUE; }
1
0.989663
1
0.989663
game-dev
MEDIA
0.348218
game-dev
0.988968
1
0.988968
fulpstation/fulpstation
6,965
code/modules/vehicles/mecha/working/clarke.dm
///Lavaproof, fireproof, fast mech with low armor and higher energy consumption and has an internal ore box. /obj/vehicle/sealed/mecha/clarke desc = "Combining man and machine for a better, stronger miner, Cannot strafe Can even resist lava!" name = "\improper Clarke" icon_state = "clarke" base_icon_state = "clarke" max_temperature = 65000 max_integrity = 250 movedelay = 1.25 overclock_coeff = 1.25 resistance_flags = LAVA_PROOF | FIRE_PROOF | ACID_PROOF lights_power = 7 step_energy_drain = 12 //slightly higher energy drain since you movin those wheels FAST armor_type = /datum/armor/mecha_clarke equip_by_category = list( MECHA_L_ARM = null, MECHA_R_ARM = null, MECHA_UTILITY = list(/obj/item/mecha_parts/mecha_equipment/orebox_manager, /obj/item/mecha_parts/mecha_equipment/sleeper/clarke), MECHA_POWER = list(), MECHA_ARMOR = list(), ) max_equip_by_category = list( MECHA_L_ARM = 1, MECHA_R_ARM = 1, MECHA_UTILITY = 6, MECHA_POWER = 1, MECHA_ARMOR = 1, ) wreckage = /obj/structure/mecha_wreckage/clarke mech_type = EXOSUIT_MODULE_CLARKE enter_delay = 40 mecha_flags = IS_ENCLOSED | HAS_LIGHTS | MMI_COMPATIBLE | OMNIDIRECTIONAL_ATTACKS accesses = list(ACCESS_MECH_ENGINE, ACCESS_MECH_SCIENCE, ACCESS_MECH_MINING) allow_diagonal_movement = FALSE pivot_step = TRUE /datum/armor/mecha_clarke melee = 40 bullet = 10 laser = 20 energy = 10 bomb = 60 fire = 100 acid = 100 /obj/vehicle/sealed/mecha/clarke/Initialize(mapload) . = ..() ore_box = new(src) /obj/vehicle/sealed/mecha/clarke/atom_destruction() if(ore_box) INVOKE_ASYNC(ore_box, TYPE_PROC_REF(/obj/structure/ore_box, dump_box_contents)) return ..() /obj/vehicle/sealed/mecha/clarke/generate_actions() . = ..() initialize_passenger_action_type(/datum/action/vehicle/sealed/mecha/mech_search_ruins) initialize_passenger_action_type(/datum/action/vehicle/sealed/mecha/clarke_scoop_body) //Ore Box Controls ///Special equipment for the Clarke mech, handles moving ore without giving the mech a hydraulic clamp and cargo compartment. /obj/item/mecha_parts/mecha_equipment/orebox_manager name = "ore storage module" desc = "An automated ore box management device, complete with a built-in boulder processor." icon_state = "mecha_bin" equipment_slot = MECHA_UTILITY detachable = FALSE /obj/item/mecha_parts/mecha_equipment/orebox_manager/attach(obj/vehicle/sealed/mecha/mecha, attach_right = FALSE) . = ..() ADD_TRAIT(chassis, TRAIT_OREBOX_FUNCTIONAL, TRAIT_MECH_EQUIPMENT(type)) /obj/item/mecha_parts/mecha_equipment/orebox_manager/detach(atom/moveto) REMOVE_TRAIT(chassis, TRAIT_OREBOX_FUNCTIONAL, TRAIT_MECH_EQUIPMENT(type)) return ..() /obj/item/mecha_parts/mecha_equipment/orebox_manager/get_snowflake_data() var/list/contents = chassis.ore_box?.contents var/list/contents_grouped = list() for(var/atom/movable/item as anything in contents) var/amount = 1 if(isstack(item)) var/obj/item/stack/stack = item amount = stack.amount if(isnull(contents_grouped[item.icon_state])) var/ore_data = list() ore_data["name"] = item.name ore_data["icon"] = item.icon_state ore_data["amount"] = amount contents_grouped[item.icon_state] = ore_data else contents_grouped[item.icon_state]["amount"] += amount var/list/data = list( "snowflake_id" = MECHA_SNOWFLAKE_ID_OREBOX_MANAGER, "contents" = contents_grouped, ) return data /obj/item/mecha_parts/mecha_equipment/orebox_manager/ui_act(action, list/params, datum/tgui/ui, datum/ui_state/state) . = ..() if(.) return TRUE if(action == "dump") var/obj/structure/ore_box/cached_ore_box = chassis.ore_box if(isnull(cached_ore_box)) return FALSE cached_ore_box.dump_box_contents() playsound(chassis, 'sound/items/weapons/tap.ogg', 50, TRUE) log_message("Dumped [cached_ore_box].", LOG_MECHA) return TRUE /obj/item/mecha_parts/mecha_equipment/sleeper/clarke //The Clarke subtype of the sleeper is a built-in utility module equipment_slot = MECHA_UTILITY detachable = FALSE /datum/action/vehicle/sealed/mecha/clarke_scoop_body name = "Pick up body" desc = "Activate to pick up a nearby body" button_icon = 'icons/obj/devices/mecha_equipment.dmi' button_icon_state = "mecha_sleeper_miner" /datum/action/vehicle/sealed/mecha/clarke_scoop_body/Trigger(trigger_flags) if(!..()) return var/obj/item/mecha_parts/mecha_equipment/sleeper/clarke/sleeper = locate() in chassis var/mob/living/carbon/human/human_target for(var/mob/living/carbon/human/body in range(1, chassis)) if(chassis.is_driver(body) || !ishuman(body) || !chassis.Adjacent(body)) continue human_target = body //Non-driver, human, and adjacent break sleeper.action(pick(chassis.return_drivers()), human_target) //This will probably break if anyone allows multiple drivers of the Clarke mech #define SEARCH_COOLDOWN (1 MINUTES) /datum/action/vehicle/sealed/mecha/mech_search_ruins name = "Search for Ruins" button_icon_state = "mech_search_ruins" COOLDOWN_DECLARE(search_cooldown) /datum/action/vehicle/sealed/mecha/mech_search_ruins/Trigger(trigger_flags) if(!..()) return if(!chassis || !(owner in chassis.occupants)) return if(!COOLDOWN_FINISHED(src, search_cooldown)) chassis.balloon_alert(owner, "on cooldown!") return if(!isliving(owner)) return var/mob/living/living_owner = owner button_icon_state = "mech_search_ruins_cooldown" build_all_button_icons() COOLDOWN_START(src, search_cooldown, SEARCH_COOLDOWN) addtimer(VARSET_CALLBACK(src, button_icon_state, "mech_search_ruins"), SEARCH_COOLDOWN) addtimer(CALLBACK(src, PROC_REF(build_all_button_icons)), SEARCH_COOLDOWN) var/obj/pinpointed_ruin for(var/obj/effect/landmark/ruin/ruin_landmark as anything in GLOB.ruin_landmarks) if(ruin_landmark.z != chassis.z) continue if(!pinpointed_ruin || get_dist(ruin_landmark, chassis) < get_dist(pinpointed_ruin, chassis)) pinpointed_ruin = ruin_landmark if(!pinpointed_ruin) chassis.balloon_alert(living_owner, "no ruins!") return var/datum/status_effect/agent_pinpointer/ruin_pinpointer = living_owner.apply_status_effect(/datum/status_effect/agent_pinpointer/ruin) ruin_pinpointer.RegisterSignal(living_owner, COMSIG_MOVABLE_MOVED, TYPE_PROC_REF(/datum/status_effect/agent_pinpointer/ruin, cancel_self)) ruin_pinpointer.scan_target = pinpointed_ruin chassis.balloon_alert(living_owner, "pinpointing nearest ruin") /datum/status_effect/agent_pinpointer/ruin duration = SEARCH_COOLDOWN * 0.5 alert_type = /atom/movable/screen/alert/status_effect/agent_pinpointer/ruin tick_interval = 3 SECONDS range_fuzz_factor = 0 minimum_range = 5 range_mid = 20 range_far = 50 /datum/status_effect/agent_pinpointer/ruin/scan_for_target() return /datum/status_effect/agent_pinpointer/ruin/proc/cancel_self(datum/source, atom/old_loc) SIGNAL_HANDLER qdel(src) /atom/movable/screen/alert/status_effect/agent_pinpointer/ruin name = "Ruin Target" desc = "Searching for valuables..." #undef SEARCH_COOLDOWN
1
0.973422
1
0.973422
game-dev
MEDIA
0.98523
game-dev
0.987933
1
0.987933
NeotokyoRebuild/neo
4,808
src/game/shared/particle_property.h
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //============================================================================= #ifndef PARTICLEPROPERTY_H #define PARTICLEPROPERTY_H #ifdef _WIN32 #pragma once #endif #include "smartptr.h" #include "globalvars_base.h" #include "particles_new.h" #include "particle_parse.h" //----------------------------------------------------------------------------- // Forward declarations //----------------------------------------------------------------------------- class CBaseEntity; class CNewParticleEffect; // Argh: Server considers -1 to be an invalid attachment, whereas the client uses 0 #ifdef CLIENT_DLL #define INVALID_PARTICLE_ATTACHMENT 0 #else #define INVALID_PARTICLE_ATTACHMENT -1 #endif struct ParticleControlPoint_t { ParticleControlPoint_t() { iControlPoint = 0; iAttachType = PATTACH_ABSORIGIN_FOLLOW; iAttachmentPoint = 0; vecOriginOffset = vec3_origin; } int iControlPoint; ParticleAttachment_t iAttachType; int iAttachmentPoint; Vector vecOriginOffset; EHANDLE hEntity; }; struct ParticleEffectList_t { ParticleEffectList_t() { pParticleEffect = NULL; } CUtlVector<ParticleControlPoint_t> pControlPoints; CSmartPtr<CNewParticleEffect> pParticleEffect; }; extern int GetAttachTypeFromString( const char *pszString ); //----------------------------------------------------------------------------- // Encapsulates particle handling for an entity //----------------------------------------------------------------------------- class CParticleProperty { DECLARE_CLASS_NOBASE( CParticleProperty ); DECLARE_EMBEDDED_NETWORKVAR(); DECLARE_PREDICTABLE(); DECLARE_DATADESC(); public: CParticleProperty(); ~CParticleProperty(); void Init( CBaseEntity *pEntity ); CBaseEntity *GetOuter( void ) { return m_pOuter; } // Effect Creation CNewParticleEffect *Create( const char *pszParticleName, ParticleAttachment_t iAttachType, const char *pszAttachmentName ); CNewParticleEffect *Create( const char *pszParticleName, ParticleAttachment_t iAttachType, int iAttachmentPoint = INVALID_PARTICLE_ATTACHMENT, Vector vecOriginOffset = vec3_origin ); void AddControlPoint( CNewParticleEffect *pEffect, int iPoint, C_BaseEntity *pEntity, ParticleAttachment_t iAttachType, const char *pszAttachmentName = NULL, Vector vecOriginOffset = vec3_origin ); void AddControlPoint( int iEffectIndex, int iPoint, C_BaseEntity *pEntity, ParticleAttachment_t iAttachType, int iAttachmentPoint = INVALID_PARTICLE_ATTACHMENT, Vector vecOriginOffset = vec3_origin ); inline void SetControlPointParent( CNewParticleEffect *pEffect, int whichControlPoint, int parentIdx ); void SetControlPointParent( int iEffectIndex, int whichControlPoint, int parentIdx ); // Commands void StopEmission( CNewParticleEffect *pEffect = NULL, bool bWakeOnStop = false, bool bDestroyAsleepSystems = false ); void StopEmissionAndDestroyImmediately( CNewParticleEffect *pEffect = NULL ); // kill all particle systems involving a given entity for their control points void StopParticlesInvolving( CBaseEntity *pEntity ); void StopParticlesNamed( const char *pszEffectName, bool bForceRemoveInstantly = false, bool bInverse = false ); ///< kills all particles using the given definition name void StopParticlesWithNameAndAttachment( const char *pszEffectName, int iAttachmentPoint, bool bForceRemoveInstantly = false ); ///< kills all particles using the given definition name // Particle System hooks void OnParticleSystemUpdated( CNewParticleEffect *pEffect, float flTimeDelta ); void OnParticleSystemDeleted( CNewParticleEffect *pEffect ); #ifdef CLIENT_DLL void OwnerSetDormantTo( bool bDormant ); #endif // Used to replace a particle effect with a different one; attaches the control point updating to the new one void ReplaceParticleEffect( CNewParticleEffect *pOldEffect, CNewParticleEffect *pNewEffect ); // Debugging void DebugPrintEffects( void ); int FindEffect( const char *pEffectName, int nStart = 0 ); inline CNewParticleEffect *GetParticleEffectFromIdx( int idx ); private: int GetParticleAttachment( C_BaseEntity *pEntity, const char *pszAttachmentName, const char *pszParticleName ); int FindEffect( CNewParticleEffect *pEffect ); void UpdateParticleEffect( ParticleEffectList_t *pEffect, bool bInitializing = false, int iOnlyThisControlPoint = -1 ); void UpdateControlPoint( ParticleEffectList_t *pEffect, int iPoint, bool bInitializing ); private: CBaseEntity *m_pOuter; CUtlVector<ParticleEffectList_t> m_ParticleEffects; int m_iDormancyChangedAtFrame; friend class CBaseEntity; }; #include "particle_property_inlines.h" #endif // PARTICLEPROPERTY_H
1
0.898851
1
0.898851
game-dev
MEDIA
0.80764
game-dev
0.683981
1
0.683981
darklinkpower/PlayniteExtensionsCollection
28,432
source/Generic/SaveFileView/SaveFileView.cs
using Microsoft.Win32; using Playnite.SDK; using Playnite.SDK.Events; using Playnite.SDK.Models; using Playnite.SDK.Plugins; using PlayState.Enums; using SteamCommon; using PlayniteUtilitiesCommon; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Controls; using FlowHttp; using SaveFileView.Models; using Playnite.SDK.Data; using PluginsCommon; namespace SaveFileView { public class SaveFileView : GenericPlugin { private static readonly ILogger logger = LogManager.GetLogger(); private static Regex pcgwContentRegex = new Regex(@"{{Game data\/(config|saves)\|[^\|]+\|.*?(?=}}\n)", RegexOptions.None); private readonly List<string> pcgwRegistryVariables; private SaveFileViewSettingsViewModel settings { get; set; } public override Guid Id { get; } = Guid.Parse("f68f302b-9799-4b77-a982-4bfca97130e2"); public SaveFileView(IPlayniteAPI api) : base(api) { settings = new SaveFileViewSettingsViewModel(this); Properties = new GenericPluginProperties { HasSettings = true }; pcgwRegistryVariables = GetSkipList(); } private List<string> GetSkipList() { return new List<string> { @"{{p|hkcu}}", @"{{p|hklm}}", @"{{p|wow64}}" }; } private const string ubisoftInstallationDir = @"C:\Program Files (x86)\Ubisoft\Ubisoft Game Launcher"; public static string GetUbisoftInstallationDirectory() { using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Ubisoft\Launcher")) { return key?.GetValue("InstallDir")?.ToString() .Replace('/', '\\') .Replace("Ubisoft Game Launcher\\", "Ubisoft Game Launcher") ?? ubisoftInstallationDir; } } private Dictionary<string, string> GetReplacementDict() { return new Dictionary<string, string> { [@"{{p|uid}}"] = @"*", [@"{{p|steam}}"] = SteamClient.GetSteamInstallationDirectory(), [@"{{p|uplay}}"] = GetUbisoftInstallationDirectory(), [@"{{p|username}}"] = Environment.UserName, [@"{{p|userprofile}}"] = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), [@"{{p|userprofile\documents}}"] = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), [@"{{p|userprofile\appdata\locallow}}"] = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).Replace("Roaming", "LocalLow"), [@"{{p|appdata}}"] = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), [@"{{p|localappdata}}"] = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), [@"{{p|public}}"] = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments)), [@"{{p|allusersprofile}}"] = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), [@"p{{p|programdata}}"] = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), [@"{{p|windir}}"] = Environment.GetFolderPath(Environment.SpecialFolder.System), [@"{{p|syswow64}}"] = Environment.GetFolderPath(Environment.SpecialFolder.SystemX86), [@"<code>"] = @"*" }; } public override IEnumerable<GameMenuItem> GetGameMenuItems(GetGameMenuItemsArgs args) { var menuSection = ResourceProvider.GetString("LOCSaveFileView_MenuSection"); return new List<GameMenuItem> { new GameMenuItem { Description = ResourceProvider.GetString("LOCSaveFileView_MenuItemOpenSaveDirectoriesDescription"), MenuSection = menuSection, Action = a => { OpenGamesDirectories(PathType.Save); } }, new GameMenuItem { Description = ResourceProvider.GetString("LOCSaveFileView_MenuItemOpenSaveConfigurationDescription"), MenuSection = menuSection, Action = a => { OpenGamesDirectories(PathType.Config); } }, new GameMenuItem { Description = ResourceProvider.GetString("LOCSaveFileView_MenuItemRefreshDirectoriesDescription"), MenuSection = menuSection, Action = a => { RefreshGamesDirectories(args.Games.Distinct()); } } }; } private void RefreshGamesDirectories(IEnumerable<Game> games) { var getDataSuccess = 0; var getDataFailed = 0; var progressTitle = ResourceProvider.GetString("LOCSaveFileView_DialogProgressDownloadingData"); var progressOptions = new GlobalProgressOptions(progressTitle, true); progressOptions.IsIndeterminate = false; PlayniteApi.Dialogs.ActivateGlobalProgress((a) => { a.ProgressMaxValue = games.Count(); foreach (var game in games) { if (a.CancelToken.IsCancellationRequested) { break; } a.CurrentProgressValue++; a.Text = $"{progressTitle}\n\n{a.CurrentProgressValue}/{a.ProgressMaxValue}\n{game.Name}"; var pathsStorePath = Path.Combine(GetPluginUserDataPath(), $"{game.Id}.json"); if (GetGameDirectories(game, pathsStorePath, true)) { getDataSuccess++; } else { getDataFailed++; } } }, progressOptions); PlayniteApi.Dialogs.ShowMessage( string.Format(ResourceProvider.GetString("LOCSaveFileView_RefreshResultsMessage"), getDataSuccess, getDataFailed), "Save File View"); } private void OpenGamesDirectories(PathType pathType) { var replacementDict = GetReplacementDict(); foreach (var game in PlayniteApi.MainView.SelectedGames.Distinct()) { if (!PlayniteUtilities.IsGamePcGame(game)) { continue; } var pathsStorePath = Path.Combine(GetPluginUserDataPath(), $"{game.Id}.json"); if (!FileSystem.FileExists(pathsStorePath)) { GetGameDirectories(game, pathsStorePath, true); if (!FileSystem.FileExists(pathsStorePath)) { PlayniteApi.Dialogs.ShowMessage(string.Format(ResourceProvider.GetString("LOCSaveFileView_CouldntGetGameDirectoriesMessage"), game.Name)); continue; } } var data = Serialization.FromJsonFile<GameDirectoriesData>(pathsStorePath); var dirDefinitions = GetAvailableDirsFromData(game, replacementDict, data, pathType); if (dirDefinitions.Count > 0) { foreach (var dir in dirDefinitions) { ProcessStarter.StartProcess(dir); } } else { PlayniteApi.Dialogs.ShowMessage( string.Format(ResourceProvider.GetString("LOCSaveFileView_DirectoriesNotDetectedMessage"), game.Name), "Save File View" ); } } } private List<string> GetAvailableDirsFromData(Game game, Dictionary<string, string> replacementDict, GameDirectoriesData data, PathType pathType) { var dirDefinitions = new List<string>(); var pathDefinitions = new List<string>(); foreach (var pathData in data.PathsData) { if (pathData.Type != pathType) { continue; } var path = pathData.Path; // Skip registry paths if (pcgwRegistryVariables.Any(x => path.Contains(x, StringComparison.OrdinalIgnoreCase))) { continue; } var pathDef = path; if (!game.InstallDirectory.IsNullOrEmpty()) { pathDef = path.Replace(@"{{p|game}}", game.InstallDirectory); } foreach (var kv in replacementDict) { pathDef = ReplaceCaseInsensitive(pathDef, kv.Key, kv.Value); } if (!pathDef.Contains("*")) { pathDefinitions.Add(pathDef); } else { foreach (var matchingPath in GetAllMatchingPaths(pathDef)) { if (matchingPath.IsNullOrEmpty()) { continue; } pathDefinitions.Add(matchingPath); } } } foreach (var path in pathDefinitions.Distinct()) { if (Directory.Exists(path)) { dirDefinitions.Add(path); } else if (File.Exists(path)) { dirDefinitions.Add(Path.GetDirectoryName(path)); } } return dirDefinitions; } private static string ReplaceCaseInsensitive(string input, string search, string replacement) { return Regex.Replace( input, Regex.Escape(search), replacement, RegexOptions.IgnoreCase ); } // Based on https://stackoverflow.com/a/36754982 public static IEnumerable<string> GetAllMatchingPaths(string pattern) { char separator = Path.DirectorySeparatorChar; string[] parts = pattern.Split(separator); if (parts[0].Contains('*') || parts[0].Contains('?')) { throw new ArgumentException("path root must not have a wildcard", nameof(parts)); } var startPattern = string.Join(separator.ToString(), parts.Skip(1)); return GetAllMatchingPathsInternal(startPattern, parts[0]); } private static IEnumerable<string> GetAllMatchingPathsInternal(string pattern, string root) { char separator = Path.DirectorySeparatorChar; string[] parts = pattern.Split(separator); for (int i = 0; i < parts.Length; i++) { // if this part of the path is a wildcard that needs expanding if (parts[i].Contains('*') || parts[i].Contains('?')) { // create an absolute path up to the current wildcard and check if it exists var combined = root + separator + string.Join(separator.ToString(), parts.Take(i)); if (!Directory.Exists(combined)) { return new string[0]; } if (i == parts.Length - 1) // if this is the end of the path (a file name) { return Directory.EnumerateFiles(combined, parts[i], SearchOption.TopDirectoryOnly).Concat( Directory.EnumerateDirectories(combined, parts[i], SearchOption.TopDirectoryOnly)); } else // if this is in the middle of the path (a directory name) { var directories = Directory.EnumerateDirectories(combined, parts[i], SearchOption.TopDirectoryOnly); return directories.SelectMany(dir => GetAllMatchingPathsInternal(string.Join(separator.ToString(), parts.Skip(i + 1)), dir)); } } } // if pattern ends in an absolute path with no wildcards in the filename var absolute = root + separator + string.Join(separator.ToString(), parts); if (File.Exists(absolute) || Directory.Exists(absolute)) { return new[] { absolute }; } return new string[0]; } private string GetPcgwPageId(Game game, string pathsStorePath, bool useCache, bool isBackgroundDownload = false) { if (useCache && FileSystem.FileExists(pathsStorePath)) { return Serialization.FromJsonFile<GameDirectoriesData>(pathsStorePath).PcgwPageId; } var uri = GetPcgwGameIdSearchUri(game); if (!uri.IsNullOrEmpty()) { var downloadStringResult = HttpRequestFactory.GetHttpRequest().WithUrl(uri).DownloadString(); if (downloadStringResult.IsSuccess) { var query = Serialization.FromJson<PcgwGameIdCargoQuery>(downloadStringResult.Content); return query.CargoQuery.FirstOrDefault()?.Title.PageId; } } return GetPcgwPageIdBySearch(game, isBackgroundDownload); } private bool GetGameDirectories(Game game, string pathsStorePath, bool useCacheId, bool isBackgroundDownload = false) { var pageId = GetPcgwPageId(game, pathsStorePath, useCacheId, isBackgroundDownload); if (pageId.IsNullOrEmpty()) { return false; } var apiUri = string.Format(@"https://www.pcgamingwiki.com/w/api.php?action=parse&format=json&pageid={0}&prop=wikitext", pageId); var downloadStringResult = HttpRequestFactory.GetHttpRequest().WithUrl(apiUri).DownloadString(); if (!downloadStringResult.IsSuccess) { return false; } var wikiTextQuery = Serialization.FromJson<PcgwWikiTextQuery>(downloadStringResult.Content); if (wikiTextQuery.Parse.Wikitext.TextDump.StartsWith("#REDIRECT [[")) { // Pages that redirect don't have any data so we have to obtain them // in another request. Example of this is "Horizon Zero Down Complete Edition" var titleMatch = Regex.Match(wikiTextQuery.Parse.Wikitext.TextDump, @"#REDIRECT \[\[([^\]]+)\]\]"); if (!titleMatch.Success) { return false; } var apiUri2 = string.Format(@"https://www.pcgamingwiki.com/w/api.php?action=cargoquery&tables=Infobox_game&fields=Infobox_game._pageID%3DPageID&where=Infobox_game._pageName%3D%22{0}%22&format=json", titleMatch.Groups[1].Value.UrlEncode()); var downloadStringResult2 = HttpRequestFactory.GetHttpRequest().WithUrl(apiUri2).DownloadString(); if (!downloadStringResult2.IsSuccess) { return false; } var query = Serialization.FromJson<PcgwGameIdCargoQuery>(downloadStringResult2.Content); pageId = query.CargoQuery.First().Title.PageId; var apiUri3 = string.Format(@"https://www.pcgamingwiki.com/w/api.php?action=parse&format=json&pageid={0}&prop=wikitext", pageId); var downloadStringResult3 = HttpRequestFactory.GetHttpRequest().WithUrl(apiUri3).DownloadString(); if (!downloadStringResult3.IsSuccess) { return false; } wikiTextQuery = Serialization.FromJson<PcgwWikiTextQuery>(downloadStringResult3.Content); if (wikiTextQuery.Parse.Wikitext.TextDump.StartsWith("#REDIRECT [[")) { return false; } } var gameLibraryPluginString = BuiltinExtensions.GetExtensionFromId(game.PluginId).ToString(); var configDirectories = GetPathsFromContent(wikiTextQuery.Parse.Wikitext.TextDump, PathType.Config, gameLibraryPluginString); var saveDirectories = GetPathsFromContent(wikiTextQuery.Parse.Wikitext.TextDump, PathType.Save, gameLibraryPluginString); var gameDirsData = new GameDirectoriesData { PcgwPageId = pageId, PathsData = configDirectories.Concat(saveDirectories).ToList() }; FileSystem.WriteStringToFile(pathsStorePath, Serialization.ToJson(gameDirsData)); AddPathsLinksToGame(game, gameDirsData); return true; } private const string linkSaveTemplate = @"[Save] "; private const string linkConfigTemplate = @"[Config] "; private void AddPathsLinksToGame(Game game, GameDirectoriesData gameDirsData) { var replacementDict = GetReplacementDict(); var linksToAdd = new Dictionary<string, string>(); var dirDefinitions = GetAvailableDirsFromData(game, replacementDict, gameDirsData, PathType.Config); if (settings.Settings.AddSaveDirsAsLinks) { foreach (var path in GetAvailableDirsFromData(game, replacementDict, gameDirsData, PathType.Save)) { linksToAdd[linkSaveTemplate + path] = @"file:///" + path; } } if (settings.Settings.AddConfigDirsAsLinks) { foreach (var path in GetAvailableDirsFromData(game, replacementDict, gameDirsData, PathType.Config)) { linksToAdd[linkConfigTemplate + path] = @"file:///" + path; } } var gameUpdated = false; if (game.Links == null) { game.Links = new System.Collections.ObjectModel.ObservableCollection<Link> { }; } var linksCopy = new System.Collections.ObjectModel.ObservableCollection<Link>(game.Links); foreach (var link in linksCopy.ToList()) { if (!link.Name.StartsWith(linkSaveTemplate) || !link.Name.StartsWith(linkConfigTemplate)) { continue; } if (!linksToAdd.Any(x => x.Value == link.Url)) { game.Links.Remove(link); gameUpdated = true; } } foreach (var linkKv in linksToAdd) { if (!linksCopy.Any(x => x.Url == linkKv.Value)) { linksCopy.Add(new Link { Name = linkKv.Key, Url = linkKv.Value }); gameUpdated = true; } } if (gameUpdated) { game.Links = linksCopy; PlayniteApi.Database.Games.Update(game); } } private const char bracketOpen = '{'; private const char bracketClose = '}'; private const char pathSeparator = '|'; private List<PathData> GetPathsFromContent(string apiDownloadedString, PathType pathType, string gameLibraryPluginString) { var pathMatches = pcgwContentRegex.Matches(apiDownloadedString); ; var paths = new List<PathData>(); if (pathMatches.Count == 0) { return paths; } foreach (Match match in pathMatches) { if (pathType == PathType.Config && !match.Value.StartsWith(@"{{Game data/config")) { continue; } else if (pathType == PathType.Save && !match.Value.StartsWith(@"{{Game data/saves")) { continue; } var sectionMatch = match.Value; var sectionVersion = Regex.Match(sectionMatch, @"^{{Game data\/[^\|]+\|([^\|]+)").Groups[1].Value.Trim(); ; // Paths that don't apply to the specific game version are skipped if (sectionVersion == "macOS" || sectionVersion == "OS X" || sectionVersion == "Linux") { continue; } else if (gameLibraryPluginString != "GogLibrary" && sectionVersion == "GOG.com") { continue; } else if (gameLibraryPluginString != "SteamLibrary" && sectionVersion == "Steam") { continue; } else if ((gameLibraryPluginString != "XboxLibrary") && sectionVersion == "Microsoft Store") { continue; } else if (gameLibraryPluginString != "UplayLibrary" && sectionVersion == "Uplay") { continue; } else if (gameLibraryPluginString != "EpicLibrary" && sectionVersion == "Epic Games Store") { continue; } // Remove section start e.g. "{{Game data/config|Windows|" sectionMatch = Regex.Replace(sectionMatch.Replace(@"\\", @"\"), @"^{{Game data\/[^\|]+\|[^\|]+\|", ""); // Make all code blocks uniform sectionMatch = Regex.Replace(sectionMatch, @"{{code\|[^}]+}}", "{{code}}"); // Remove all comments sectionMatch = Regex.Replace(sectionMatch, @"<!--[^-]+-->", ""); if (sectionMatch.IsNullOrEmpty()) { continue; } // Path sections separate different paths by the "|" character in a single // string so we need to separate them StringBuilder sb = new StringBuilder(); int bracketOpenCount = 0; int bracketClosedCount = 0; int index = 0; int stringLenght = sectionMatch.Length; foreach (char c in sectionMatch) { index++; // We verify if all variables are closed by comparing the number // of open and close bracket chars. If the amount is the same, // the '|' character is a separator for the next path if (c == pathSeparator && bracketOpenCount == bracketClosedCount) { bracketOpenCount = 0; bracketClosedCount = 0; paths.Add(new PathData { Path = sb.ToString().Trim(), Type = pathType } ); sb.Clear(); continue; } else if (c == bracketOpen) { bracketOpenCount++; } else if (c == bracketClose) { bracketClosedCount++; } if (index == stringLenght) { // We add the last character and create the string sb.Append(c); paths.Add(new PathData { Path = sb.ToString().Trim(), Type = pathType }); break; } sb.Append(c); } } return paths; } private string GetPcgwGameIdSearchUri(Game game, bool isBackgroundDownload = false) { var gameLibraryPlugin = BuiltinExtensions.GetExtensionFromId(game.PluginId); if (gameLibraryPlugin == BuiltinExtension.SteamLibrary) { return string.Format(@"https://www.pcgamingwiki.com/w/api.php?action=cargoquery&tables=Infobox_game&fields=Infobox_game._pageID%3DPageID&where=Infobox_game.Steam_AppID%20HOLDS%20%22{0}%22&format=json", game.GameId.UrlEncode()); } else if (gameLibraryPlugin == BuiltinExtension.GogLibrary) { return string.Format(@"https://www.pcgamingwiki.com/w/api.php?action=cargoquery&tables=Infobox_game&fields=Infobox_game._pageID%3DPageID&where=Infobox_game.GogCom_ID%20HOLDS%20%22{0}%22&format=json", game.GameId.UrlEncode()); } return null; } private const string pcgwTitleSearchQuery = @"https://www.pcgamingwiki.com/w/api.php?action=query&list=search&srlimit=10&srwhat=title&srsearch={0}&format=json"; private string GetPcgwPageIdBySearch(Game game, bool isBackgroundDownload) { var query = GetPcgwSearchQuery(game.Name); if (query == null) { return null; } var matchName = game.Name.Satinize(); foreach (var item in query.Query.Search) { if (item.Title.Satinize() == matchName) { return item.PageId.ToString(); } } if (isBackgroundDownload) { return null; } var selectedItem = PlayniteApi.Dialogs.ChooseItemWithSearch( new List<GenericItemOption>(), (a) => GetPcgwSearchOptions(a), game.Name, ResourceProvider.GetString("LOCSaveFileView_DialogTitleSelectPcgwGame")); if (selectedItem != null) { return selectedItem.Description; } return string.Empty; } private PcgwTitleSearch GetPcgwSearchQuery(string gameName) { var searchUri = string.Format(pcgwTitleSearchQuery, gameName.UrlEncode()); var downloadedString = HttpRequestFactory.GetHttpRequest().WithUrl(searchUri).DownloadString(); if (!downloadedString.IsSuccess) { return null; } return Serialization.FromJson<PcgwTitleSearch>(downloadedString.Content); } private List<GenericItemOption> GetPcgwSearchOptions(string gameName) { var itemOptions = new List<GenericItemOption>(); var query = GetPcgwSearchQuery(gameName); if (query == null) { return null; } foreach (var item in query.Query.Search) { itemOptions.Add(new GenericItemOption { Name = item.Title, Description = item.PageId.ToString() }); } return itemOptions; } public override void OnGameStopped(OnGameStoppedEventArgs args) { var game = args.Game; if (!PlayniteUtilities.IsGamePcGame(game)) { return; } var pathsStorePath = Path.Combine(GetPluginUserDataPath(), $"{game.Id}.json"); var refreshSuccess = GetGameDirectories(game, pathsStorePath, true, true); } public override void OnLibraryUpdated(OnLibraryUpdatedEventArgs args) { // Add code to be executed when library is updated. } public override ISettings GetSettings(bool firstRunSettings) { return settings; } public override UserControl GetSettingsView(bool firstRunSettings) { return new SaveFileViewSettingsView(); } } }
1
0.895303
1
0.895303
game-dev
MEDIA
0.550708
game-dev,desktop-app
0.934308
1
0.934308
The-Cataclysm-Preservation-Project/TrinityCore
125,807
src/server/game/Entities/Player/Player.h
/* * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _PLAYER_H #define _PLAYER_H #include "Unit.h" #include "CUFProfile.h" #include "DatabaseEnvFwd.h" #include "DBCEnums.h" #include "EquipmentSet.h" #include "GroupReference.h" #include "ItemDefines.h" #include "ItemEnchantmentMgr.h" #include "MapReference.h" #include "PetDefines.h" #include "PlayerTaxi.h" #include "QuestDef.h" struct AccessRequirement; struct AchievementEntry; struct AreaTableEntry; struct AreaTriggerEntry; struct ArchData; struct BarberShopStyleEntry; struct CharacterCustomizeInfo; struct CharTitlesEntry; struct ChatChannelsEntry; struct CreatureTemplate; struct CurrencyTypesEntry; struct FactionEntry; struct ItemExtendedCostEntry; struct ItemSetEffect; struct ItemTemplate; struct Loot; struct Mail; struct PlayerTalent; struct PlayerTalentInfo; struct ScalingStatDistributionEntry; struct ScalingStatValuesEntry; struct SkillRaceClassInfoEntry; struct TrainerSpell; struct VendorItem; struct GuildMemberProfessionData; template<class T> class AchievementMgr; class Archaeology; class Bag; class Battleground; class CinematicMgr; class Channel; class CharacterCreateInfo; class Creature; class DynamicObject; class GameClient; class Group; class Guild; class Item; class LootStore; class OutdoorPvP; class Pet; class PetAura; class PlayerAI; class PlayerMenu; class PlayerSocial; class ReputationMgr; class SpellCastTargets; class TradeData; enum InventoryType : uint8; enum ItemClass : uint8; enum LootError : uint8; enum LootType : uint8; enum UpdateCollisionHeightReason : uint8; enum ZLiquidStatus : uint32; typedef std::deque<Mail*> PlayerMails; constexpr uint8 PLAYER_MAX_SKILLS = 128; constexpr uint8 PLAYER_MAX_DAILY_QUESTS = 25; constexpr uint8 PLAYER_EXPLORED_ZONES_SIZE = 156; enum SpellModType : uint8 { SPELLMOD_FLAT = 0, // SPELL_AURA_ADD_FLAT_MODIFIER SPELLMOD_PCT = 1, // SPELL_AURA_ADD_PCT_MODIFIER SPELLMOD_END }; // 2^n values, Player::m_isunderwater is a bitmask. These are Trinity internal values, they are never send to any client enum PlayerUnderwaterState { UNDERWATER_NONE = 0x00, UNDERWATER_INWATER = 0x01, // terrain type is water and player is afflicted by it UNDERWATER_INLAVA = 0x02, // terrain type is lava and player is afflicted by it UNDERWATER_INSLIME = 0x04, // terrain type is lava and player is afflicted by it UNDERWATER_INDARKWATER = 0x08, // terrain type is dark water and player is afflicted by it UNDERWATER_EXIST_TIMERS = 0x10 }; enum BuyBankSlotResult { ERR_BANKSLOT_FAILED_TOO_MANY = 0, ERR_BANKSLOT_INSUFFICIENT_FUNDS = 1, ERR_BANKSLOT_NOTBANKER = 2, ERR_BANKSLOT_OK = 3 }; enum PlayerSpellState : uint8 { PLAYERSPELL_UNCHANGED = 0, PLAYERSPELL_CHANGED = 1, PLAYERSPELL_NEW = 2, PLAYERSPELL_REMOVED = 3, PLAYERSPELL_TEMPORARY = 4 }; struct PlayerSpell { PlayerSpellState state : 8; bool active : 1; // show in spellbook bool dependent : 1; // learned as result another spell learn, skill grow, quest reward, etc bool disabled : 1; // first rank has been learned in result talent learn but currently talent unlearned, save max learned ranks }; struct PlayerTalent { PlayerSpellState State; uint8 Spec; }; extern std::array<uint32, MAX_CLASSES> const MasterySpells; enum TalentTree // talent tabs { TALENT_TREE_WARRIOR_ARMS = 746, TALENT_TREE_WARRIOR_FURY = 815, TALENT_TREE_WARRIOR_PROTECTION = 845, TALENT_TREE_PALADIN_HOLY = 831, TALENT_TREE_PALADIN_PROTECTION = 839, TALENT_TREE_PALADIN_RETRIBUTION = 855, TALENT_TREE_HUNTER_BEAST_MASTERY = 811, TALENT_TREE_HUNTER_MARKSMANSHIP = 807, TALENT_TREE_HUNTER_SURVIVAL = 809, TALENT_TREE_ROGUE_ASSASSINATION = 182, TALENT_TREE_ROGUE_COMBAT = 181, TALENT_TREE_ROGUE_SUBTLETY = 183, TALENT_TREE_PRIEST_DISCIPLINE = 760, TALENT_TREE_PRIEST_HOLY = 813, TALENT_TREE_PRIEST_SHADOW = 795, TALENT_TREE_DEATH_KNIGHT_BLOOD = 398, TALENT_TREE_DEATH_KNIGHT_FROST = 399, TALENT_TREE_DEATH_KNIGHT_UNHOLY = 400, TALENT_TREE_SHAMAN_ELEMENTAL = 261, TALENT_TREE_SHAMAN_ENHANCEMENT = 263, TALENT_TREE_SHAMAN_RESTORATION = 262, TALENT_TREE_MAGE_ARCANE = 799, TALENT_TREE_MAGE_FIRE = 851, TALENT_TREE_MAGE_FROST = 823, TALENT_TREE_WARLOCK_AFFLICTION = 871, TALENT_TREE_WARLOCK_DEMONOLOGY = 867, TALENT_TREE_WARLOCK_DESTRUCTION = 865, TALENT_TREE_DRUID_BALANCE = 752, TALENT_TREE_DRUID_FERAL_COMBAT = 750, TALENT_TREE_DRUID_RESTORATION = 748 }; constexpr uint8 MAX_ARMOR_SPECIALIZATION_IDS = 7; constexpr std::array<uint32, MAX_ARMOR_SPECIALIZATION_IDS> ArmorSpecializationIds= { 86530, 86531, 86529, 86528, 86525, 86524, 86526 }; // Spell modifier (used for modify other spells) struct SpellModifier { SpellModifier(Aura* _ownerAura) : op(SpellModOp::HealingAndDamage), type(SPELLMOD_FLAT), spellId(0), ownerAura(_ownerAura) { } virtual ~SpellModifier() = default; SpellModOp op; SpellModType type; uint32 spellId; Aura* const ownerAura; }; struct SpellModifierByClassMask : SpellModifier { SpellModifierByClassMask(Aura* _ownerAura) : SpellModifier(_ownerAura), value(0), mask() { } int32 value; flag96 mask; }; struct SpellModifierCompare { bool operator()(SpellModifier const* left, SpellModifier const* right) const { // first sort by SpellModOp if (left->op != right->op) return left->op < right->op; // then by type (flat/pct) if (left->type != right->type) return left->type < right->type; return left < right; } }; enum PlayerCurrencyState { PLAYERCURRENCY_UNCHANGED = 0, PLAYERCURRENCY_CHANGED = 1, PLAYERCURRENCY_NEW = 2, PLAYERCURRENCY_REMOVED = 3 //not removed just set count == 0 }; struct PlayerCurrency { PlayerCurrency() : State(PLAYERCURRENCY_NEW), Quantity(0), WeeklyQuantity(0), TrackedQuantity(0), Flags(0) { } PlayerCurrencyState State; uint32 Quantity; uint32 WeeklyQuantity; uint32 TrackedQuantity; uint8 Flags; }; typedef std::unordered_map<uint32, PlayerTalent> PlayerTalentMap; typedef std::unordered_map<uint32, PlayerSpell> PlayerSpellMap; typedef Trinity::Containers::FlatSet<SpellModifier*, SpellModifierCompare> SpellModContainer; typedef std::unordered_map<uint32, PlayerCurrency> PlayerCurrenciesMap; typedef std::unordered_map<uint32 /*instanceId*/, time_t/*releaseTime*/> InstanceTimeMap; enum ActionButtonUpdateState { ACTIONBUTTON_UNCHANGED = 0, ACTIONBUTTON_CHANGED = 1, ACTIONBUTTON_NEW = 2, ACTIONBUTTON_DELETED = 3 }; enum ActionButtonType { ACTION_BUTTON_SPELL = 0x00, ACTION_BUTTON_C = 0x01, // click? ACTION_BUTTON_EQSET = 0x20, ACTION_BUTTON_DROPDOWN = 0x30, ACTION_BUTTON_MACRO = 0x40, ACTION_BUTTON_CMACRO = ACTION_BUTTON_C | ACTION_BUTTON_MACRO, ACTION_BUTTON_ITEM = 0x80 }; enum ReputationSource { REPUTATION_SOURCE_KILL, REPUTATION_SOURCE_QUEST, REPUTATION_SOURCE_DAILY_QUEST, REPUTATION_SOURCE_WEEKLY_QUEST, REPUTATION_SOURCE_MONTHLY_QUEST, REPUTATION_SOURCE_REPEATABLE_QUEST, REPUTATION_SOURCE_SPELL }; constexpr uint32 ACTION_BUTTON_ACTION(uint32 x) { return x & 0x00FFFFFF; } constexpr uint32 ACTION_BUTTON_TYPE(uint32 x) { return (x & 0xFF000000) >> 24; } constexpr uint32 MAX_ACTION_BUTTON_ACTION_VALUE = 0x00FFFFFF + 1; struct ActionButton { ActionButton() : packedData(0), uState(ACTIONBUTTON_NEW) { } uint32 packedData; ActionButtonUpdateState uState; // helpers ActionButtonType GetType() const { return ActionButtonType(ACTION_BUTTON_TYPE(packedData)); } uint32 GetAction() const { return ACTION_BUTTON_ACTION(packedData); } void SetActionAndType(uint32 action, ActionButtonType type) { uint32 newData = action | (uint32(type) << 24); if (newData != packedData || uState == ACTIONBUTTON_DELETED) { packedData = newData; if (uState != ACTIONBUTTON_NEW) uState = ACTIONBUTTON_CHANGED; } } }; constexpr uint8 MAX_ACTION_BUTTONS = 144; //checked in 3.2.0 typedef std::map<uint8, ActionButton> ActionButtonList; struct PvPInfo { PvPInfo() : IsHostile(false), IsInHostileArea(false), IsInNoPvPArea(false), IsInFFAPvPArea(false), EndTimer(0) { } bool IsHostile; bool IsInHostileArea; ///> Marks if player is in an area which forces PvP flag bool IsInNoPvPArea; ///> Marks if player is in a sanctuary or friendly capital city bool IsInFFAPvPArea; ///> Marks if player is in an FFAPvP area (such as Gurubashi Arena) time_t EndTimer; ///> Time when player unflags himself for PvP (flag removed after 5 minutes) }; struct DuelInfo { DuelInfo() : initiator(nullptr), opponent(nullptr), startTimer(0), startTime(0), outOfBound(0), isMounted(false), isCompleted(false) { } Player* initiator; Player* opponent; time_t startTimer; time_t startTime; time_t outOfBound; bool isMounted; bool isCompleted; }; struct Areas { uint32 areaID; uint32 areaFlag; float x1; float x2; float y1; float y2; }; constexpr uint8 MAX_RUNES = 6; constexpr float RUNE_BASE_COOLDOWN = 1.0f; enum class RuneType : uint8 { Blood = 0, Unholy = 1, Frost = 2, Death = 3, Max = 4 }; struct RuneInfo { RuneType BaseRune; RuneType CurrentRune; float Cooldown; AuraEffect const* ConvertAura; AuraType ConvertAuraType; SpellInfo const* ConvertAuraInfo; }; struct Runes { RuneInfo _Runes[MAX_RUNES]; uint8 RuneState; // mask of available runes RuneType LastUsedRune; uint8 LastUsedRuneMask; void SetRuneState(uint8 index, bool set = true); }; struct EnchantDuration { EnchantDuration() : item(nullptr), slot(MAX_ENCHANTMENT_SLOT), leftduration(0) { } EnchantDuration(Item* _item, EnchantmentSlot _slot, uint32 _leftduration) : item(_item), slot(_slot), leftduration(_leftduration){ ASSERT(item); } Item* item; EnchantmentSlot slot; uint32 leftduration; }; typedef std::list<EnchantDuration> EnchantDurationList; typedef std::list<Item*> ItemDurationList; enum DrunkenState { DRUNKEN_SOBER = 0, DRUNKEN_TIPSY = 1, DRUNKEN_DRUNK = 2, DRUNKEN_SMASHED = 3 }; constexpr uint8 MAX_DRUNKEN = 4; enum PlayerFlags { PLAYER_FLAGS_GROUP_LEADER = 0x00000001, PLAYER_FLAGS_AFK = 0x00000002, PLAYER_FLAGS_DND = 0x00000004, PLAYER_FLAGS_GM = 0x00000008, PLAYER_FLAGS_GHOST = 0x00000010, PLAYER_FLAGS_RESTING = 0x00000020, PLAYER_FLAGS_VOICE_CHAT = 0x00000040, PLAYER_FLAGS_UNK7 = 0x00000080, // pre-3.0.3 PLAYER_FLAGS_FFA_PVP flag for FFA PVP state PLAYER_FLAGS_CONTESTED_PVP = 0x00000100, // Player has been involved in a PvP combat and will be attacked by contested guards PLAYER_FLAGS_IN_PVP = 0x00000200, PLAYER_FLAGS_HIDE_HELM = 0x00000400, PLAYER_FLAGS_HIDE_CLOAK = 0x00000800, PLAYER_FLAGS_PLAYED_LONG_TIME = 0x00001000, // played long time PLAYER_FLAGS_PLAYED_TOO_LONG = 0x00002000, // played too long time PLAYER_FLAGS_IS_OUT_OF_BOUNDS = 0x00004000, PLAYER_FLAGS_DEVELOPER = 0x00008000, // <Dev> prefix for something? PLAYER_FLAGS_LOW_LEVEL_RAID_ENABLED = 0x00010000, // pre-3.0.3 PLAYER_FLAGS_SANCTUARY flag for player entered sanctuary PLAYER_FLAGS_TAXI_BENCHMARK = 0x00020000, // taxi benchmark mode (on/off) (2.0.1) PLAYER_FLAGS_PVP_TIMER = 0x00040000, // 3.0.2, pvp timer active (after you disable pvp manually) PLAYER_FLAGS_UBER = 0x00080000, PLAYER_FLAGS_UNK20 = 0x00100000, PLAYER_FLAGS_UNK21 = 0x00200000, PLAYER_FLAGS_COMMENTATOR2 = 0x00400000, PLAYER_FLAGS_DISABLE_CASTING_EXCEPT_ABILITIES = 0x00800000, // disables casting any ability except for the ones specified in the aura effect's SpellClassMask PLAYER_FLAGS_DISABLE_ATTACKING_EXCEPT_ABILITIES = 0x01000000, // disables all attacks including ability casts except for the ones specified in the aura effect's SpellClassMask PLAYER_FLAGS_NO_XP_GAIN = 0x02000000, PLAYER_FLAGS_UNK26 = 0x04000000, PLAYER_FLAGS_AUTO_DECLINE_GUILD = 0x08000000, // Automatically declines guild invites PLAYER_FLAGS_GUILD_LEVEL_ENABLED = 0x10000000, // Lua_GetGuildLevelEnabled() - enables guild leveling related UI PLAYER_FLAGS_VOID_UNLOCKED = 0x20000000, // void storage PLAYER_FLAGS_TIMEWALKING = 0x40000000, PLAYER_FLAGS_COMMENTATOR_CAMERA = 0x80000000 }; enum PlayerBytesOffsets { PLAYER_BYTES_OFFSET_SKIN_ID = 0, PLAYER_BYTES_OFFSET_FACE_ID = 1, PLAYER_BYTES_OFFSET_HAIR_STYLE_ID = 2, PLAYER_BYTES_OFFSET_HAIR_COLOR_ID = 3 }; enum PlayerBytes2Offsets { PLAYER_BYTES_2_OFFSET_FACIAL_STYLE = 0, PLAYER_BYTES_2_OFFSET_PARTY_TYPE = 1, PLAYER_BYTES_2_OFFSET_BANK_BAG_SLOTS = 2, PLAYER_BYTES_2_OFFSET_REST_STATE = 3 }; enum PlayerBytes3Offsets { PLAYER_BYTES_3_OFFSET_GENDER = 0, PLAYER_BYTES_3_OFFSET_INEBRIATION = 1, PLAYER_BYTES_3_OFFSET_PVP_TITLE = 2, PLAYER_BYTES_3_OFFSET_ARENA_FACTION = 3 }; enum PlayerFieldBytesOffsets { PLAYER_FIELD_BYTES_OFFSET_FLAGS = 0, PLAYER_FIELD_BYTES_OFFSET_RAF_GRANTABLE_LEVEL = 1, PLAYER_FIELD_BYTES_OFFSET_ACTION_BAR_TOGGLES = 2, PLAYER_FIELD_BYTES_OFFSET_LIFETIME_MAX_PVP_RANK = 3 }; enum PlayerFieldBytes2Offsets { PLAYER_FIELD_BYTES_2_OFFSET_OVERRIDE_SPELLS_ID = 0, // uint16! PLAYER_FIELD_BYTES_2_OFFSET_IGNORE_POWER_REGEN_PREDICTION_MASK = 2, PLAYER_FIELD_BYTES_2_OFFSET_AURA_VISION = 3 }; static_assert((PLAYER_FIELD_BYTES_2_OFFSET_OVERRIDE_SPELLS_ID & 1) == 0, "PLAYER_FIELD_BYTES_2_OFFSET_OVERRIDE_SPELLS_ID must be aligned to 2 byte boundary"); constexpr uint8 PLAYER_BYTES_2_OVERRIDE_SPELLS_UINT16_OFFSET = PLAYER_FIELD_BYTES_2_OFFSET_OVERRIDE_SPELLS_ID / 2; constexpr uint8 KNOWN_TITLES_SIZE = 4; constexpr uint32 MAX_TITLE_INDEX = KNOWN_TITLES_SIZE * sizeof(uint64); // 4 uint64 fields // used in PLAYER_FIELD_BYTES values enum PlayerFieldByteFlags { PLAYER_FIELD_BYTE_TRACK_STEALTHED = 0x00000002, PLAYER_FIELD_BYTE_RELEASE_TIMER = 0x00000008, // Display time till auto release spirit PLAYER_FIELD_BYTE_NO_RELEASE_WINDOW = 0x00000010 // Display no "release spirit" window at all }; // used in PLAYER_FIELD_BYTES2 values enum PlayerFieldByte2Flags { PLAYER_FIELD_BYTE2_NONE = 0x00, PLAYER_FIELD_BYTE2_STEALTH = 0x20, PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW = 0x40 }; enum MirrorTimerType { FATIGUE_TIMER = 0, BREATH_TIMER = 1, FIRE_TIMER = 2 // feign death }; constexpr uint8 MAX_TIMERS = 3; constexpr int32 DISABLED_MIRROR_TIMER = -1; // 2^n values enum PlayerExtraFlags { // gm abilities PLAYER_EXTRA_GM_ON = 0x0001, PLAYER_EXTRA_ACCEPT_WHISPERS = 0x0004, PLAYER_EXTRA_TAXICHEAT = 0x0008, PLAYER_EXTRA_GM_INVISIBLE = 0x0010, PLAYER_EXTRA_GM_CHAT = 0x0020, // Show GM badge in chat messages // other states PLAYER_EXTRA_PVP_DEATH = 0x0100 // store PvP death status until corpse creating. }; // 2^n values enum AtLoginFlags { AT_LOGIN_NONE = 0x000, AT_LOGIN_RENAME = 0x001, AT_LOGIN_RESET_SPELLS = 0x002, AT_LOGIN_RESET_TALENTS = 0x004, AT_LOGIN_CUSTOMIZE = 0x008, AT_LOGIN_RESET_PET_TALENTS = 0x010, AT_LOGIN_FIRST = 0x020, AT_LOGIN_CHANGE_FACTION = 0x040, AT_LOGIN_CHANGE_RACE = 0x080, AT_LOGIN_RESURRECT = 0x100 }; typedef std::map<uint32, QuestStatusData> QuestStatusMap; typedef std::set<uint32> RewardedQuestSet; enum QuestSaveType { QUEST_DEFAULT_SAVE_TYPE = 0, QUEST_DELETE_SAVE_TYPE, QUEST_FORCE_DELETE_SAVE_TYPE }; // quest typedef std::map<uint32, QuestSaveType> QuestStatusSaveMap; enum QuestSlotOffsets { QUEST_ID_OFFSET = 0, QUEST_STATE_OFFSET = 1, QUEST_COUNTS_OFFSET = 2, QUEST_TIME_OFFSET = 4 }; constexpr uint8 MAX_QUEST_OFFSET = 5; enum QuestSlotStateMask { QUEST_STATE_NONE = 0x0000, QUEST_STATE_COMPLETE = 0x0001, QUEST_STATE_FAIL = 0x0002 }; enum SkillUpdateState { SKILL_UNCHANGED = 0, SKILL_CHANGED = 1, SKILL_NEW = 2, SKILL_DELETED = 3 }; struct SkillStatusData { SkillStatusData(uint8 _pos, SkillUpdateState _uState) : pos(_pos), uState(_uState) { } uint8 pos; SkillUpdateState uState; }; typedef std::unordered_map<uint32, SkillStatusData> SkillStatusMap; class Quest; class Spell; class Item; class WorldSession; enum PlayerSlots { // first slot for item stored (in any way in player m_items data) PLAYER_SLOT_START = 0, // last+1 slot for item stored (in any way in player m_items data) PLAYER_SLOT_END = 86, PLAYER_SLOTS_COUNT = (PLAYER_SLOT_END - PLAYER_SLOT_START) }; constexpr uint8 INVENTORY_SLOT_BAG_0 = 255; enum EquipmentSlots : uint8 // 19 slots { EQUIPMENT_SLOT_START = 0, EQUIPMENT_SLOT_HEAD = 0, EQUIPMENT_SLOT_NECK = 1, EQUIPMENT_SLOT_SHOULDERS = 2, EQUIPMENT_SLOT_BODY = 3, EQUIPMENT_SLOT_CHEST = 4, EQUIPMENT_SLOT_WAIST = 5, EQUIPMENT_SLOT_LEGS = 6, EQUIPMENT_SLOT_FEET = 7, EQUIPMENT_SLOT_WRISTS = 8, EQUIPMENT_SLOT_HANDS = 9, EQUIPMENT_SLOT_FINGER1 = 10, EQUIPMENT_SLOT_FINGER2 = 11, EQUIPMENT_SLOT_TRINKET1 = 12, EQUIPMENT_SLOT_TRINKET2 = 13, EQUIPMENT_SLOT_BACK = 14, EQUIPMENT_SLOT_MAINHAND = 15, EQUIPMENT_SLOT_OFFHAND = 16, EQUIPMENT_SLOT_RANGED = 17, EQUIPMENT_SLOT_TABARD = 18, EQUIPMENT_SLOT_END = 19 }; enum InventorySlots : uint8 // 4 slots { INVENTORY_SLOT_BAG_START = 19, INVENTORY_SLOT_BAG_END = 23 }; enum InventoryPackSlots : uint8 // 16 slots { INVENTORY_SLOT_ITEM_START = 23, INVENTORY_SLOT_ITEM_END = 39 }; enum BankItemSlots // 28 slots { BANK_SLOT_ITEM_START = 39, BANK_SLOT_ITEM_END = 67 }; enum BankBagSlots // 7 slots { BANK_SLOT_BAG_START = 67, BANK_SLOT_BAG_END = 74 }; enum BuyBackSlots // 12 slots { // stored in m_buybackitems BUYBACK_SLOT_START = 74, BUYBACK_SLOT_END = 86 }; struct ItemPosCount { ItemPosCount(uint16 _pos, uint32 _count) : pos(_pos), count(_count) { } bool isContainedIn(std::vector<ItemPosCount> const& vec) const; uint16 pos; uint32 count; }; typedef std::vector<ItemPosCount> ItemPosCountVec; constexpr uint32 JUSTICE_POINTS_CONVERSION_MONEY = 4750; enum TransferAbortReason { TRANSFER_ABORT_NONE = 0x00, TRANSFER_ABORT_ERROR = 0x01, TRANSFER_ABORT_MAX_PLAYERS = 0x02, // Transfer Aborted: instance is full TRANSFER_ABORT_NOT_FOUND = 0x03, // Transfer Aborted: instance not found TRANSFER_ABORT_TOO_MANY_INSTANCES = 0x04, // You have entered too many instances recently. TRANSFER_ABORT_ZONE_IN_COMBAT = 0x06, // Unable to zone in while an encounter is in progress. TRANSFER_ABORT_INSUF_EXPAN_LVL = 0x07, // You must have <TBC, WotLK> expansion installed to access this area. TRANSFER_ABORT_DIFFICULTY = 0x08, // <Normal, Heroic, Epic> difficulty mode is not available for %s. TRANSFER_ABORT_UNIQUE_MESSAGE = 0x09, // Until you've escaped TLK's grasp, you cannot leave this place! TRANSFER_ABORT_TOO_MANY_REALM_INSTANCES = 0x0A, // Additional instances cannot be launched, please try again later. TRANSFER_ABORT_NEED_GROUP = 0x0B, // 3.1 TRANSFER_ABORT_NOT_FOUND1 = 0x0C, // 3.1 TRANSFER_ABORT_NOT_FOUND2 = 0x0D, // 3.1 TRANSFER_ABORT_NOT_FOUND3 = 0x0E, // 3.2 TRANSFER_ABORT_REALM_ONLY = 0x0F, // All players on party must be from the same realm. TRANSFER_ABORT_MAP_NOT_ALLOWED = 0x10, // Map can't be entered at this time. TRANSFER_ABORT_LOCKED_TO_DIFFERENT_INSTANCE = 0x12, // 4.2.2 TRANSFER_ABORT_ALREADY_COMPLETED_ENCOUNTER = 0x13 // 4.2.2 }; enum class TransferAbortedUniqueMessageArgs : uint8 { None = 0, StillWithinTheLichKingsGrasp = 1, DestinyOfTheBilgewaterCartelStillUndecided = 2, FateOfGilneasHasNotBeenDecidedYet = 3 }; enum InstanceResetWarningType { RAID_INSTANCE_WARNING_HOURS = 1, // WARNING! %s is scheduled to reset in %d hour(s). RAID_INSTANCE_WARNING_MIN = 2, // WARNING! %s is scheduled to reset in %d minute(s)! RAID_INSTANCE_WARNING_MIN_SOON = 3, // WARNING! %s is scheduled to reset in %d minute(s). Please exit the zone or you will be returned to your bind location! RAID_INSTANCE_WELCOME = 4, // Welcome to %s. This raid instance is scheduled to reset in %s. RAID_INSTANCE_EXPIRED = 5 }; // PLAYER_FIELD_ARENA_TEAM_INFO_1_1 offsets enum ArenaTeamInfoType { ARENA_TEAM_ID = 0, ARENA_TEAM_TYPE = 1, // new in 3.2 - team type? ARENA_TEAM_MEMBER = 2, // 0 - captain, 1 - member ARENA_TEAM_GAMES_WEEK = 3, ARENA_TEAM_GAMES_SEASON = 4, ARENA_TEAM_WINS_SEASON = 5, ARENA_TEAM_PERSONAL_RATING = 6, ARENA_TEAM_END = 7 }; class InstanceSave; enum RestFlag { REST_FLAG_IN_TAVERN = 0x1, REST_FLAG_IN_CITY = 0x2, REST_FLAG_IN_FACTION_AREA = 0x4 }; enum TeleportToOptions { TELE_TO_NONE = 0x00, TELE_TO_GM_MODE = 0x01, TELE_TO_NOT_LEAVE_TRANSPORT = 0x02, TELE_TO_NOT_LEAVE_COMBAT = 0x04, TELE_TO_NOT_UNSUMMON_PET = 0x08, TELE_TO_SPELL = 0x10 }; DEFINE_ENUM_FLAG(TeleportToOptions); /// Type of environmental damages enum EnviromentalDamage { DAMAGE_EXHAUSTED = 0, DAMAGE_DROWNING = 1, DAMAGE_FALL = 2, DAMAGE_LAVA = 3, DAMAGE_SLIME = 4, DAMAGE_FIRE = 5, DAMAGE_FALL_TO_VOID = 6 // custom case for fall without durability loss }; enum PlayerChatTag { CHAT_TAG_NONE = 0x00, CHAT_TAG_AFK = 0x01, CHAT_TAG_DND = 0x02, CHAT_TAG_GM = 0x04, CHAT_TAG_COM = 0x08, // Commentator CHAT_TAG_DEV = 0x10, CHAT_TAG_BOSS_SOUND = 0x20, // Plays "RaidBossEmoteWarning" sound on raid boss emote/whisper CHAT_TAG_MOBILE = 0x40 }; enum PlayedTimeIndex { PLAYED_TIME_TOTAL = 0, PLAYED_TIME_LEVEL = 1 }; constexpr uint8 MAX_PLAYED_TIME_INDEX = 2; // used at player loading query list preparing, and later result selection enum PlayerLoginQueryIndex { PLAYER_LOGIN_QUERY_LOAD_FROM = 0, PLAYER_LOGIN_QUERY_LOAD_GROUP = 1, PLAYER_LOGIN_QUERY_LOAD_BOUND_INSTANCES = 2, PLAYER_LOGIN_QUERY_LOAD_AURAS = 3, PLAYER_LOGIN_QUERY_LOAD_SPELLS = 4, PLAYER_LOGIN_QUERY_LOAD_QUEST_STATUS = 5, PLAYER_LOGIN_QUERY_LOAD_DAILY_QUEST_STATUS = 6, PLAYER_LOGIN_QUERY_LOAD_REPUTATION = 7, PLAYER_LOGIN_QUERY_LOAD_INVENTORY = 8, PLAYER_LOGIN_QUERY_LOAD_ACTIONS = 9, PLAYER_LOGIN_QUERY_LOAD_MAILS = 10, PLAYER_LOGIN_QUERY_LOAD_MAIL_ITEMS = 11, PLAYER_LOGIN_QUERY_LOAD_SOCIAL_LIST = 12, PLAYER_LOGIN_QUERY_LOAD_HOME_BIND = 13, PLAYER_LOGIN_QUERY_LOAD_SPELL_COOLDOWNS = 14, PLAYER_LOGIN_QUERY_LOAD_DECLINED_NAMES = 15, PLAYER_LOGIN_QUERY_LOAD_GUILD = 16, PLAYER_LOGIN_QUERY_LOAD_ARENA_INFO = 17, PLAYER_LOGIN_QUERY_LOAD_ACHIEVEMENTS = 18, PLAYER_LOGIN_QUERY_LOAD_CRITERIA_PROGRESS = 19, PLAYER_LOGIN_QUERY_LOAD_EQUIPMENT_SETS = 20, PLAYER_LOGIN_QUERY_LOAD_BG_DATA = 21, PLAYER_LOGIN_QUERY_LOAD_GLYPHS = 22, PLAYER_LOGIN_QUERY_LOAD_TALENTS = 23, PLAYER_LOGIN_QUERY_LOAD_ACCOUNT_DATA = 24, PLAYER_LOGIN_QUERY_LOAD_SKILLS = 25, PLAYER_LOGIN_QUERY_LOAD_WEEKLY_QUEST_STATUS = 26, PLAYER_LOGIN_QUERY_LOAD_RANDOM_BG = 27, PLAYER_LOGIN_QUERY_LOAD_BANNED = 28, PLAYER_LOGIN_QUERY_LOAD_QUEST_STATUS_REW = 29, PLAYER_LOGIN_QUERY_LOAD_INSTANCE_LOCK_TIMES = 30, PLAYER_LOGIN_QUERY_LOAD_SEASONAL_QUEST_STATUS = 31, PLAYER_LOGIN_QUERY_LOAD_MONTHLY_QUEST_STATUS = 32, PLAYER_LOGIN_QUERY_LOAD_VOID_STORAGE = 33, PLAYER_LOGIN_QUERY_LOAD_CURRENCY = 34, PLAYER_LOGIN_QUERY_LOAD_CUF_PROFILES = 35, PLAYER_LOGIN_QUERY_LOAD_CORPSE_LOCATION = 36, PLAYER_LOGIN_QUERY_LOAD_ALL_PETS = 37, PLAYER_LOGIN_QUERY_LOAD_LFG_REWARD_STATUS = 38, MAX_PLAYER_LOGIN_QUERY }; enum PlayerDelayedOperations { DELAYED_SAVE_PLAYER = 0x01, DELAYED_RESURRECT_PLAYER = 0x02, DELAYED_SPELL_CAST_DESERTER = 0x04, DELAYED_BG_MOUNT_RESTORE = 0x08, ///< Flag to restore mount state after teleport from BG DELAYED_BG_TAXI_RESTORE = 0x10, ///< Flag to restore taxi state after teleport from BG DELAYED_BG_GROUP_RESTORE = 0x20, ///< Flag to restore group state after teleport from BG DELAYED_END }; // Player summoning auto-decline time (in secs) constexpr uint32 MAX_PLAYER_SUMMON_DELAY= 2 * MINUTE; // Maximum money amount : 2^31 - 1 TC_GAME_API extern uint64 const MAX_MONEY_AMOUNT; enum BindExtensionState { EXTEND_STATE_EXPIRED = 0, EXTEND_STATE_NORMAL = 1, EXTEND_STATE_EXTENDED = 2, EXTEND_STATE_KEEP = 255 // special state: keep current save type }; struct InstancePlayerBind { InstanceSave* save; /* permanent PlayerInstanceBinds are created in Raid/Heroic instances for players that aren't already permanently bound when they are inside when a boss is killed or when they enter an instance that the group leader is permanently bound to. */ bool perm; /* extend state listing: EXPIRED - doesn't affect anything unless manually re-extended by player NORMAL - standard state EXTENDED - won't be promoted to EXPIRED at next reset period, will instead be promoted to NORMAL */ BindExtensionState extendState; InstancePlayerBind() : save(nullptr), perm(false), extendState(EXTEND_STATE_NORMAL) { } }; enum CharDeleteMethod { CHAR_DELETE_REMOVE = 0, // Completely remove from the database CHAR_DELETE_UNLINK = 1 // The character gets unlinked from the account, // the name gets freed up and appears as deleted ingame }; enum ReferAFriendError { ERR_REFER_A_FRIEND_NONE = 0x00, ERR_REFER_A_FRIEND_NOT_REFERRED_BY = 0x01, ERR_REFER_A_FRIEND_TARGET_TOO_HIGH = 0x02, ERR_REFER_A_FRIEND_INSUFFICIENT_GRANTABLE_LEVELS = 0x03, ERR_REFER_A_FRIEND_TOO_FAR = 0x04, ERR_REFER_A_FRIEND_DIFFERENT_FACTION = 0x05, ERR_REFER_A_FRIEND_NOT_NOW = 0x06, ERR_REFER_A_FRIEND_GRANT_LEVEL_MAX_I = 0x07, ERR_REFER_A_FRIEND_NO_TARGET = 0x08, ERR_REFER_A_FRIEND_NOT_IN_GROUP = 0x09, ERR_REFER_A_FRIEND_SUMMON_LEVEL_MAX_I = 0x0A, ERR_REFER_A_FRIEND_SUMMON_COOLDOWN = 0x0B, ERR_REFER_A_FRIEND_INSUF_EXPAN_LVL = 0x0C, ERR_REFER_A_FRIEND_SUMMON_OFFLINE_S = 0x0D }; enum PlayerRestState : uint8 { REST_STATE_RESTED = 0x01, REST_STATE_NOT_RAF_LINKED = 0x02, REST_STATE_RAF_LINKED = 0x06 }; enum PlayerCommandStates { CHEAT_NONE = 0x00, CHEAT_GOD = 0x01, CHEAT_CASTTIME = 0x02, CHEAT_COOLDOWN = 0x04, CHEAT_POWER = 0x08, CHEAT_WATERWALK = 0x10 }; enum PlayerLogXPReason : uint8 { LOG_XP_REASON_KILL = 0, LOG_XP_REASON_NO_KILL = 1 }; struct PlayerPetData { uint32 PetId; uint32 CreatureId; uint64 Owner; uint32 DisplayId; uint32 Petlevel; uint32 PetExp; ReactStates Reactstate; uint8 Slot; std::string Name; bool Renamed; bool Active; uint32 SavedHealth; uint32 SavedMana; std::string Actionbar; uint32 Timediff; uint32 SummonSpellId; PetType Type; }; class Player; /// Holder for Battleground data struct BGData { BGData() : bgInstanceID(0), bgTypeID(BATTLEGROUND_TYPE_NONE), bgAfkReportedCount(0), bgAfkReportedTimer(0), bgTeam(0), mountSpell(0) { bgQueuesJoinedTime.clear(); ClearTaxiPath(); } uint32 bgInstanceID; ///< This variable is set to bg->m_InstanceID, /// when player is teleported to BG - (it is battleground's GUID) BattlegroundTypeId bgTypeID; std::map<uint32, uint32> bgQueuesJoinedTime; std::set<uint32> bgAfkReporter; uint8 bgAfkReportedCount; time_t bgAfkReportedTimer; uint32 bgTeam; ///< What side the player will be added to uint32 mountSpell; uint32 taxiPath[2]; WorldLocation joinPos; ///< From where player entered BG WorldLocation leavePos; void ClearTaxiPath() { taxiPath[0] = taxiPath[1] = 0; } bool HasTaxiPath() const { return taxiPath[0] && taxiPath[1]; } }; struct VoidStorageItem { VoidStorageItem() : ItemId(0), ItemEntry(0), ItemRandomPropertyId(), ItemSuffixFactor(0) { } VoidStorageItem(uint64 id, uint32 entry, ObjectGuid const& creator, ItemRandomEnchantmentId randomPropertyId, uint32 suffixFactor) : ItemId(id), ItemEntry(entry), CreatorGuid(creator), ItemRandomPropertyId(randomPropertyId), ItemSuffixFactor(suffixFactor) { } uint64 ItemId; uint32 ItemEntry; ObjectGuid CreatorGuid; ItemRandomEnchantmentId ItemRandomPropertyId; uint32 ItemSuffixFactor; }; struct ResurrectionData { ObjectGuid GUID; WorldLocation Location; uint32 Health; uint32 Mana; uint32 Aura; }; class TC_GAME_API Player : public Unit, public GridObject<Player> { friend class WorldSession; friend class CinematicMgr; friend void AddItemToUpdateQueueOf(Item* item, Player* player); friend void RemoveItemFromUpdateQueueOf(Item* item, Player* player); public: explicit Player(WorldSession* session); ~Player(); PlayerAI* AI() const { return reinterpret_cast<PlayerAI*>(GetAI()); } void CleanupsBeforeDelete(bool finalCleanup = true) override; void AddToWorld() override; void RemoveFromWorld() override; void SetObjectScale(float scale) override; bool TeleportTo(uint32 mapid, float x, float y, float z, float orientation, TeleportToOptions options = TELE_TO_NONE, Optional<uint32> instanceId = {}); bool TeleportTo(WorldLocation const& loc, TeleportToOptions options = TELE_TO_NONE, Optional<uint32> instanceId = {}); bool TeleportToBGEntryPoint(); bool HasSummonPending() const; void SendSummonRequestFrom(Unit* summoner); void SummonIfPossible(bool agree); bool Create(ObjectGuid::LowType guidlow, CharacterCreateInfo* createInfo); void Update(uint32 time) override; void Heartbeat() override; bool IsImmunedToSpellEffect(SpellInfo const* spellInfo, uint32 index, WorldObject const* caster, bool requireImmunityPurgesEffectAttribute = false) const override; bool IsInAreaTriggerRadius(AreaTriggerEntry const* trigger) const; void SendInitialPacketsBeforeAddToMap(bool firstLogin = false); void SendInitialPacketsAfterAddToMap(); void SendSupercededSpell(uint32 oldSpell, uint32 newSpell) const; void SendTransferAborted(uint32 mapid, TransferAbortReason reason, uint8 arg = 0) const; void SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint32 time, bool welcome) const; bool CanInteractWithQuestGiver(Object* questGiver) const; Creature* GetNPCIfCanInteractWith(ObjectGuid const& guid, uint32 npcflagmask) const; GameObject* GetGameObjectIfCanInteractWith(ObjectGuid const& guid) const; GameObject* GetGameObjectIfCanInteractWith(ObjectGuid const& guid, GameobjectTypes type) const; void ToggleAFK(); void ToggleDND(); bool isAFK() const { return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK); } bool isDND() const { return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND); } uint8 GetChatTag() const; std::string autoReplyMsg; uint32 GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, BarberShopStyleEntry const* newSkin = nullptr) const; PlayerSocial* GetSocial() { return m_social; } void RemoveSocial(); void SendTamePetFailure(PetTameFailureReason reason); PlayerTaxi m_taxi; void InitTaxiNodesForLevel() { m_taxi.InitTaxiNodesForLevel(getRace(), getClass(), getLevel()); } bool ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc = nullptr, uint32 spellid = 0); bool ActivateTaxiPathTo(uint32 taxi_path_id, uint32 spellid = 0); void CleanupAfterTaxiFlight(); void ContinueTaxiFlight() const; void SendTaxiNodeStatusMultiple(); // mount_id can be used in scripting calls bool isAcceptWhispers() const { return (m_ExtraFlags & PLAYER_EXTRA_ACCEPT_WHISPERS) != 0; } void SetAcceptWhispers(bool on) { if (on) m_ExtraFlags |= PLAYER_EXTRA_ACCEPT_WHISPERS; else m_ExtraFlags &= ~PLAYER_EXTRA_ACCEPT_WHISPERS; } bool IsGameMaster() const { return (m_ExtraFlags & PLAYER_EXTRA_GM_ON) != 0; } bool CanBeGameMaster() const; void SetGameMaster(bool on); bool isGMChat() const { return (m_ExtraFlags & PLAYER_EXTRA_GM_CHAT) != 0; } void SetGMChat(bool on) { if (on) m_ExtraFlags |= PLAYER_EXTRA_GM_CHAT; else m_ExtraFlags &= ~PLAYER_EXTRA_GM_CHAT; } bool isTaxiCheater() const { return (m_ExtraFlags & PLAYER_EXTRA_TAXICHEAT) != 0; } void SetTaxiCheater(bool on) { if (on) m_ExtraFlags |= PLAYER_EXTRA_TAXICHEAT; else m_ExtraFlags &= ~PLAYER_EXTRA_TAXICHEAT; } bool isGMVisible() const { return !(m_ExtraFlags & PLAYER_EXTRA_GM_INVISIBLE); } void SetGMVisible(bool on); void SetPvPDeath(bool on) { if (on) m_ExtraFlags |= PLAYER_EXTRA_PVP_DEATH; else m_ExtraFlags &= ~PLAYER_EXTRA_PVP_DEATH; } void GiveXP(uint32 xp, Unit* victim, float group_rate=1.0f); void GiveLevel(uint8 level); bool IsMaxLevel() const; void InitStatsForLevel(bool reapplyMods = false); // .cheat command related bool GetCommandStatus(uint32 command) const { return (_activeCheats & command) != 0; } void SetCommandStatusOn(uint32 command) { _activeCheats |= command; } void SetCommandStatusOff(uint32 command) { _activeCheats &= ~command; } // Played Time Stuff time_t m_logintime; time_t m_Last_tick; std::array<uint32, MAX_PLAYED_TIME_INDEX> m_Played_time; uint32 GetTotalPlayedTime() const { return m_Played_time[PLAYED_TIME_TOTAL]; } uint32 GetLevelPlayedTime() const { return m_Played_time[PLAYED_TIME_LEVEL]; } void setDeathState(DeathState s) override; // overwrite Unit::setDeathState float GetRestBonus() const { return m_rest_bonus; } void SetRestBonus(float rest_bonus_new); bool HasRestFlag(RestFlag restFlag) const { return (_restFlagMask & restFlag) != 0; } void SetRestFlag(RestFlag restFlag); void RemoveRestFlag(RestFlag restFlag); uint32 GetXPRestBonus(uint32 xp); uint32 GetInnTriggerId() const { return inn_triggerId; } void SetInnTriggerID(uint32 id) { inn_triggerId = id; } Pet* GetPet() const; Pet* SummonPet(uint32 entry, float x, float y, float z, float ang, PetType petType, uint32 despwtime); void RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent = false); // pet auras std::unordered_set<PetAura const*> m_petAuras; void AddPetAura(PetAura const* petSpell); void RemovePetAura(PetAura const* petSpell); /// Handles said message in regular chat based on declared language and in config pre-defined Range. void Say(std::string const& text, Language language, WorldObject const* = nullptr) override; void Say(uint32 textId, WorldObject const* target = nullptr) override; /// Handles yelled message in regular chat based on declared language and in config pre-defined Range. void Yell(std::string const& text, Language language, WorldObject const* = nullptr) override; void Yell(uint32 textId, WorldObject const* target = nullptr) override; /// Outputs an universal text which is supposed to be an action. void TextEmote(std::string const& text, WorldObject const* = nullptr, bool = false) override; void TextEmote(uint32 textId, WorldObject const* target = nullptr, bool isBossEmote = false) override; /// Handles whispers from Addons and players based on sender, receiver's guid and language. void Whisper(std::string const& text, Language language, Player* receiver, bool = false) override; void Whisper(uint32 textId, Player* target, bool isBossWhisper = false) override; void WhisperAddon(std::string const& text, std::string const& prefix, Player* receiver); /*********************************************************/ /*** STORAGE SYSTEM ***/ /*********************************************************/ void SetVirtualItemSlot(uint8 i, Item* item); void SetSheath(SheathState sheathed) override; // overwrite Unit version uint8 FindEquipSlot(ItemTemplate const* proto, uint32 slot, bool swap) const; uint32 GetItemCount(uint32 item, bool inBankAlso = false, Item* skipItem = nullptr) const; uint32 GetItemCountWithLimitCategory(uint32 limitCategory, Item* skipItem = nullptr) const; Item* GetItemByGuid(ObjectGuid guid) const; Item* GetItemByEntry(uint32 entry) const; Item* GetItemByPos(uint16 pos) const; Item* GetItemByPos(uint8 bag, uint8 slot) const; Item* GetUseableItemByPos(uint8 bag, uint8 slot) const; Bag* GetBagByPos(uint8 slot) const; uint32 GetFreeInventorySpace() const; Item* GetWeaponForAttack(WeaponAttackType attackType, bool useable = false) const; Item* GetShield(bool useable = false) const; static WeaponAttackType GetAttackBySlot(uint8 slot); // MAX_ATTACK if not weapon slot std::vector<Item*>& GetItemUpdateQueue() { return m_itemUpdateQueue; } static bool IsInventoryPos(uint16 pos) { return IsInventoryPos(pos >> 8, pos & 255); } static bool IsInventoryPos(uint8 bag, uint8 slot); static bool IsEquipmentPos(uint16 pos) { return IsEquipmentPos(pos >> 8, pos & 255); } static bool IsEquipmentPos(uint8 bag, uint8 slot); static bool IsBagPos(uint16 pos); static bool IsBankPos(uint16 pos) { return IsBankPos(pos >> 8, pos & 255); } static bool IsBankPos(uint8 bag, uint8 slot); bool IsValidPos(uint16 pos, bool explicit_pos) const { return IsValidPos(pos >> 8, pos & 255, explicit_pos); } bool IsValidPos(uint8 bag, uint8 slot, bool explicit_pos) const; uint8 GetBankBagSlotCount() const { return GetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_BANK_BAG_SLOTS); } void SetBankBagSlotCount(uint8 count) { SetByteValue(PLAYER_BYTES_2, PLAYER_BYTES_2_OFFSET_BANK_BAG_SLOTS, count); } bool HasItemCount(uint32 item, uint32 count = 1, bool inBankAlso = false) const; bool HasItemFitToSpellRequirements(SpellInfo const* spellInfo, Item const* ignoreItem = nullptr) const; bool HasAllItemsToFitToSpellRequirements(SpellInfo const* spellInfo); bool CanNoReagentCast(SpellInfo const* spellInfo) const; bool HasItemOrGemWithIdEquipped(uint32 item, uint32 count, uint8 except_slot = NULL_SLOT) const; bool HasItemWithLimitCategoryEquipped(uint32 limitCategory, uint32 count, uint8 except_slot = NULL_SLOT) const; bool HasGemWithLimitCategoryEquipped(uint32 limitCategory, uint32 count, uint8 except_slot = NULL_SLOT) const; InventoryResult CanTakeMoreSimilarItems(Item* pItem, uint32* offendingItemId = nullptr) const; InventoryResult CanTakeMoreSimilarItems(uint32 entry, uint32 count, uint32* offendingItemId = nullptr) const { return CanTakeMoreSimilarItems(entry, count, nullptr, nullptr, offendingItemId); } InventoryResult CanStoreNewItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 item, uint32 count, uint32* no_space_count = nullptr) const; InventoryResult CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, Item* pItem, bool swap = false) const; InventoryResult CanStoreItems(Item** items, int count, uint32* offendingItemId) const; InventoryResult CanEquipNewItem(uint8 slot, uint16& dest, uint32 item, bool swap) const; InventoryResult CanEquipItem(uint8 slot, uint16& dest, Item* pItem, bool swap, bool not_loading = true) const; InventoryResult CanEquipUniqueItem(Item* pItem, uint8 except_slot = NULL_SLOT, uint32 limit_count = 1) const; InventoryResult CanEquipUniqueItem(ItemTemplate const* itemProto, uint8 except_slot = NULL_SLOT, uint32 limit_count = 1) const; InventoryResult CanUnequipItems(uint32 item, uint32 count) const; InventoryResult CanUnequipItem(uint16 src, bool swap) const; InventoryResult CanBankItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, Item* pItem, bool swap, bool not_loading = true) const; InventoryResult CanUseItem(Item* pItem, bool not_loading = true) const; bool HasItemTotemCategory(uint32 TotemCategory) const; InventoryResult CanUseItem(ItemTemplate const* pItem) const; bool CanRollNeedForItem(ItemTemplate const* itemTemplate) const; Item* StoreNewItem(ItemPosCountVec const& pos, uint32 item, bool update, ItemRandomEnchantmentId const& randomPropertyId = {}, GuidSet const& allowedLooters = GuidSet()); Item* StoreItem(ItemPosCountVec const& pos, Item* pItem, bool update); Item* EquipNewItem(uint16 pos, uint32 item, bool update); Item* EquipItem(uint16 pos, Item* pItem, bool update); void AutoUnequipOffhandIfNeed(bool force = false); bool StoreNewItemInBestSlots(uint32 item_id, uint32 item_count); void AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast = false); void AutoStoreLoot(uint32 loot_id, LootStore const& store, bool broadcast = false) { AutoStoreLoot(NULL_BAG, NULL_SLOT, loot_id, store, broadcast); } void StoreLootItem(ObjectGuid lootWorldObjectGuid, uint8 lootSlot, Loot* loot, GameObject* go = nullptr); InventoryResult CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count = nullptr, uint32* offendingItemId = nullptr) const; InventoryResult CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 entry, uint32 count, Item* pItem = nullptr, bool swap = false, uint32* no_space_count = nullptr) const; void AddRefundReference(ObjectGuid it); void DeleteRefundReference(ObjectGuid it); /// send initialization of new currency for client void SendNewCurrency(uint32 id) const; /// send full data about all currencies to client void SendCurrencies() const; /// send conquest currency points and their cap week/arena void SendPvpRewards() const; /// return count of currency witch has plr uint32 GetCurrency(uint32 id, bool usePrecision) const; /// return count of currency gaind on current week uint32 GetCurrencyOnWeek(uint32 id, bool usePrecision) const; /// return count of earned currency on current season uint32 GetCurrencyOnSeason(uint32 id) const; /// return week cap by currency id uint32 GetCurrencyWeekCap(uint32 id, bool usePrecision) const; /// return presence related currency bool HasCurrency(uint32 id, uint32 count) const; /// initialize currency count for custom initialization at create character void SetCurrency(uint32 currencyId, uint32 amount); void ResetCurrencyWeekCap(); void ModifyCurrency(uint32 currencyId, int32 amount, bool supressChatLog = false, bool ignoreModifiersAndTracking = false); void ApplyEquipCooldown(Item* pItem); void QuickEquipItem(uint16 pos, Item* pItem); void VisualizeItem(uint8 slot, Item* pItem); void SetVisibleItemSlot(uint8 slot, Item* pItem); Item* BankItem(ItemPosCountVec const& dest, Item* pItem, bool update); void RemoveItem(uint8 bag, uint8 slot, bool update); void MoveItemFromInventory(uint8 bag, uint8 slot, bool update); // in trade, auction, guild bank, mail.... void MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB = false); // in trade, guild bank, mail.... void RemoveItemDependentAurasAndCasts(Item* pItem); void DestroyItem(uint8 bag, uint8 slot, bool update); void DestroyItemCount(uint32 item, uint32 count, bool update, bool unequip_check = false); void DestroyItemCount(Item* item, uint32& count, bool update); void DestroyConjuredItems(bool update); void DestroyZoneLimitedItem(bool update, uint32 new_zone); void SplitItem(uint16 src, uint16 dst, uint32 count); void SwapItem(uint16 src, uint16 dst); void AddItemToBuyBackSlot(Item* pItem); Item* GetItemFromBuyBackSlot(uint32 slot); void RemoveItemFromBuyBackSlot(uint32 slot, bool del); void SendEquipError(InventoryResult msg, Item* pItem, Item* pItem2 = nullptr, uint32 itemid = 0) const; void SendBuyError(BuyResult msg, Creature* creature, uint32 item, uint32 param) const; void SendSellError(SellResult msg, Creature* creature, ObjectGuid guid) const; void AddWeaponProficiency(uint32 newflag) { m_WeaponProficiency |= newflag; } void AddArmorProficiency(uint32 newflag) { m_ArmorProficiency |= newflag; } uint32 GetWeaponProficiency() const { return m_WeaponProficiency; } uint32 GetArmorProficiency() const { return m_ArmorProficiency; } bool IsUseEquipedWeapon(bool mainhand) const; bool IsTwoHandUsed() const; bool IsUsingTwoHandedWeaponInOneHand() const; void SendNewItem(Item* item, uint32 count, bool received, bool created, bool broadcast = false, bool sendChatMessage = true); bool BuyItemFromVendorSlot(ObjectGuid vendorguid, uint32 vendorslot, uint32 item, uint32 count, uint8 bag, uint8 slot); bool BuyCurrencyFromVendorSlot(ObjectGuid vendorGuid, uint32 vendorSlot, uint32 currency, uint32 count); bool _StoreOrEquipNewItem(uint32 vendorslot, uint32 item, uint32 count, uint8 bag, uint8 slot, int64 price, ItemTemplate const* pProto, Creature* pVendor, VendorItem const* crItem, bool bStore); float GetReputationPriceDiscount(Creature const* creature) const; Player* GetTrader() const; TradeData* GetTradeData() const { return m_trade; } void TradeCancel(bool sendback, TradeStatus status = TRADE_STATUS_TRADE_CANCELED); CinematicMgr* GetCinematicMgr() const { return _cinematicMgr.get(); } void UpdateEnchantTime(uint32 time); void UpdateSoulboundTradeItems(); void AddTradeableItem(Item* item); void RemoveTradeableItem(Item* item); void UpdateItemDuration(uint32 time, bool realtimeonly = false); void AddEnchantmentDurations(Item* item); void RemoveEnchantmentDurations(Item* item); void RemoveEnchantmentDurationsReferences(Item* item); void RemoveArenaEnchantments(EnchantmentSlot slot); void AddEnchantmentDuration(Item* item, EnchantmentSlot slot, uint32 duration); void ApplyEnchantment(Item* item, EnchantmentSlot slot, bool apply, bool apply_dur = true, bool ignore_condition = false); void ApplyEnchantment(Item* item, bool apply); void ApplyReforgeEnchantment(Item* item, bool apply); void UpdateSkillEnchantments(uint16 skill_id, uint16 curr_value, uint16 new_value); void SendEnchantmentDurations(); void BuildEnchantmentsInfoData(WorldPacket* data); void AddItemDurations(Item* item); void RemoveItemDurations(Item* item); void SendItemDurations(); void LoadCorpse(PreparedQueryResult result); void LoadPet(); void LoadPetsFromDB(PreparedQueryResult result); bool AddItem(uint32 itemId, uint32 count); uint32 m_stableSlots; /*********************************************************/ /*** GOSSIP SYSTEM ***/ /*********************************************************/ void PrepareGossipMenu(WorldObject* source, uint32 menuId = 0, bool showQuests = false); void SendPreparedGossip(WorldObject* source); void OnGossipSelect(WorldObject* source, uint32 gossipListId, uint32 menuId); uint32 GetGossipTextId(uint32 menuId, WorldObject* source); uint32 GetGossipTextId(WorldObject* source); static uint32 GetDefaultGossipMenuForSource(WorldObject* source); /*********************************************************/ /*** QUEST SYSTEM ***/ /*********************************************************/ int32 GetQuestLevel(Quest const* quest) const { return quest && (quest->GetQuestLevel() > 0) ? quest->GetQuestLevel() : getLevel(); } void PrepareQuestMenu(ObjectGuid guid); void SendPreparedQuest(ObjectGuid guid); bool IsActiveQuest(uint32 quest_id) const; Quest const* GetNextQuest(Object const* questGiver, Quest const* quest) const; bool CanSeeStartQuest(Quest const* quest) const; bool CanTakeQuest(Quest const* quest, bool msg) const; bool CanAddQuest(Quest const* quest, bool msg) const; bool CanCompleteQuest(uint32 quest_id); bool CanCompleteRepeatableQuest(Quest const* quest); bool CanRewardQuest(Quest const* quest, bool msg); bool CanRewardQuest(Quest const* quest, uint32 reward, bool msg); void AddQuestAndCheckCompletion(Quest const* quest, Object* questGiver); void AddQuest(Quest const* quest, Object* questGiver); void AbandonQuest(uint32 quest_id); void CompleteQuest(uint32 quest_id); void IncompleteQuest(uint32 quest_id); int32 GetQuestMoneyReward(Quest const* quest) const; uint32 GetQuestXPReward(Quest const* quest); void RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, bool announce = true); void SetRewardedQuest(uint32 quest_id); void FailQuest(uint32 quest_id); void FailQuestsWithFlag(QuestFlags flag); bool SatisfyQuestSkill(Quest const* qInfo, bool msg) const; bool SatisfyQuestLevel(Quest const* qInfo, bool msg) const; bool SatisfyQuestLog(bool msg) const; bool SatisfyQuestDependentQuests(Quest const* qInfo, bool msg) const; bool SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg) const; bool SatisfyQuestDependentPreviousQuests(Quest const* qInfo, bool msg) const; bool SatisfyQuestBreadcrumbQuest(Quest const* qInfo, bool msg) const; bool SatisfyQuestDependentBreadcrumbQuests(Quest const* qInfo, bool msg) const; bool SatisfyQuestClass(Quest const* qInfo, bool msg) const; bool SatisfyQuestRace(Quest const* qInfo, bool msg) const; bool SatisfyQuestReputation(Quest const* qInfo, bool msg) const; bool SatisfyQuestStatus(Quest const* qInfo, bool msg) const; bool SatisfyQuestConditions(Quest const* qInfo, bool msg) const; bool SatisfyQuestTimed(Quest const* qInfo, bool msg) const; bool SatisfyQuestExclusiveGroup(Quest const* qInfo, bool msg) const; bool SatisfyQuestDay(Quest const* qInfo, bool msg) const; bool SatisfyQuestWeek(Quest const* qInfo, bool msg) const; bool SatisfyQuestMonth(Quest const* qInfo, bool msg) const; bool SatisfyQuestSeasonal(Quest const* qInfo, bool msg) const; bool GiveQuestSourceItem(Quest const* quest); bool TakeQuestSourceItem(uint32 questId, bool msg); bool GetQuestRewardStatus(uint32 quest_id) const; QuestStatus GetQuestStatus(uint32 quest_id) const; void SetQuestStatus(uint32 questId, QuestStatus status, bool update = true); void RemoveActiveQuest(uint32 questId, bool update = true); void RemoveRewardedQuest(uint32 questId, bool update = true); void SendQuestUpdate(uint32 questId); QuestGiverStatus GetQuestDialogStatus(Object* questGiver); bool SatisfyFirstLFGReward(uint32 dungeonId, uint8 maxRewCount) const; uint8 GetFirstRewardCountForDungeonId(uint32 dungeon); void SetDailyQuestStatus(uint32 quest_id); bool IsDailyQuestDone(uint32 quest_id); void SetWeeklyQuestStatus(uint32 quest_id); void SetMonthlyQuestStatus(uint32 quest_id); void SetSeasonalQuestStatus(uint32 quest_id); void SetLFGRewardStatus(uint32 dungeon_id, bool daily_reset); void ResetDailyQuestStatus(); void ResetWeeklyQuestStatus(); void ResetMonthlyQuestStatus(); void ResetSeasonalQuestStatus(uint16 event_id, time_t eventStartTime); void ResetWeeklyLFGRewardStatus(); void ResetDailyLFGRewardStatus(); uint16 FindQuestSlot(uint32 quest_id) const; uint32 GetQuestSlotQuestId(uint16 slot) const; uint32 GetQuestSlotState(uint16 slot) const; uint16 GetQuestSlotCounter(uint16 slot, uint8 counter) const; uint32 GetQuestSlotTime(uint16 slot) const; void SetQuestSlot(uint16 slot, uint32 quest_id, uint32 timer = 0); void SetQuestSlotCounter(uint16 slot, uint8 counter, uint16 count); void SetQuestSlotState(uint16 slot, uint32 state); void RemoveQuestSlotState(uint16 slot, uint32 state); void SetQuestSlotTimer(uint16 slot, uint32 timer); void SwapQuestSlot(uint16 slot1, uint16 slot2); uint16 GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry) const; void AreaExploredOrEventHappens(uint32 questId); void GroupEventHappens(uint32 questId, WorldObject const* pEventObject); void ItemAddedQuestCheck(uint32 entry, uint32 count); void ItemRemovedQuestCheck(uint32 entry, uint32 count); void KilledMonster(CreatureTemplate const* cInfo, ObjectGuid guid); void KilledMonsterCredit(uint32 entry, ObjectGuid guid = ObjectGuid::Empty); void KilledPlayerCredit(uint16 count = 1); void KilledPlayerCreditForQuest(uint16 count, Quest const* quest); void KillCreditGO(uint32 entry, ObjectGuid guid = ObjectGuid::Empty); void TalkedToCreature(uint32 entry, ObjectGuid guid); void MoneyChanged(uint64 value); void ReputationChanged(FactionEntry const* factionEntry); void ReputationChanged2(FactionEntry const* factionEntry); bool HasQuestForItem(uint32 itemId, uint32 excludeQuestId = 0, bool turnIn = false) const; bool HasQuestForGO(int32 goId) const; void UpdateVisibleGameobjectsOrSpellClicks(); bool CanShareQuest(uint32 questId) const; void SendQuestComplete(Quest const* quest) const; void SendQuestReward(Quest const* quest, Creature const* questGiver, uint32 xp); void SendQuestFailed(uint32 questId, InventoryResult reason = EQUIP_ERR_OK) const; void SendQuestTimerFailed(uint32 questId) const; void SendCanTakeQuestResponse(QuestFailedReason reason) const; void SendQuestConfirmAccept(Quest const* quest, Player* receiver) const; void SendPushToPartyResponse(Player const* player, uint8 msg) const; void SendQuestUpdateAddCredit(Quest const* quest, ObjectGuid guid, uint32 creatureOrGOIdx, uint16 count); void SendQuestUpdateAddPlayer(Quest const* quest, uint16 newCount); void SendQuestGiverStatusMultiple(); uint32 GetSharedQuestID() const { return m_sharedQuestId; } ObjectGuid GetPlayerSharingQuest() const { return m_playerSharingQuest; } void SetQuestSharingInfo(ObjectGuid guid, uint32 id) { m_playerSharingQuest = guid; m_sharedQuestId = id; } void ClearQuestSharingInfo() { m_playerSharingQuest = ObjectGuid::Empty; m_sharedQuestId = 0; } // Returns the ID of the next available quest in chain of the most recently rewarded quest that has been rewarded via UI popup uint32 GetPopupQuestId() const { return m_popupQuestId; } void SetPopupQuestId(uint32 questId) { m_popupQuestId = questId; } uint32 GetInGameTime() const { return m_ingametime; } void SetInGameTime(uint32 time) { m_ingametime = time; } void AddTimedQuest(uint32 questId) { m_timedquests.insert(questId); } void RemoveTimedQuest(uint32 questId) { m_timedquests.erase(questId); } void SaveCUFProfile(uint8 id, std::nullptr_t) { _CUFProfiles[id] = nullptr; } ///> Empties a CUF profile at position 0-4 void SaveCUFProfile(uint8 id, std::unique_ptr<CUFProfile> profile) { _CUFProfiles[id] = std::move(profile); } ///> Replaces a CUF profile at position 0-4 CUFProfile* GetCUFProfile(uint8 id) const { return _CUFProfiles[id].get(); } ///> Retrieves a CUF profile at position 0-4 uint8 GetCUFProfilesCount() const { uint8 count = 0; for (uint8 i = 0; i < MAX_CUF_PROFILES; ++i) if (_CUFProfiles[i]) ++count; return count; } bool HasPvPForcingQuest() const; /*********************************************************/ /*** LOAD SYSTEM ***/ /*********************************************************/ bool LoadFromDB(ObjectGuid guid, CharacterDatabaseQueryHolder const& holder); bool IsLoading() const override; void Initialize(ObjectGuid::LowType guid); static uint32 GetZoneIdFromDB(ObjectGuid guid); static bool LoadPositionFromDB(uint32& mapid, float& x, float& y, float& z, float& o, bool& in_flight, ObjectGuid guid); static bool IsValidGender(uint8 Gender) { return Gender <= GENDER_FEMALE; } static bool ValidateAppearance(uint8 race, uint8 class_, uint8 gender, uint8 hairID, uint8 hairColor, uint8 faceID, uint8 facialHair, uint8 skinColor, bool create = false); static bool IsValidClass(uint8 Class) { return ((1 << (Class - 1)) & CLASSMASK_ALL_PLAYABLE) != 0; } static bool IsValidRace(uint8 Race) { return ((1 << (Race - 1)) & RACEMASK_ALL_PLAYABLE) != 0; } /*********************************************************/ /*** SAVE SYSTEM ***/ /*********************************************************/ void SaveToDB(bool create = false); void SaveToDB(CharacterDatabaseTransaction trans, bool create = false); void SaveInventoryAndGoldToDB(CharacterDatabaseTransaction& trans); // fast save function for item/money cheating preventing void SaveGoldToDB(CharacterDatabaseTransaction& trans) const; static void Customize(CharacterCustomizeInfo const* customizeInfo, CharacterDatabaseTransaction& trans); static void SavePositionInDB(WorldLocation const& loc, uint16 zoneId, ObjectGuid guid, CharacterDatabaseTransaction& trans); static void DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRealmChars = true, bool deleteFinally = false); static void DeleteOldCharacters(); static void DeleteOldCharacters(uint32 keepDays); bool m_mailsUpdated; void SetBindPoint(ObjectGuid guid) const; void SendTalentWipeConfirm(ObjectGuid guid) const; void ResetPetTalents(); void RegenerateAll(uint32 diff); void RegenerateHealth() override; void setWeaponChangeTimer(uint32 time) { m_weaponChangeTimer = time;} uint64 GetMoney() const { return GetUInt64Value(PLAYER_FIELD_COINAGE); } bool ModifyMoney(int64 amount, bool sendError = true); bool HasEnoughMoney(uint64 amount) const { return (GetMoney() >= amount); } bool HasEnoughMoney(int64 amount) const; void SetMoney(uint64 value); RewardedQuestSet const& getRewardedQuests() const { return m_RewardedQuests; } QuestStatusMap& getQuestStatusMap() { return m_QuestStatus; } size_t GetRewardedQuestCount() const { return m_RewardedQuests.size(); } bool IsQuestRewarded(uint32 quest_id) const; Unit* GetSelectedUnit() const; Player* GetSelectedPlayer() const; void SetTarget(ObjectGuid /*guid*/) override { } /// Used for serverside target changes, does not apply to players void SetSelection(ObjectGuid guid) { SetGuidValue(UNIT_FIELD_TARGET, guid); } void SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError = 0, ObjectGuid::LowType item_guid = 0, uint32 item_count = 0) const; void SendNewMail() const; void UpdateNextMailTimeAndUnreads(); void AddNewMailDeliverTime(time_t deliver_time); void RemoveMail(uint32 id); void AddMail(Mail* mail) { m_mail.push_front(mail);}// for call from WorldSession::SendMailTo uint32 GetMailSize() { return m_mail.size();} Mail* GetMail(uint32 id); PlayerMails::iterator GetMailBegin() { return m_mail.begin();} PlayerMails::iterator GetMailEnd() { return m_mail.end();} void SendItemRetrievalMail(uint32 itemEntry, uint32 count); // Item retrieval mails sent by The Postmaster (34337), used in multiple places. /*********************************************************/ /*** MAILED ITEMS SYSTEM ***/ /*********************************************************/ uint8 unReadMails; time_t m_nextMailDelivereTime; typedef std::unordered_map<uint32, Item*> ItemMap; ItemMap mMitems; //template defined in objectmgr.cpp Item* GetMItem(uint32 id); void AddMItem(Item* it); bool RemoveMItem(uint32 id); void SendOnCancelExpectedVehicleRideAura() const; bool CanControlPet(uint32 spellId = 0) const; void PetSpellInitialize(); void CharmSpellInitialize(); void PossessSpellInitialize(); void VehicleSpellInitialize(); void SendPetSpells(SummonInfo* summonInfo); void SendRemoveControlBar() const; bool HasSpell(uint32 spell) const override; bool HasActiveSpell(uint32 spell) const; // show in spellbook bool IsSpellFitByClassAndRace(uint32 spell_id) const; bool HandlePassiveSpellLearn(SpellInfo const* spellInfo); bool IsCurrentSpecMasterySpell(SpellInfo const* spellInfo) const; void SendProficiency(ItemClass itemClass, uint32 itemSubclassMask) const; void SendKnownSpells(bool firstLogin = false); bool AddSpell(uint32 spellId, bool active, bool learning, bool dependent, bool disabled, bool loading = false, uint32 fromSkill = 0); void LearnSpell(uint32 spell_id, bool dependent, uint32 fromSkill = 0); void RemoveSpell(uint32 spell_id, bool disabled = false, bool learn_low_rank = true); void ResetSpells(bool myClassOnly = false); void LearnCustomSpells(); void LearnDefaultSkills(); void LearnDefaultSkill(SkillRaceClassInfoEntry const* rcInfo); void LearnQuestRewardedSpells(); void LearnQuestRewardedSpells(Quest const* quest); void LearnSpellHighestRank(uint32 spellid); void AddTemporarySpell(uint32 spellId); void RemoveTemporarySpell(uint32 spellId); void SetReputation(uint32 factionentry, uint32 value); uint32 GetReputation(uint32 factionentry) const; std::string GetGuildName() const; void SendSpellCategoryCooldowns() const; void SendRaidGroupOnlyMessage(RaidGroupReason reason, int32 delay) const; // Talents uint32 GetFreeTalentPoints() const; void SetFreeTalentPoints(uint32 points); uint32 GetUsedTalentCount() const; void SetUsedTalentCount(uint32 talents); uint32 GetQuestRewardedTalentCount() const; void AddQuestRewardedTalentCount(uint32 points); uint32 GetTalentResetCost() const; void SetTalentResetCost(uint32 cost); uint32 GetTalentResetTime() const; void SetTalentResetTime(time_t time_); uint32 GetPrimaryTalentTree(uint8 spec) const; void SetPrimaryTalentTree(uint8 spec, uint32 tree); uint8 GetActiveSpec() const; void SetActiveSpec(uint8 spec); uint8 GetSpecsCount() const; void SetSpecsCount(uint8 count); bool ResetTalents(bool no_cost = false); uint32 GetNextResetTalentsCost() const; void InitTalentForLevel(); void BuildPlayerTalentsInfoData(WorldPacket* data); void BuildPetTalentsInfoData(WorldPacket* data); void SendTalentsInfoData(bool pet); bool LearnTalent(uint32 talentId, uint32 talentRank); void LearnPetTalent(ObjectGuid petGuid, uint32 talentId, uint32 talentRank); bool LearnPrimaryTalentSpecialization(uint8 talentTabIndex); bool AddTalent(uint32 spellId, uint8 spec, bool learning); bool HasTalent(uint32 spell_id, uint8 spec) const; uint32 CalculateTalentsPoints() const; // Armor Specializaion void UpdateArmorSpecialization(); // Dual Spec void UpdateSpecCount(uint8 count); void ActivateSpec(uint8 spec); void LoadActions(PreparedQueryResult result); void InitGlyphsForLevel(); void SetGlyphSlot(uint8 slot, uint32 slottype) { SetUInt32Value(PLAYER_FIELD_GLYPH_SLOTS_1 + slot, slottype); } uint32 GetGlyphSlot(uint8 slot) const { return GetUInt32Value(PLAYER_FIELD_GLYPH_SLOTS_1 + slot); } void SetGlyph(uint8 slot, uint32 glyph); uint32 GetGlyph(uint8 spec, uint8 slot) const; PlayerTalentMap const& GetTalentMap(uint8 spec) const; PlayerTalentMap& GetTalentMap(uint8 spec); ActionButtonList const& GetActionButtons() const { return m_actionButtons; } uint32 GetFreePrimaryProfessionPoints() const { return GetUInt32Value(PLAYER_CHARACTER_POINTS); } void SetFreePrimaryProfessions(uint16 profs) { SetUInt32Value(PLAYER_CHARACTER_POINTS, profs); } void InitPrimaryProfessions(); PlayerSpellMap const& GetSpellMap() const { return m_spells; } PlayerSpellMap & GetSpellMap() { return m_spells; } void AddSpellMod(SpellModifier* mod, bool apply); static bool IsAffectedBySpellmod(SpellInfo const* spellInfo, SpellModifier const* mod, Spell* spell = nullptr); template <class T> void GetSpellModValues(SpellInfo const* spellInfo, SpellModOp op, Spell* spell, T base, int32* flat, float* pct) const; template <class T> void ApplySpellMod(SpellInfo const* spellInfo, SpellModOp op, T& basevalue, Spell* spell = nullptr) const; static void ApplyModToSpell(SpellModifier* mod, Spell* spell); void SetSpellModTakingSpell(Spell* spell, bool apply); void SendSpellModifiers() const; void RemoveArenaSpellCooldowns(bool removeActivePetCooldowns = false); uint32 GetLastPotionId() const { return m_lastPotionId; } void SetLastPotionId(uint32 item_id) { m_lastPotionId = item_id; } void UpdatePotionCooldown(Spell* spell = nullptr); void SetResurrectRequestData(WorldObject const* caster, uint32 health, uint32 mana, uint32 appliedAura); void ClearResurrectRequestData() { _resurrectionData.reset(); } bool IsResurrectRequestedBy(ObjectGuid const& guid) const { if (!IsResurrectRequested()) return false; return _resurrectionData->GUID == guid; } bool IsResurrectRequested() const { return _resurrectionData != nullptr; } void ResurrectUsingRequestData(); uint8 getCinematic() const { return m_cinematic; } void setCinematic(uint8 cine) { m_cinematic = cine; } uint32 GetMovie() const { return m_movie; } void SetMovie(uint32 movie) { m_movie = movie; } ActionButton* addActionButton(uint8 button, uint32 action, uint8 type); void removeActionButton(uint8 button); ActionButton const* GetActionButton(uint8 button); void SendInitialActionButtons() const { SendActionButtons(0); } void SendActionButtons(uint32 state) const; bool IsActionButtonDataValid(uint8 button, uint32 action, uint8 type) const; PvPInfo pvpInfo; void UpdatePvPState(bool onlyFFA = false); void SetPvP(bool state) override; void UpdatePvP(bool state, bool override = false); void UpdateZone(uint32 newZone, uint32 newArea); void UpdateArea(uint32 newArea); void UpdateHostileAreaState(AreaTableEntry const* area); void SetNeedsZoneUpdate(bool needsUpdate) { m_needsZoneUpdate = needsUpdate; } void UpdateZoneDependentAuras(uint32 zone_id); // zones void UpdateAreaDependentAuras(uint32 area_id); // subzones void UpdateAfkReport(time_t currTime); void UpdatePvPFlag(time_t currTime); void SetContestedPvP(Player* attackedPlayer = nullptr); void UpdateContestedPvP(uint32 currTime); void SetContestedPvPTimer(uint32 newTime) {m_contestedPvPTimer = newTime;} void ResetContestedPvP(); /// @todo: maybe move UpdateDuelFlag+DuelComplete to independent DuelHandler DuelInfo* duel; void UpdateDuelFlag(time_t currTime); void CheckDuelDistance(time_t currTime); void DuelComplete(DuelCompleteType type); void SendDuelCountdown(uint32 counter); bool IsGroupVisibleFor(Player const* p) const; bool IsInSameGroupWith(Player const* p) const; bool IsInSameRaidWith(Player const* p) const; void UninviteFromGroup(); static void RemoveFromGroup(Group* group, ObjectGuid guid, RemoveMethod method = GROUP_REMOVEMETHOD_DEFAULT, ObjectGuid kicker = ObjectGuid::Empty, char const* reason = nullptr); void RemoveFromGroup(RemoveMethod method = GROUP_REMOVEMETHOD_DEFAULT) { RemoveFromGroup(GetGroup(), GetGUID(), method); } void SendUpdateToOutOfRangeGroupMembers(); void SetInGuild(uint32 guildId); void SetGuildRank(uint8 rankId) { SetUInt32Value(PLAYER_GUILDRANK, rankId); } uint8 GetGuildRank() const { return uint8(GetUInt32Value(PLAYER_GUILDRANK)); } void SetGuildLevel(uint32 level) { SetUInt32Value(PLAYER_GUILDLEVEL, level); } uint32 GetGuildLevel() { return GetUInt32Value(PLAYER_GUILDLEVEL); } void SetGuildIdInvited(uint32 GuildId) { m_GuildIdInvited = GuildId; } uint32 GetGuildId() const { return GetUInt32Value(OBJECT_FIELD_DATA); /* return only lower part */ } Guild* GetGuild(); int GetGuildIdInvited() const { return m_GuildIdInvited; } static void RemovePetitionsAndSigns(ObjectGuid guid, CharterTypes type); // Arena Team void SetInArenaTeam(uint32 ArenaTeamId, uint8 slot, uint8 type); void SetArenaTeamInfoField(uint8 slot, ArenaTeamInfoType type, uint32 value); static void LeaveAllArenaTeams(ObjectGuid guid); uint32 GetArenaTeamId(uint8 slot) const { return GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + ARENA_TEAM_ID); } uint32 GetArenaPersonalRating(uint8 slot) const { return GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + ARENA_TEAM_PERSONAL_RATING); } void SetArenaTeamIdInvited(uint32 ArenaTeamId) { m_ArenaTeamIdInvited = ArenaTeamId; } uint32 GetArenaTeamIdInvited() const { return m_ArenaTeamIdInvited; } uint32 GetRBGPersonalRating() const { return 0; } Difficulty GetDifficulty(bool isRaid) const { return isRaid ? m_raidDifficulty : m_dungeonDifficulty; } Difficulty GetDungeonDifficulty() const { return m_dungeonDifficulty; } Difficulty GetRaidDifficulty() const { return m_raidDifficulty; } Difficulty GetStoredRaidDifficulty() const { return m_raidMapDifficulty; } // only for use in difficulty packet after exiting to raid map void SetDungeonDifficulty(Difficulty dungeon_difficulty) { m_dungeonDifficulty = dungeon_difficulty; } void SetRaidDifficulty(Difficulty raid_difficulty) { m_raidDifficulty = raid_difficulty; } void StoreRaidMapDifficulty(); bool UpdateSkill(uint32 skill_id, uint32 step); bool UpdateSkillPro(uint16 skillId, int32 chance, uint32 step); bool UpdateCraftSkill(SpellInfo const* spellInfo); bool UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator = 1); bool UpdateFishingSkill(); void SurveyDigSite(); void NotifyRequestResearchHistory(); bool ArchProjectCompleteable(uint16 projectId); bool HasArchProject(uint16 projectId); void CompleteArchProject(uint16 projectId); void SetArchData(ArchData const& data); float GetHealthBonusFromStamina(); float GetManaBonusFromIntellect(); bool UpdateStats(Stats stat) override; bool UpdateAllStats() override; void ApplySpellPenetrationBonus(int32 amount, bool apply); void UpdateResistances(uint32 school) override; void UpdateArmor() override; void UpdateMaxHealth() override; void UpdateMaxPower(Powers power) override; uint32 GetPowerIndex(Powers power) const override; void UpdateAttackPowerAndDamage(bool ranged = false) override; void ApplySpellPowerBonus(int32 amount, bool apply); void UpdateSpellDamageAndHealingBonus(); void UpdateSpellHealingPercentDone(); void UpdateSpellHealingPercentTaken(); void ApplyRatingMod(CombatRating cr, int32 value, bool apply); void UpdateRating(CombatRating cr); void UpdateAllRatings(); void UpdateMastery(); bool CanUseMastery() const; void CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, bool addTotalPct, float& minDamage, float& maxDamage) const override; void RecalculateRating(CombatRating cr) { ApplyRatingMod(cr, 0, true);} float GetMeleeCritFromAgility() const; void GetDodgeFromAgility(float &diminishing, float &nondiminishing) const; float GetSpellCritFromIntellect() const; float GetRatingMultiplier(CombatRating cr) const; float GetRatingBonusValue(CombatRating cr) const; /// Returns base spellpower bonus from spellpower stat on items, without spellpower from intellect stat uint32 GetBaseSpellPowerBonus() const { return m_baseSpellPower; } int32 GetSpellPenetrationItemMod() const { return m_spellPenetrationItemMod; } bool CanApplyResilience() const override { return true; } float GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const; void UpdateBlockPercentage(); void UpdateCritPercentage(WeaponAttackType attType); void UpdateAllCritPercentages(); void UpdateParryPercentage(); void UpdateDodgePercentage(); void UpdateMeleeHitChances(); void UpdateRangedHitChances(); void UpdateSpellHitChances(); void UpdateHitChances(); void UpdateAllSpellCritChances(); void UpdateSpellCritChance(uint32 school); void UpdateExpertise(WeaponAttackType attType); void ApplyManaRegenBonus(int32 amount, bool apply); void ApplyHealthRegenBonus(int32 amount, bool apply); uint32 GetRuneTimer(uint8 index) const { return m_runeGraceCooldown[index]; } void SetRuneTimer(uint8 index, uint32 timer) { m_runeGraceCooldown[index] = timer; } uint32 GetLastRuneGraceTimer(uint8 index) const { return m_lastRuneGraceTimers[index]; } void SetLastRuneGraceTimer(uint8 index, uint32 timer) { m_lastRuneGraceTimers[index] = timer; } ObjectGuid GetLootGUID() const { return m_lootGuid; } void SetLootGUID(ObjectGuid guid) { m_lootGuid = guid; } void RemovedInsignia(Player* looterPlr); WorldSession* GetSession() const { return m_session; } GameClient* GetGameClient() const; void BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) const override; void DestroyForPlayer(Player* target, bool onDeath = false) const override; // notifiers void SendAttackSwingCantAttack() const; void SendAttackSwingCancelAttack() const; void SendAttackSwingDeadTarget() const; void SendAttackSwingNotInRange() const; void SendAttackSwingBadFacingAttack() const; void SendAutoRepeatCancel(Unit* target); void SendExplorationExperience(uint32 Area, uint32 Experience) const; void SendDungeonDifficulty(bool IsInGroup) const; void SendRaidDifficulty(bool IsInGroup, int32 forcedDifficulty = -1) const; void ResetInstances(uint8 method, bool isRaid); void SendResetInstanceSuccess(uint32 MapId) const; void SendResetInstanceFailed(uint32 reason, uint32 MapId) const; void SendResetFailedNotify(uint32 mapid) const; bool UpdatePosition(float x, float y, float z, float orientation, bool teleport = false) override; bool UpdatePosition(Position const& pos, bool teleport = false) override { return UpdatePosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), teleport); } void ProcessTerrainStatusUpdate(ZLiquidStatus oldLiquidStatus, Optional<LiquidData> const& newLiquidData) override; void AtExitCombat() override; void SendMessageToSet(WorldPacket const* data, bool self) const override { SendMessageToSetInRange(data, GetVisibilityRange(), self); } void SendMessageToSetInRange(WorldPacket const* data, float dist, bool self) const override; void SendMessageToSetInRange(WorldPacket const* data, float dist, bool self, bool own_team_only) const; void SendMessageToSet(WorldPacket const* data, Player const* skipped_rcvr) const override; Corpse* GetCorpse() const; void SpawnCorpseBones(bool triggerSave = true); Corpse* CreateCorpse(); void KillPlayer(); static void OfflineResurrect(ObjectGuid const& guid, CharacterDatabaseTransaction& trans); bool HasCorpse() const { return _corpseLocation.GetMapId() != MAPID_INVALID; } WorldLocation GetCorpseLocation() const { return _corpseLocation; } uint32 GetResurrectionSpellId(); void ResurrectPlayer(float restore_percent, bool applySickness = false); void BuildPlayerRepop(); void RepopAtGraveyard(); void DurabilityLossAll(double percent, bool inventory); void DurabilityLoss(Item* item, double percent); void DurabilityPointsLossAll(int32 points, bool inventory); void DurabilityPointsLoss(Item* item, int32 points); void DurabilityPointLossForEquipSlot(EquipmentSlots slot); void DurabilityRepairAll(bool takeCost, float discountMod, bool guildBank); void DurabilityRepair(uint16 pos, bool takeCost, float discountMod); void UpdateMirrorTimers(); void StopMirrorTimers(); bool IsMirrorTimerActive(MirrorTimerType type) const; bool CanJoinConstantChannelInZone(ChatChannelsEntry const* channel, AreaTableEntry const* zone) const; void JoinedChannel(Channel* c); void LeftChannel(Channel* c); void CleanupChannels(); void UpdateLocalChannels(uint32 newZone); void LeaveLFGChannel(); typedef std::list<Channel*> JoinedChannelsList; JoinedChannelsList const& GetJoinedChannels() const { return m_channels; } void InitializeSkillFields(); void SetSkill(uint16 id, uint16 step, uint16 newVal, uint16 maxVal); uint16 GetMaxSkillValue(uint32 skill) const; // max + perm. bonus + temp bonus uint16 GetPureMaxSkillValue(uint32 skill) const; // max uint16 GetSkillValue(uint32 skill) const; // skill value + perm. bonus + temp bonus uint16 GetBaseSkillValue(uint32 skill) const; // skill value + perm. bonus uint16 GetPureSkillValue(uint32 skill) const; // skill value int16 GetSkillPermBonusValue(uint32 skill) const; int16 GetSkillTempBonusValue(uint32 skill) const; uint16 GetSkillStep(uint16 skill) const; // 0...6 bool HasSkill(uint32 skill) const; void LearnSkillRewardedSpells(uint32 skillId, uint32 skillValue); uint32 GetSkillRank(uint8 pos) const; void SetSkillLineId(uint8 pos, uint16 value); void SetSkillStep(uint8 pos, uint16 value); void SetSkillRank(uint8 pos, uint16 value); void SetSkillMaxRank(uint8 pos, uint16 value); void SetSkillTempBonus(uint8 pos, uint16 value); void SetSkillPermBonus(uint8 pos, uint16 value); WorldLocation& GetTeleportDest() { return m_teleport_dest; } Optional<uint32> GetTeleportDestInstanceId() const { return m_teleport_instanceId; } bool IsBeingTeleported() const { return mSemaphoreTeleport_Near || mSemaphoreTeleport_Far; } bool IsBeingTeleportedNear() const { return mSemaphoreTeleport_Near; } bool IsBeingTeleportedFar() const { return mSemaphoreTeleport_Far; } void SetSemaphoreTeleportNear(bool semphsetting) { mSemaphoreTeleport_Near = semphsetting; } void SetSemaphoreTeleportFar(bool semphsetting) { mSemaphoreTeleport_Far = semphsetting; } void ProcessDelayedOperations(); void CheckAreaExplore(); void SetAreaExplored(uint32 areaId); // These methods are used to periodically update certain area and aura based mechanics used in Heartbeat and Movement void UpdateZoneAndAreaId(); void UpdateIndoorsOutdoorsAuras(); void UpdateTavernRestingState(); static uint32 TeamForRace(uint8 race); uint32 GetTeam() const { return m_team; } TeamId GetTeamId() const { return m_team == ALLIANCE ? TEAM_ALLIANCE : TEAM_HORDE; } void SetFactionForRace(uint8 race); void InitDisplayIds(); bool IsAtGroupRewardDistance(WorldObject const* pRewardSource) const; bool IsAtRecruitAFriendDistance(WorldObject const* pOther) const; void RewardPlayerAndGroupAtKill(Unit* victim, bool isBattleGround); void RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource); bool isHonorOrXPTarget(Unit const* victim) const; bool GetsRecruitAFriendBonus(bool forXP); uint8 GetGrantableLevels() const { return m_grantableLevels; } void SetGrantableLevels(uint8 val) { m_grantableLevels = val; } ReputationMgr& GetReputationMgr() { return *m_reputationMgr; } ReputationMgr const& GetReputationMgr() const { return *m_reputationMgr; } ReputationRank GetReputationRank(uint32 faction_id) const; void RewardOnKill(Unit* victim, float rate); void RewardReputation(Quest const* quest); int32 CalculateReputationGain(ReputationSource source, uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool noQuestBonus = false); void UpdateSkillsForLevel(); void ModifySkillBonus(uint32 skillid, int32 val, bool talent); void SetLastSoulburnSpell(SpellInfo const* spell) { m_lastSoulburnSpell = spell; } SpellInfo const* GetLastSoulburnSpell() const { return m_lastSoulburnSpell; } /*********************************************************/ /*** PVP SYSTEM ***/ /*********************************************************/ // TODO: Properly implement correncies as of Cataclysm void UpdateHonorFields(); bool RewardHonor(Unit* victim, uint32 groupsize, int32 honor = -1, bool pvptoken = false); uint32 GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot) const; // duel health and mana reset methods void SaveHealthBeforeDuel() { healthBeforeDuel = GetHealth(); } void SaveManaBeforeDuel() { manaBeforeDuel = GetPower(POWER_MANA); } void RestoreHealthAfterDuel() { SetHealth(healthBeforeDuel); } void RestoreManaAfterDuel() { SetPower(POWER_MANA, manaBeforeDuel); } //End of PvP System void SetDrunkValue(uint8 newDrunkValue, uint32 itemId = 0); uint8 GetDrunkValue() const { return GetByteValue(PLAYER_BYTES_3, PLAYER_BYTES_3_OFFSET_INEBRIATION); } static DrunkenState GetDrunkenstateByValue(uint8 value); uint32 GetDeathTimer() const { return m_deathTimer; } uint32 GetCorpseReclaimDelay(bool pvp) const; void UpdateCorpseReclaimDelay(); int32 CalculateCorpseReclaimDelay(bool load = false) const; void SendCorpseReclaimDelay(uint32 delay) const; uint32 GetBlockPercent() const override { return GetUInt32Value(PLAYER_SHIELD_BLOCK); } bool CanParry() const { return m_canParry; } void SetCanParry(bool value); bool CanBlock() const { return m_canBlock; } void SetCanBlock(bool value); bool CanTitanGrip() const { return m_canTitanGrip; } void SetCanTitanGrip(bool value, uint32 penaltySpellId = 0); void CheckTitanGripPenalty(); bool CanTameExoticPets() const { return IsGameMaster() || HasAuraType(SPELL_AURA_ALLOW_TAME_PET_TYPE); } void SetRegularAttackTime(); void HandleBaseModFlatValue(BaseModGroup modGroup, float amount, bool apply); void ApplyBaseModPctValue(BaseModGroup modGroup, float pct); void SetBaseModFlatValue(BaseModGroup modGroup, float val); void SetBaseModPctValue(BaseModGroup modGroup, float val); void UpdateDamageDoneMods(WeaponAttackType attackType, int32 skipEnchantSlot = -1) override; void UpdateBaseModGroup(BaseModGroup modGroup); float GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const; float GetTotalBaseModValue(BaseModGroup modGroup) const; void _ApplyAllStatBonuses(); void _RemoveAllStatBonuses(); void ResetAllPowers(); SpellSchoolMask GetMeleeDamageSchoolMask(WeaponAttackType attackType = BASE_ATTACK) const override; void CastAllObtainSpells(); void ApplyItemObtainSpells(Item* item, bool apply); void UpdateWeaponDependentCritAuras(WeaponAttackType attackType); void UpdateAllWeaponDependentCritAuras(); void UpdateWeaponDependentAuras(WeaponAttackType attackType); void ApplyItemDependentAuras(Item* item, bool apply); bool CheckAttackFitToAuraRequirement(WeaponAttackType attackType, AuraEffect const* aurEff) const override; void _ApplyItemMods(Item* item, uint8 slot, bool apply, bool updateItemAuras = true); void _RemoveAllItemMods(); void _ApplyAllItemMods(); void _ApplyAllLevelScaleItemMods(bool apply); ScalingStatDistributionEntry const* GetScalingStatDistributionFor(ItemTemplate const& itemTemplate) const; ScalingStatValuesEntry const* GetScalingStatValuesFor(ItemTemplate const& itemTemplate) const; void _ApplyItemBonuses(ItemTemplate const* proto, uint8 slot, bool apply, bool only_level_scale = false); void _ApplyWeaponDamage(uint8 slot, ItemTemplate const* proto, bool apply); bool EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot) const; void ToggleMetaGemsActive(uint8 exceptslot, bool apply); void CorrectMetaGemEnchants(uint8 slot, bool apply); void InitDataForForm(bool reapplyMods = false); void ApplyItemEquipSpell(Item* item, bool apply, bool form_change = false); void ApplyEquipSpell(SpellInfo const* spellInfo, Item* item, bool apply, bool form_change = false); void UpdateEquipSpellsAtFormChange(); void CastItemCombatSpell(DamageInfo const& damageInfo); void CastItemCombatSpell(DamageInfo const& damageInfo, Item* item, ItemTemplate const* proto); void CastItemUseSpell(Item* item, SpellCastTargets const& targets, uint8 castId, uint32 glyphIndex); void SendEquipmentSetList(); void SetEquipmentSet(EquipmentSetInfo::EquipmentSetData const& eqset); void DeleteEquipmentSet(uint64 setGuid); void SendInitWorldStates(uint32 zone, uint32 area); void SendUpdateWorldState(uint32 variable, uint32 value, bool hidden = false) const; void SendDirectMessage(WorldPacket const* data) const; void SendAurasForTarget(Unit* target) const; std::unique_ptr<PlayerMenu> PlayerTalkClass; std::vector<std::unique_ptr<ItemSetEffect>> ItemSetEff; void SendLoot(ObjectGuid guid, LootType loot_type); void SendLootError(ObjectGuid guid, LootError error) const; void SendLootRelease(ObjectGuid guid) const; void SendNotifyLootItemRemoved(uint8 lootSlot) const; void SendNotifyCurrencyLootRemoved(uint8 lootSlot); void SendNotifyLootMoneyRemoved() const; /*********************************************************/ /*** BATTLEGROUND SYSTEM ***/ /*********************************************************/ bool InBattleground() const { return m_bgData.bgInstanceID != 0; } bool InArena() const; uint32 GetBattlegroundId() const { return m_bgData.bgInstanceID; } BattlegroundTypeId GetBattlegroundTypeId() const { return m_bgData.bgTypeID; } Battleground* GetBattleground() const; uint32 GetBattlegroundQueueJoinTime(uint32 bgTypeId) const; void AddBattlegroundQueueJoinTime(uint32 bgTypeId, uint32 joinTime); void RemoveBattlegroundQueueJoinTime(uint32 bgTypeId); bool InBattlegroundQueue() const; BattlegroundQueueTypeId GetBattlegroundQueueTypeId(uint32 index) const; uint32 GetBattlegroundQueueIndex(BattlegroundQueueTypeId bgQueueTypeId) const; bool IsInvitedForBattlegroundQueueType(BattlegroundQueueTypeId bgQueueTypeId) const; bool InBattlegroundQueueForBattlegroundQueueType(BattlegroundQueueTypeId bgQueueTypeId) const; void SetBattlegroundId(uint32 val, BattlegroundTypeId bgTypeId); uint32 AddBattlegroundQueueId(BattlegroundQueueTypeId val); bool HasFreeBattlegroundQueueId() const; void RemoveBattlegroundQueueId(BattlegroundQueueTypeId val); void SetInviteForBattlegroundQueueType(BattlegroundQueueTypeId bgQueueTypeId, uint32 instanceId); bool IsInvitedForBattlegroundInstance(uint32 instanceId) const; WorldLocation const& GetBattlegroundEntryPoint() const { return m_bgData.joinPos; } void SetBattlegroundEntryPoint(); void SetBGTeam(uint32 team); uint32 GetBGTeam() const; void LeaveBattleground(bool teleportToEntryPoint = true); bool CanJoinToBattleground(Battleground const* bg) const; bool CanReportAfkDueToLimit(); void ReportedAfkBy(Player* reporter); void ClearAfkReports() { m_bgData.bgAfkReporter.clear(); } bool GetBGAccessByLevel(BattlegroundTypeId bgTypeId) const; bool isTotalImmunity() const; bool CanUseBattlegroundObject(GameObject* gameobject) const; bool isTotalImmune() const; bool CanCaptureTowerPoint() const; bool GetRandomWinner() const { return m_IsBGRandomWinner; } void SetRandomWinner(bool isWinner); /*********************************************************/ /*** OUTDOOR PVP SYSTEM ***/ /*********************************************************/ OutdoorPvP* GetOutdoorPvP() const; // returns true if the player is in active state for outdoor pvp objective capturing, false otherwise bool IsOutdoorPvPActive() const; /*********************************************************/ /*** ENVIROMENTAL SYSTEM ***/ /*********************************************************/ bool IsImmuneToEnvironmentalDamage() const; uint32 EnvironmentalDamage(EnviromentalDamage type, uint32 damage); /*********************************************************/ /*** FLOOD FILTER SYSTEM ***/ /*********************************************************/ struct ChatFloodThrottle { enum Index { REGULAR = 0, ADDON = 1, MAX }; time_t Time = 0; uint32 Count = 0; }; void UpdateSpeakTime(ChatFloodThrottle::Index index); /*********************************************************/ /*** VARIOUS SYSTEMS ***/ /*********************************************************/ void UpdateFallInformationIfNeed(MovementInfo const& minfo, uint16 opcode); WorldObject* m_seer; void SetFallInformation(uint32 time, float z); void HandleFall(MovementInfo const& movementInfo); bool SetDisableGravity(bool disable, bool updateAnimTier = true) override; bool SetCanFly(bool enable) override; bool SetCanTransitionBetweenSwimAndFly(bool enable) override; void SendMovementSetCollisionHeight(float height, UpdateCollisionHeightReason reason); void SetClientControl(Unit* target, bool allowMove); void SetSeer(WorldObject* target) { m_seer = target; } void SetViewpoint(WorldObject* target, bool apply); WorldObject* GetViewpoint() const; void StopCastingCharm(); void StopCastingBindSight() const; uint32 GetSaveTimer() const { return m_nextSave; } void SetSaveTimer(uint32 timer) { m_nextSave = timer; } void SaveRecallPosition() { m_recall_location.WorldRelocate(*this); m_recall_instanceId = GetInstanceId(); } void Recall() { TeleportTo(m_recall_location, TELE_TO_NONE, m_recall_instanceId); } void SetHomebind(WorldLocation const& loc, uint32 areaId); void SendBindPointUpdate() const; // Homebind coordinates uint32 m_homebindMapId; uint16 m_homebindAreaId; float m_homebindX; float m_homebindY; float m_homebindZ; WorldLocation GetStartPosition() const; // currently visible objects at player client GuidUnorderedSet m_clientGUIDs; GuidUnorderedSet m_visibleTransports; bool HaveAtClient(Object const* u) const; bool IsNeverVisible() const override; bool IsVisibleGloballyFor(Player const* player) const; void SendInitialVisiblePackets(Unit* target) const; void UpdateObjectVisibility(bool forced = true) override; void UpdateVisibilityForPlayer(); void UpdateVisibilityOf(WorldObject* target); void UpdateTriggerVisibility(); template<class T> void UpdateVisibilityOf(T* target, UpdateData& data, std::set<Unit*>& visibleNow); uint8 m_forced_speed_changes[MAX_MOVE_TYPE]; bool HasAtLoginFlag(AtLoginFlags f) const { return (m_atLoginFlags & f) != 0; } void SetAtLoginFlag(AtLoginFlags f) { m_atLoginFlags |= f; } void RemoveAtLoginFlag(AtLoginFlags flags, bool persist = false); bool isUsingLfg() const; bool inRandomLfgDungeon() const; void GetLFGLeavePoint(Position* pos); bool HasValidLFGLeavePoint(uint32 mapid); void SetLFGLeavePoint(); // Temporarily removed pet cache uint32 GetTemporaryUnsummonedPetNumber() const { return m_temporaryUnsummonedPetNumber; } void SetTemporaryUnsummonedPetNumber(uint32 petnumber) { m_temporaryUnsummonedPetNumber = petnumber; } void UnsummonPetTemporaryIfAny(); void ResummonPetTemporaryUnSummonedIfAny(); bool IsPetNeedBeTemporaryUnsummoned() const; void SendCinematicStart(uint32 cinematicId); void SendMovieStart(uint32 movieId); uint32 DoRandomRoll(uint32 minimum, uint32 maximum); /*********************************************************/ /*** INSTANCE SYSTEM ***/ /*********************************************************/ typedef std::unordered_map< uint32 /*mapId*/, InstancePlayerBind > BoundInstancesMap; void UpdateHomebindTime(uint32 time); uint32 m_HomebindTimer; bool m_InstanceValid; // permanent binds and solo binds by difficulty BoundInstancesMap m_boundInstances[MAX_DIFFICULTY]; InstancePlayerBind* GetBoundInstance(uint32 mapid, Difficulty difficulty, bool withExpired = false); InstancePlayerBind const* GetBoundInstance(uint32 mapid, Difficulty difficulty, bool withExpired = false) const; BoundInstancesMap& GetBoundInstances(Difficulty difficulty) { return m_boundInstances[difficulty]; } InstanceSave* GetInstanceSave(uint32 mapid, bool raid); void UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload = false); void UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload = false); InstancePlayerBind* BindToInstance(InstanceSave* save, bool permanent, BindExtensionState extendState = EXTEND_STATE_NORMAL, bool load = false); void BindToInstance(); void SetPendingBind(uint32 instanceId, uint32 bindTimer); bool HasPendingBind() const { return _pendingBindId > 0; } void SendRaidInfo(); void SendSavedInstances(); bool Satisfy(AccessRequirement const* ar, uint32 target_map, bool report = false); bool CheckInstanceValidity(bool /*isLogin*/); bool CheckInstanceCount(uint32 instanceId) const; void AddInstanceEnterTime(uint32 instanceId, time_t enterTime); // last used pet number (for BG's) uint32 GetLastPetNumber() const { return m_lastpetnumber; } void SetLastPetNumber(uint32 petnumber) { m_lastpetnumber = petnumber; } /*********************************************************/ /*** GROUP SYSTEM ***/ /*********************************************************/ bool IsInGroup(ObjectGuid groupGuid) const; Group* GetGroupInvite() const { return m_groupInvite; } void SetGroupInvite(Group* group) { m_groupInvite = group; } Group* GetGroup() { return m_group.getTarget(); } Group const* GetGroup() const { return const_cast<Group const*>(m_group.getTarget()); } GroupReference& GetGroupRef() { return m_group; } void SetGroup(Group* group, int8 subgroup = -1); uint8 GetSubGroup() const { return m_group.getSubGroup(); } uint32 GetGroupUpdateFlag() const { return m_groupUpdateMask; } void SetGroupUpdateFlag(uint32 flag) { m_groupUpdateMask |= flag; } uint64 GetAuraUpdateMaskForRaid() const { return m_auraRaidUpdateMask; } void SetAuraUpdateMaskForRaid(uint8 slot) { m_auraRaidUpdateMask |= (uint64(1) << slot); } Player* GetNextRandomRaidMember(float radius); PartyResult CanUninviteFromGroup(ObjectGuid guidMember = ObjectGuid::Empty) const; // Battleground / Battlefield Group System void SetBattlegroundOrBattlefieldRaid(Group* group, int8 subgroup = -1); void RemoveFromBattlegroundOrBattlefieldRaid(); Group* GetOriginalGroup() const { return m_originalGroup.getTarget(); } GroupReference& GetOriginalGroupRef() { return m_originalGroup; } uint8 GetOriginalSubGroup() const { return m_originalGroup.getSubGroup(); } void SetOriginalGroup(Group* group, int8 subgroup = -1); void SetPassOnGroupLoot(bool bPassOnGroupLoot) { m_bPassOnGroupLoot = bPassOnGroupLoot; } bool GetPassOnGroupLoot() const { return m_bPassOnGroupLoot; } MapReference &GetMapRef() { return m_mapRef; } // Set map to player and add reference void SetMap(Map* map) override; void ResetMap() override; bool isAllowedToLoot(Creature const* creature); DeclinedName const* GetDeclinedNames() const { return m_declinedname.get(); } // Runes uint8 GetRunesState() const { return m_runes->RuneState; } RuneType GetBaseRune(uint8 index) const { return RuneType(m_runes->_Runes[index].BaseRune); } RuneType GetCurrentRune(uint8 index) const { return RuneType(m_runes->_Runes[index].CurrentRune); } float GetRuneCooldown(uint8 index) const { return m_runes->_Runes[index].Cooldown; } bool IsRuneFullyDepleted(uint8 index) const; /// <summary> /// Checks if there is a fully depleted rune. A rune is considered fully depleted when it's on cooldown and isn't recovering yet ('waiting' for another rune to finish regenerating) /// </summary> /// <param name="runeType">The kind of base rune that is being checked (Blood, Unholy, Frost). Death Runes are no base rune and can't be checked with this method. Use the underlying base rune instead.</param> /// <returns>true when there is a fully depleted rune</returns> bool HasFullyDepletedRune(RuneType runeType) const; RuneType GetLastUsedRune() { return m_runes->LastUsedRune; } uint8 GetLastUsedRuneMask() { return m_runes->LastUsedRuneMask; } void ClearLastUsedRuneMask() { m_runes->LastUsedRuneMask = 0; } void SetLastUsedRune(RuneType type) { m_runes->LastUsedRune = type; } void SetLastUsedRuneIndex(uint8 index) { m_runes->LastUsedRuneMask |= (1 << index); } void SetBaseRune(uint8 index, RuneType baseRune) { m_runes->_Runes[index].BaseRune = baseRune; } void SetCurrentRune(uint8 index, RuneType currentRune) { m_runes->_Runes[index].CurrentRune = currentRune; } void SetRuneConvertAura(uint8 index, AuraEffect const* aura, AuraType auraType, SpellInfo const* spellInfo); void AddRuneByAuraEffect(uint8 index, RuneType newType, AuraEffect const* aura, AuraType auraType, SpellInfo const* spellInfo); void SetRuneCooldown(uint8 index, float cooldown); void RemoveRunesByAuraEffect(AuraEffect const* aura); void RestoreBaseRune(uint8 index); void ConvertRune(uint8 index, RuneType newType); void SendConvertedRunes(); void ResyncRunes() const; void AddRunePower(uint8 mask) const; void InitRunes(); void SendRespondInspectAchievements(Player* player) const; uint32 GetAchievementPoints() const; bool HasAchieved(uint32 achievementId) const; void ResetAchievements(); void FailAchievementCriteria(AchievementCriteriaFailEvent condition, int32 failAsset); void UpdateAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1 = 0, uint64 miscValue2 = 0, uint64 miscValue3 = 0, WorldObject* ref = nullptr, GameObject* go = nullptr); void StartAchievementCriteria(AchievementCriteriaStartEvent startEvent, uint32 entry, Milliseconds timeLost = Milliseconds::zero()); void CompletedAchievement(AchievementEntry const* entry); bool HasTitle(uint32 bitIndex) const; bool HasTitle(CharTitlesEntry const* title) const; void SetTitle(CharTitlesEntry const* title, bool lost = false); //bool isActiveObject() const { return true; } bool CanSeeSpellClickOn(Creature const* creature) const; uint32 GetChampioningFaction() const { return m_ChampioningFaction; } void SetChampioningFaction(uint32 faction) { m_ChampioningFaction = faction; } uint8 GetExpansionForFaction(uint32 factionId) const; Spell* m_spellModTakingSpell; float GetAverageItemLevel() const; bool isDebugAreaTriggers; void ClearWhisperWhiteList() { WhisperList.clear(); } void AddWhisperWhiteList(ObjectGuid guid) { WhisperList.push_back(guid); } bool IsInWhisperWhiteList(ObjectGuid guid); void RemoveFromWhisperWhiteList(ObjectGuid guid) { WhisperList.remove(guid); } void ReadMovementInfo(WorldPacket& data, MovementInfo* mi, Movement::ExtraMovementStatusElement* extras = nullptr); /*! These methods send different packets to the client in apply and unapply case. These methods are only sent to the current unit. */ void ValidateMovementInfo(MovementInfo* mi); bool CanFly() const override { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_CAN_FLY); } bool CanEnterWater() const override { return true; } std::string GetMapAreaAndZoneString() const; std::string GetCoordsMapAreaAndZoneString() const; // Void Storage bool IsVoidStorageUnlocked() const { return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_VOID_UNLOCKED); } void UnlockVoidStorage() { SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_VOID_UNLOCKED); } void LockVoidStorage() { RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_VOID_UNLOCKED); } uint8 GetNextVoidStorageFreeSlot() const; uint8 GetNumOfVoidStorageFreeSlots() const; uint8 AddVoidStorageItem(VoidStorageItem const& item); void AddVoidStorageItemAtSlot(uint8 slot, const VoidStorageItem& item); void DeleteVoidStorageItem(uint8 slot); bool SwapVoidStorageItem(uint8 oldSlot, uint8 newSlot); VoidStorageItem* GetVoidStorageItem(uint8 slot) const; VoidStorageItem* GetVoidStorageItem(uint64 id, uint8& slot) const; // Pets PlayerPetData* GetPlayerPetDataById(uint32 petId); PlayerPetData* GetPlayerPetDataBySlot(uint8 slot); PlayerPetData* GetPlayerPetDataByCreatureId(uint32 creatureId); PlayerPetData* GetPlayerPetDataCurrent(); Optional<uint8> GetFirstUnusedActivePetSlot(); Optional<uint8> GetFirstUnusedPetSlot(); void DeleteFromPlayerPetDataStore(uint32 petNumber); void AddToPlayerPetDataStore(std::unique_ptr<PlayerPetData> playerPetData); protected: // Gamemaster whisper whitelist GuidList WhisperList; uint32 m_contestedPvPTimer; /*********************************************************/ /*** BATTLEGROUND SYSTEM ***/ /*********************************************************/ /* this is an array of BG queues (BgTypeIDs) in which is player */ struct BgBattlegroundQueueID_Rec { BattlegroundQueueTypeId bgQueueTypeId; uint32 invitedToInstance; }; BgBattlegroundQueueID_Rec m_bgBattlegroundQueueID[PLAYER_MAX_BATTLEGROUND_QUEUES]; BGData m_bgData; bool m_IsBGRandomWinner; /*********************************************************/ /*** QUEST SYSTEM ***/ /*********************************************************/ //We allow only one timed quest active at the same time. Below can then be simple value instead of set. typedef std::set<uint32> QuestSet; typedef std::unordered_map<uint32, time_t> SeasonalQuestMapByQuest; typedef std::unordered_map<uint32, SeasonalQuestMapByQuest> SeasonalQuestMapByEvent; struct LFGRewardInfo { LFGRewardInfo(uint8 _completionsThisPeriod = 0, bool _isDaily = false) : CompletionsThisPeriod(_completionsThisPeriod), IsDaily(_isDaily) { } uint8 CompletionsThisPeriod; bool IsDaily; }; typedef std::unordered_map<uint32, LFGRewardInfo> LFGRewardStatusMap; QuestSet m_timedquests; QuestSet m_weeklyquests; QuestSet m_monthlyquests; SeasonalQuestMapByEvent m_seasonalquests; LFGRewardStatusMap m_lfgrewardstatus; ObjectGuid m_playerSharingQuest; uint32 m_sharedQuestId; uint32 m_popupQuestId; uint32 m_ingametime; /*********************************************************/ /*** LOAD SYSTEM ***/ /*********************************************************/ void _LoadActions(PreparedQueryResult result); void _LoadAuras(PreparedQueryResult result, uint32 timediff); void _LoadGlyphAuras(); void _LoadBoundInstances(PreparedQueryResult result); void _LoadInventory(PreparedQueryResult result, uint32 timeDiff); void _LoadVoidStorage(PreparedQueryResult result); void _LoadMail(PreparedQueryResult mailsResult, PreparedQueryResult mailItemsResult); static Item* _LoadMailedItem(ObjectGuid const& playerGuid, Player* player, uint32 mailId, Mail* mail, Field* fields); void _LoadQuestStatus(PreparedQueryResult result); void _LoadQuestStatusRewarded(PreparedQueryResult result); void _LoadDailyQuestStatus(PreparedQueryResult result); void _LoadWeeklyQuestStatus(PreparedQueryResult result); void _LoadMonthlyQuestStatus(PreparedQueryResult result); void _LoadSeasonalQuestStatus(PreparedQueryResult result); void _LoadRandomBGStatus(PreparedQueryResult result); void _LoadGroup(PreparedQueryResult result); void _LoadSkills(PreparedQueryResult result); void _LoadSpells(PreparedQueryResult result); bool _LoadHomeBind(PreparedQueryResult result); void _LoadDeclinedNames(PreparedQueryResult result); void _LoadArenaTeamInfo(PreparedQueryResult result); void _LoadEquipmentSets(PreparedQueryResult result); void _LoadBGData(PreparedQueryResult result); void _LoadGlyphs(PreparedQueryResult result); void _LoadTalents(PreparedQueryResult result); void _LoadInstanceTimeRestrictions(PreparedQueryResult result); void _LoadCurrency(PreparedQueryResult result); void _LoadCUFProfiles(PreparedQueryResult result); void _LoadLFGRewardStatus(PreparedQueryResult result); /*********************************************************/ /*** SAVE SYSTEM ***/ /*********************************************************/ void _SaveActions(CharacterDatabaseTransaction& trans); void _SaveAuras(CharacterDatabaseTransaction& trans); void _SaveInventory(CharacterDatabaseTransaction& trans); void _SaveVoidStorage(CharacterDatabaseTransaction& trans); void _SaveMail(CharacterDatabaseTransaction& trans); void _SaveQuestStatus(CharacterDatabaseTransaction& trans); void _SaveDailyQuestStatus(CharacterDatabaseTransaction& trans); void _SaveWeeklyQuestStatus(CharacterDatabaseTransaction& trans); void _SaveMonthlyQuestStatus(CharacterDatabaseTransaction& trans); void _SaveSeasonalQuestStatus(CharacterDatabaseTransaction& trans); void _SaveSkills(CharacterDatabaseTransaction& trans); void _SaveSpells(CharacterDatabaseTransaction& trans); void _SaveEquipmentSets(CharacterDatabaseTransaction& trans); void _SaveBGData(CharacterDatabaseTransaction& trans); void _SaveGlyphs(CharacterDatabaseTransaction& trans) const; void _SaveTalents(CharacterDatabaseTransaction& trans); void _SaveStats(CharacterDatabaseTransaction& trans) const; void _SaveInstanceTimeRestrictions(CharacterDatabaseTransaction& trans); void _SaveCurrency(CharacterDatabaseTransaction& trans); void _SaveCUFProfiles(CharacterDatabaseTransaction& trans); void _SaveLFGRewardStatus(CharacterDatabaseTransaction& trans); /*********************************************************/ /*** ENVIRONMENTAL SYSTEM ***/ /*********************************************************/ void HandleSobering(); void SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen); void StopMirrorTimer(MirrorTimerType Type); void HandleDrowning(uint32 time_diff); int32 getMaxTimer(MirrorTimerType timer) const; /*********************************************************/ /*** HONOR SYSTEM ***/ /*********************************************************/ time_t m_lastHonorUpdateTime; void outDebugValues() const; ObjectGuid m_lootGuid; uint32 m_team; uint32 m_nextSave; std::array<ChatFloodThrottle, ChatFloodThrottle::MAX> m_chatFloodData; Difficulty m_dungeonDifficulty; Difficulty m_raidDifficulty; Difficulty m_raidMapDifficulty; uint32 m_atLoginFlags; std::array<Item*, PLAYER_SLOTS_COUNT> m_items; uint32 m_currentBuybackSlot; PlayerCurrenciesMap _currencyStorage; /** * @name GetCurrencyWeekCap * @brief return week cap for selected currency * @param CurrencyTypesEntry for which to retrieve weekly cap */ uint32 GetCurrencyWeekCap(CurrencyTypesEntry const* currency) const; /* * @name GetCurrencyTotalCap * @brief return total cap for selected currency * @param CurrencyTypesEntry for which to retrieve total cap */ uint32 GetCurrencyTotalCap(CurrencyTypesEntry const* currency) const; /// Updates weekly conquest point cap (dynamic cap) void UpdateConquestCurrencyCap(uint32 currency); std::array<std::unique_ptr<VoidStorageItem>, VOID_STORAGE_MAX_SLOT> _voidStorageItems; std::vector<Item*> m_itemUpdateQueue; bool m_itemUpdateQueueBlocked; uint32 m_ExtraFlags; QuestStatusMap m_QuestStatus; QuestStatusSaveMap m_QuestStatusSave; RewardedQuestSet m_RewardedQuests; QuestStatusSaveMap m_RewardedQuestsSave; SkillStatusMap mSkillStatus; uint32 m_GuildIdInvited; uint32 m_ArenaTeamIdInvited; PlayerMails m_mail; PlayerSpellMap m_spells; uint32 m_lastPotionId; // last used health/mana potion in combat, that block next potion use std::unique_ptr<PlayerTalentInfo> _talentMgr; ActionButtonList m_actionButtons; std::array<float, BASEMOD_END> m_auraBaseFlatMod; std::array<float, BASEMOD_END> m_auraBasePctMod; std::array<int16, MAX_COMBAT_RATING> m_baseRatingValue; uint32 m_baseSpellPower; uint32 m_baseManaRegen; uint32 m_baseHealthRegen; int32 m_spellPenetrationItemMod; SpellModContainer m_spellMods; EnchantDurationList m_enchantDuration; ItemDurationList m_itemDuration; GuidUnorderedSet m_itemSoulboundTradeable; std::unique_ptr<ResurrectionData> _resurrectionData; WorldSession* m_session; JoinedChannelsList m_channels; uint8 m_cinematic; uint32 m_movie; TradeData* m_trade; bool m_DailyQuestChanged; bool m_WeeklyQuestChanged; bool m_MonthlyQuestChanged; bool m_SeasonalQuestChanged; bool m_LFGRewardStatusChanged; time_t m_lastDailyQuestTime; uint32 m_hostileReferenceCheckTimer; uint32 m_drunkTimer; uint32 m_weaponChangeTimer; uint32 m_zoneUpdateId; uint32 m_areaUpdateId; uint32 m_deathTimer; time_t m_deathExpireTime; uint32 m_WeaponProficiency; uint32 m_ArmorProficiency; bool m_canParry; bool m_canBlock; bool m_canTitanGrip; uint32 m_titanGripPenaltySpellId; uint8 m_swingErrorMsg; ////////////////////Rest System///////////////////// time_t _restTime; uint32 inn_triggerId; float m_rest_bonus; uint32 _restFlagMask; ////////////////////Rest System///////////////////// // Social PlayerSocial* m_social; // Groups GroupReference m_group; GroupReference m_originalGroup; Group* m_groupInvite; uint32 m_groupUpdateMask; uint64 m_auraRaidUpdateMask; bool m_bPassOnGroupLoot; // last used pet number (for BG's) uint32 m_lastpetnumber; // Player summoning time_t m_summon_expire; WorldLocation m_summon_location; uint32 m_summon_instanceId; // Recall position WorldLocation m_recall_location; uint32 m_recall_instanceId; std::unique_ptr<DeclinedName> m_declinedname; std::unique_ptr<Runes> m_runes; EquipmentSetContainer _equipmentSets; bool CanAlwaysSee(WorldObject const* obj) const override; bool IsAlwaysDetectableFor(WorldObject const* seer) const override; uint8 m_grantableLevels; uint8 m_fishingSteps; bool m_needsZoneUpdate; std::array<std::unique_ptr<CUFProfile>, MAX_CUF_PROFILES> _CUFProfiles; SpellInfo const* m_lastSoulburnSpell; private: // internal common parts for CanStore/StoreItem functions InventoryResult CanStoreItem_InSpecificSlot(uint8 bag, uint8 slot, ItemPosCountVec& dest, ItemTemplate const* pProto, uint32& count, bool swap, Item* pSrcItem) const; InventoryResult CanStoreItem_InBag(uint8 bag, ItemPosCountVec& dest, ItemTemplate const* pProto, uint32& count, bool merge, bool non_specialized, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot) const; InventoryResult CanStoreItem_InInventorySlots(uint8 slot_begin, uint8 slot_end, ItemPosCountVec& dest, ItemTemplate const* pProto, uint32& count, bool merge, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot) const; Item* _StoreItem(uint16 pos, Item* pItem, uint32 count, bool clone, bool update); Item* _LoadItem(CharacterDatabaseTransaction& trans, uint32 zoneId, uint32 timeDiff, Field* fields); std::unique_ptr<CinematicMgr> _cinematicMgr; GuidSet m_refundableItems; void SendRefundInfo(Item* item); void RefundItem(Item* item); void SendItemRefundResult(Item* item, ItemExtendedCostEntry const* iece, uint8 error); // know currencies are not removed at any point (0 displayed) void AddKnownCurrency(uint32 itemId); void AdjustQuestReqItemCount(Quest const* quest, QuestStatusData& questStatusData); bool IsCanDelayTeleport() const { return m_bCanDelayTeleport; } void SetCanDelayTeleport(bool setting) { m_bCanDelayTeleport = setting; } bool IsHasDelayedTeleport() const { return m_bHasDelayedTeleport; } void SetDelayedTeleportFlag(bool setting) { m_bHasDelayedTeleport = setting; } void ScheduleDelayedOperation(uint32 operation) { if (operation < DELAYED_END) m_DelayedOperations |= operation; } bool IsInstanceLoginGameMasterException() const; MapReference m_mapRef; uint32 m_lastFallTime; float m_lastFallZ; std::array<int32, MAX_TIMERS> m_MirrorTimer; uint8 m_MirrorTimerFlags; uint8 m_MirrorTimerFlagsLast; // Rune type / Rune timer std::array<uint32, MAX_RUNES> m_runeGraceCooldown; std::array<uint32, MAX_RUNES> m_lastRuneGraceTimers; // Current teleport data WorldLocation m_teleport_dest; Optional<uint32> m_teleport_instanceId; TeleportToOptions m_teleport_options; bool mSemaphoreTeleport_Near; bool mSemaphoreTeleport_Far; uint32 m_DelayedOperations; bool m_bCanDelayTeleport; bool m_bHasDelayedTeleport; // Temporary removed pet cache uint32 m_temporaryUnsummonedPetNumber; uint32 m_oldpetspell; std::unique_ptr<AchievementMgr<Player>> m_achievementMgr; std::unique_ptr<ReputationMgr> m_reputationMgr; uint32 m_ChampioningFaction; InstanceTimeMap _instanceResetTimes; uint32 _pendingBindId; uint32 _pendingBindTimer; uint32 _activeCheats; uint32 _maxPersonalArenaRate; bool _hasValidLFGLeavePoint; // variables to save health and mana before duel and restore them after duel uint32 healthBeforeDuel; uint32 manaBeforeDuel; WorldLocation _corpseLocation; std::unique_ptr<Archaeology> _archaeology; std::vector<std::unique_ptr<PlayerPetData>> PlayerPetDataStore; TimeTrackerSmall m_petScalingSynchTimer; }; TC_GAME_API void AddItemsSetItem(Player* player, Item* item); TC_GAME_API void RemoveItemsSetItem(Player* player, ItemTemplate const* proto); #endif
1
0.973321
1
0.973321
game-dev
MEDIA
0.952845
game-dev
0.954318
1
0.954318
open-gunz/ogz-source
1,756
src/sdk/bullet/include/BulletDynamics/Featherstone/btMultiBodyJointLimitConstraint.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2013 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_MULTIBODY_JOINT_LIMIT_CONSTRAINT_H #define BT_MULTIBODY_JOINT_LIMIT_CONSTRAINT_H #include "btMultiBodyConstraint.h" struct btSolverInfo; class btMultiBodyJointLimitConstraint : public btMultiBodyConstraint { protected: btScalar m_lowerBound; btScalar m_upperBound; public: btMultiBodyJointLimitConstraint(btMultiBody* body, int link, btScalar lower, btScalar upper); virtual ~btMultiBodyJointLimitConstraint(); virtual void finalizeMultiDof(); virtual int getIslandIdA() const; virtual int getIslandIdB() const; virtual void createConstraintRows(btMultiBodyConstraintArray& constraintRows, btMultiBodyJacobianData& data, const btContactSolverInfo& infoGlobal); virtual void debugDraw(class btIDebugDraw* drawer) { //todo(erwincoumans) } }; #endif //BT_MULTIBODY_JOINT_LIMIT_CONSTRAINT_H
1
0.794625
1
0.794625
game-dev
MEDIA
0.972706
game-dev
0.663299
1
0.663299
houstudio/cdroid
6,571
src/gui/core/looper.h
/********************************************************************************* * Copyright (C) [2019] [houzh@msn.com] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *********************************************************************************/ #ifndef __ALOOPER_H__ #define __ALOOPER_H__ #include <unordered_map> #include <vector> #include <mutex> #include <list> #include <cstdint> #include <core/callbackbase.h> namespace cdroid{ typedef int64_t nsecs_t; typedef int (*Looper_callbackFunc)(int fd, int events, void* data); struct Message{ int what; int arg1; int arg2; int flags; void*obj; Runnable callback; class Handler*target; public: Message(int what=0); }; class LooperCallback{ protected: virtual ~LooperCallback(); public: virtual int handleEvent(int fd, int events, void* data) = 0; }; class MessageHandler{ private: uint32_t mFlags; friend class Looper; protected: MessageHandler(); void setOwned(bool looper); virtual ~MessageHandler(); public: virtual void dispatchMessage(Message&); virtual void handleMessage(Message& message)=0; virtual void handleIdle(); }; class EventHandler{ protected: uint32_t mFlags; friend class Looper; protected: EventHandler(); virtual ~EventHandler(); void setOwned(bool looper); public: virtual int checkEvents()=0; virtual int handleEvents()=0; }; class Looper{ private: using SequenceNumber = uint64_t; struct Request { int fd; int ident; int events; LooperCallback* callback1; Looper_callbackFunc callback2; void* data; }; struct Response { SequenceNumber seq; int events; Request request; }; struct MessageEnvelope { MessageEnvelope() : uptime(0),handler(nullptr){} MessageEnvelope(nsecs_t u, MessageHandler* h, const Message& m) : uptime(u), handler(h), message(m) { } nsecs_t uptime; MessageHandler* handler; Message message; }; int mWakeEventFd;// immutable std::recursive_mutex mLock; std::list<MessageEnvelope> mMessageEnvelopes; // guarded by mLock std::list<MessageHandler*>mHandlers; std::list<EventHandler*> mEventHandlers; // Whether we are currently waiting for work. Not protected by a lock, // any use of it is racy anyway. bool mPolling; bool mSendingMessage; // guarded by mLock bool mAllowNonCallbacks; // immutable bool mEpollRebuildRequired; // guarded by mLock class IOEventProcessor* mEpoll; //int mEpollFd;// guarded by mLock but only modified on the looper thread // Locked list of file descriptor monitoring requests. std::unordered_map<SequenceNumber, Request> mRequests; //guarded by mLock std::unordered_map<int,SequenceNumber>mSequenceNumberByFd; //guarded by mLock SequenceNumber mNextRequestSeq; // This state is only used privately by pollOnce and does not require a lock since // it runs on a single thread. std::vector<Response> mResponses; size_t mResponseIndex; nsecs_t mNextMessageUptime; private: static Looper*sMainLooper; int doEventHandlers(); int pollInner(int timeoutMillis); int removeSequenceNumberLocked(SequenceNumber seq); void awoken(); void pushResponse(int events, const Request& request); void rebuildEpollLocked(); void scheduleEpollRebuildLocked(); int addFd(int fd, int ident, int events,const LooperCallback* callback1,Looper_callbackFunc callback2, void* data); static void initTLSKey(); static void threadDestructor(void*); protected: public: enum { POLL_WAKE = -1, POLL_CALLBACK = -2, POLL_TIMEOUT = -3, POLL_ERROR = -4, }; enum { EVENT_INPUT = 1 << 0, EVENT_OUTPUT = 1 << 1, EVENT_ERROR = 1 << 2, EVENT_HANGUP = 1 << 3, EVENT_INVALID = 1 << 4, }; enum { PREPARE_ALLOW_NON_CALLBACKS = 1<<0 }; public: Looper(bool allowNonCallbacks=false); virtual ~Looper(); [[deprecated("This function is deprecated, please use myLooper() or getMainLooper() instead.")]] static Looper*getDefault(); static Looper*getMainLooper(); static Looper*myLooper(); static void prepareMainLooper(); static Looper*prepare(int opts); static void setForThread(Looper* looper); static Looper* getForThread(); bool getAllowNonCallbacks() const; int pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData); inline int pollOnce(int timeoutMillis) { return pollOnce(timeoutMillis, NULL, NULL, NULL); } int pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData); inline int pollAll(int timeoutMillis) { return pollAll(timeoutMillis, NULL, NULL, NULL); } void wake(); int addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data); int addFd(int fd, int ident, int events, const LooperCallback* callback, void* data); int removeFd(int fd); void sendMessage(const MessageHandler* handler, const Message& message); void sendMessageDelayed(nsecs_t uptimeDelay, const MessageHandler* handler,const Message& message); void sendMessageAtTime(nsecs_t uptime, const MessageHandler* handler,const Message& message); bool hasMessages(const MessageHandler* handler,int what,void*obj); void removeMessages(const MessageHandler* handler); void removeMessages(const MessageHandler* handler, int what); void removeCallbacks(const MessageHandler* handler,const Runnable& r); bool isPolling() const; void addHandler(MessageHandler*); void removeHandler(MessageHandler*); void addEventHandler(const EventHandler*handler); void removeEventHandler(const EventHandler*handler); }; } #endif
1
0.911047
1
0.911047
game-dev
MEDIA
0.309256
game-dev
0.755651
1
0.755651
OpenXRay/xray-16
7,120
src/xrGame/inventory_upgrade.cpp
//////////////////////////////////////////////////////////////////////////// // Module : inventory_upgrade.cpp // Created : 01.11.2007 // Modified : 27.11.2007 // Author : Evgeniy Sokolov // Description : inventory upgrade class implementation //////////////////////////////////////////////////////////////////////////// #include "pch_script.h" #include "ai_space.h" #include "xrScriptEngine/script_engine.hpp" #include "inventory_upgrade.h" #include "inventory_upgrade_manager.h" #include "inventory_upgrade_group.h" #include "inventory_upgrade_root.h" #include "inventory_upgrade_property.h" namespace inventory { namespace upgrade { Upgrade::Upgrade() {} Upgrade::~Upgrade() {} void Upgrade::construct(const shared_str& upgrade_id, Group& parental_group, Manager& manager_r) { inherited::construct(upgrade_id, manager_r); m_parent_group = &parental_group; // name : StringTable(); icon; description; m_name = StringTable().translate(pSettings->r_string(id(), "name")); m_description = StringTable().translate(pSettings->r_string(id(), "description")); m_icon._set(pSettings->r_string(id(), "icon")); // section -------------------------------------------------------------------------- LPCSTR section_str = pSettings->r_string(id(), "section"); VERIFY2(pSettings->section_exist(section_str), make_string("Upgrade <%s> : settings section [%s] not exist!", id_str(), section_str)); VERIFY2(pSettings->line_count(section_str), make_string("Upgrade <%s> : settings section [%s] is empty !", id_str(), section_str)); m_section._set(section_str); // precondition_functor LPCSTR precondition_functor_str = pSettings->r_string(id(), "precondition_functor"); m_preconditions.parameter = pSettings->r_string(id(), "precondition_parameter"); m_preconditions.parameter2 = m_section.c_str(); R_ASSERT2(GEnv.ScriptEngine->functor(precondition_functor_str, m_preconditions.functr), make_string( "Failed to get precondition functor in section[%s], functor[%s]", id_str(), precondition_functor_str)); m_preconditions(); // effect_functor LPCSTR effect_functor_str = pSettings->r_string(id(), "effect_functor"); m_effects.parameter = pSettings->r_string(id(), "effect_parameter"); m_effects.parameter2 = m_section.c_str(); m_effects.parameter3 = 1; R_ASSERT2(GEnv.ScriptEngine->functor(effect_functor_str, m_effects.functr), make_string("Failed to get effect functor in section[%s], functor[%s]", id_str(), effect_functor_str)); m_effects(); // prereq_functor (1,2) : m_prerequisites, m_tooltip LPCSTR prereq_functor_str = pSettings->r_string(id(), "prereq_functor"); // prerequisites_functor // LPCSTR tooltip_functor_str = pSettings->r_string( id(), "prereq_tooltip_functor" ); m_prerequisites.parameter = pSettings->r_string(id(), "prereq_params"); // prerequisites_params m_prerequisites.parameter2 = m_section.c_str(); // m_tooltip.parameter = pSettings->r_string( id(), "prereq_params" ); R_ASSERT2(GEnv.ScriptEngine->functor(prereq_functor_str, m_prerequisites.functr), make_string("Failed to get prerequisites functor in section[%s], functor[%s]", id_str(), prereq_functor_str)); m_prerequisites(); /*R_ASSERT2( GEnv.ScriptEngine->functor( tooltip_functor_str, m_tooltip.functr ), make_string( "Failed to get tooltip functor in section[%s], functor[%s]", id_str(), tooltip_functor_str ) ); m_tooltip();*/ // effects = groups LPCSTR groups_str = pSettings->r_string(id(), "effects"); if (groups_str) { add_dependent_groups(groups_str, manager_r); } m_known = !!READ_IF_EXISTS(pSettings, r_bool, id(), "known", false); shared_str properties = pSettings->r_string(id(), "property"); VERIFY2(properties.size(), make_string("Upgrade <%s> : property is empty !", id_str())); string256 buffer; for (u8 i = 0; i < max_properties_count; i++) { shared_str prop = _GetItem(properties.c_str(), i, buffer); if (prop.size()) { m_properties[i] = prop; VERIFY2(manager_r.get_property(prop), make_string("Upgrade <%s> : property [%s] is unknown (not found in upgrade manager) !", id_str(), prop.c_str())); } } m_scheme_index.set(-1, -1); m_scheme_index = pSettings->r_ivector2(id(), "scheme_index"); m_highlight = false; } // Upgrade() #ifdef DEBUG void Upgrade::log_hierarchy(LPCSTR nest) { u32 sz = (xr_strlen(nest) + 4) * sizeof(char); PSTR nest2 = (PSTR)xr_alloca(sz); xr_strcpy(nest2, sz, nest); xr_strcat(nest2, sz, " "); Msg("%s<u> %s", nest2, id_str()); inherited::log_hierarchy(nest2); } #endif // DEBUG void Upgrade::fill_root_container(Root* root) { R_ASSERT(root); root->add_upgrade(this); inherited::fill_root_container(root); } enum UpgradeStateResultScript { result_script_ok = 0, // Call of Pripyat meaning result_script_e_cant_do = 1, result_script_e_precondition_any = 2, // Clear Sky meaning result_script_e_precondition_money = 1, result_script_e_precondition_quest = 2, }; UpgradeStateResult Upgrade::can_install(CInventoryItem& item, bool loading) { // If loading data, it was already saved in such state and checked in process of installation. if (loading) { return result_ok; } UpgradeStateResult res = inherited::can_install(item, loading); if (res != result_ok) { return res; } res = m_parent_group->can_install(item, *this, loading); int script_res = m_preconditions(); switch (script_res) { case result_script_ok: return res; case result_script_e_cant_do: if (ClearSkyMode) { if (res != result_ok) return res; return result_e_precondition_money; } return result_e_cant_do; case result_script_e_precondition_any: if (res != result_ok) return res; return result_e_precondition_quest; } return result_ok; } UpgradeStateResult Upgrade::can_add(CInventoryItem& item) { return inherited::can_install(item, false); } bool Upgrade::check_scheme_index(Ivector2 const& scheme_index) { return (m_scheme_index.x == scheme_index.x && m_scheme_index.y == scheme_index.y); } LPCSTR Upgrade::get_prerequisites() { return m_prerequisites(); } void Upgrade::run_effects(bool loading) { m_effects.parameter3 = loading ? 1 : 0; m_effects(); } void Upgrade::set_highlight(bool value) { m_highlight = value; } void Upgrade::highlight_up() { set_highlight(true); Groups_type::iterator ib = m_depended_groups.begin(); Groups_type::iterator ie = m_depended_groups.end(); for (; ib != ie; ++ib) { (*ib)->highlight_up(); } } void Upgrade::highlight_down() { set_highlight(true); m_parent_group->highlight_down(); } } // namespace upgrade } // namespace inventory
1
0.980122
1
0.980122
game-dev
MEDIA
0.574216
game-dev,desktop-app
0.937491
1
0.937491
Darkrp-community/OpenKeep
42,132
code/game/objects/items/toys.dm
/* Toys! * Contains * Balloons * Fake singularity * Toy gun * Toy crossbow * Toy swords * Crayons * Snap pops * Mech prizes * AI core prizes * Toy codex gigas * Skeleton toys * Cards * Toy nuke * Fake meteor * Foam armblade * Toy big red button * Beach ball * Toy xeno * Kitty toys! * Snowballs * Clockwork Watches * Toy Daggers */ /obj/item/toy throwforce = 0 throw_speed = 1 throw_range = 7 force = 0 /* * Balloons */ /obj/item/toy/waterballoon name = "water balloon" desc = "" icon = 'icons/obj/toy.dmi' icon_state = "waterballoon-e" item_state = "balloon-empty" /obj/item/toy/waterballoon/Initialize() . = ..() create_reagents(10) /obj/item/toy/waterballoon/attack(mob/living/carbon/human/M, mob/user) return /obj/item/toy/waterballoon/afterattack(atom/A as mob|obj, mob/user, proximity) . = ..() if(!proximity) return if (istype(A, /obj/structure/reagent_dispensers)) var/obj/structure/reagent_dispensers/RD = A if(RD.reagents.total_volume <= 0) to_chat(user, "<span class='warning'>[RD] is empty.</span>") else if(reagents.total_volume >= 10) to_chat(user, "<span class='warning'>[src] is full.</span>") else A.reagents.trans_to(src, 10, transfered_by = user) to_chat(user, "<span class='notice'>I fill the balloon with the contents of [A].</span>") desc = "" update_icon() /obj/item/toy/waterballoon/attackby(obj/item/I, mob/user, params) if(istype(I, /obj/item/reagent_containers/glass)) if(I.reagents) if(I.reagents.total_volume <= 0) to_chat(user, "<span class='warning'>[I] is empty.</span>") else if(reagents.total_volume >= 10) to_chat(user, "<span class='warning'>[src] is full.</span>") else desc = "" to_chat(user, "<span class='notice'>I fill the balloon with the contents of [I].</span>") I.reagents.trans_to(src, 10, transfered_by = user) update_icon() else if(I.get_sharpness()) balloon_burst() else return ..() /obj/item/toy/waterballoon/throw_impact(atom/hit_atom, datum/thrownthing/throwingdatum) if(!..()) //was it caught by a mob? balloon_burst(hit_atom) /obj/item/toy/waterballoon/proc/balloon_burst(atom/AT) if(reagents.total_volume >= 1) var/turf/T if(AT) T = get_turf(AT) else T = get_turf(src) T.visible_message("<span class='danger'>[src] bursts!</span>","<span class='hear'>I hear a pop and a splash.</span>") reagents.reaction(T) for(var/atom/A in T) reagents.reaction(A) icon_state = "burst" qdel(src) /obj/item/toy/waterballoon/update_icon() if(src.reagents.total_volume >= 1) icon_state = "waterballoon" item_state = "balloon" else icon_state = "waterballoon-e" item_state = "balloon-empty" #define BALLOON_COLORS list("red", "blue", "green", "yellow") /obj/item/toy/balloon name = "balloon" desc = "" icon = 'icons/obj/balloons.dmi' icon_state = "balloon" item_state = "balloon" lefthand_file = 'icons/mob/inhands/balloons_lefthand.dmi' righthand_file = 'icons/mob/inhands/balloons_righthand.dmi' w_class = WEIGHT_CLASS_BULKY throwforce = 0 throw_speed = 1 throw_range = 7 force = 0 var/random_color = TRUE /obj/item/toy/balloon/Initialize(mapload) . = ..() if(random_color) var/chosen_balloon_color = pick(BALLOON_COLORS) name = "[chosen_balloon_color] [name]" icon_state = "[icon_state]_[chosen_balloon_color]" item_state = icon_state /obj/item/toy/balloon/corgi name = "corgi balloon" desc = "" icon_state = "corgi" item_state = "corgi" random_color = FALSE /obj/item/toy/balloon/syndicate name = "syndicate balloon" desc = "" icon_state = "syndballoon" item_state = "syndballoon" random_color = FALSE /obj/item/toy/balloon/syndicate/pickup(mob/user) . = ..() if(user && user.mind && user.mind.has_antag_datum(/datum/antagonist, TRUE)) SEND_SIGNAL(user, COMSIG_ADD_MOOD_EVENT, "badass_antag", /datum/mood_event/badass_antag) /obj/item/toy/balloon/syndicate/dropped(mob/user) if(user) SEND_SIGNAL(user, COMSIG_CLEAR_MOOD_EVENT, "badass_antag", /datum/mood_event/badass_antag) . = ..() /obj/item/toy/balloon/syndicate/Destroy() if(ismob(loc)) var/mob/M = loc SEND_SIGNAL(M, COMSIG_CLEAR_MOOD_EVENT, "badass_antag", /datum/mood_event/badass_antag) . = ..() /* * Fake singularity */ /obj/item/toy/spinningtoy name = "gravitational singularity" desc = "" icon = 'icons/obj/singularity.dmi' icon_state = "singularity_s1" /* * Toy gun: Why isnt this an /obj/item/gun? */ /obj/item/toy/gun name = "cap gun" desc = "" icon = 'icons/obj/guns/projectile.dmi' icon_state = "revolver" item_state = "gun" lefthand_file = 'icons/mob/inhands/weapons/guns_lefthand.dmi' righthand_file = 'icons/mob/inhands/weapons/guns_righthand.dmi' flags_1 = CONDUCT_1 slot_flags = ITEM_SLOT_BELT w_class = WEIGHT_CLASS_NORMAL custom_materials = list(/datum/material/iron=10, /datum/material/glass=10) attack_verb = list("struck", "pistol whipped", "hit", "bashed") var/bullets = 7 /obj/item/toy/gun/examine(mob/user) . = ..() . += "There [bullets == 1 ? "is" : "are"] [bullets] cap\s left." /obj/item/toy/gun/attackby(obj/item/toy/ammo/gun/A, mob/user, params) if(istype(A, /obj/item/toy/ammo/gun)) if (src.bullets >= 7) to_chat(user, "<span class='warning'>It's already fully loaded!</span>") return 1 if (A.amount_left <= 0) to_chat(user, "<span class='warning'>There are no more caps!</span>") return 1 if (A.amount_left < (7 - src.bullets)) src.bullets += A.amount_left to_chat(user, text("<span class='notice'>I reload [] cap\s.</span>", A.amount_left)) A.amount_left = 0 else to_chat(user, text("<span class='notice'>I reload [] cap\s.</span>", 7 - src.bullets)) A.amount_left -= 7 - src.bullets src.bullets = 7 A.update_icon() return 1 else return ..() /obj/item/toy/gun/afterattack(atom/target as mob|obj|turf|area, mob/user, flag) . = ..() if (flag) return if (!user.IsAdvancedToolUser()) to_chat(user, "<span class='warning'>I don't have the dexterity to do this!</span>") return src.add_fingerprint(user) if (src.bullets < 1) user.show_message("<span class='warning'>*click*</span>", MSG_AUDIBLE) playsound(src, 'sound/blank.ogg', 30, TRUE) return playsound(user, 'sound/blank.ogg', 100, TRUE) src.bullets-- user.visible_message("<span class='danger'>[user] fires [src] at [target]!</span>", \ "<span class='danger'>I fire [src] at [target]!</span>", \ "<span class='hear'>I hear a gunshot!</span>") /obj/item/toy/ammo/gun name = "capgun ammo" desc = "" icon = 'icons/obj/ammo.dmi' icon_state = "357OLD-7" w_class = WEIGHT_CLASS_TINY custom_materials = list(/datum/material/iron=10, /datum/material/glass=10) var/amount_left = 7 /obj/item/toy/ammo/gun/update_icon() src.icon_state = text("357OLD-[]", src.amount_left) /obj/item/toy/ammo/gun/examine(mob/user) . = ..() . += "There [amount_left == 1 ? "is" : "are"] [amount_left] cap\s left." /* * Toy swords */ /obj/item/toy/sword name = "toy sword" desc = "" icon = 'icons/obj/transforming_energy.dmi' icon_state = "sword0" item_state = "sword0" lefthand_file = 'icons/mob/inhands/weapons/swords_lefthand.dmi' righthand_file = 'icons/mob/inhands/weapons/swords_righthand.dmi' var/active = 0 w_class = WEIGHT_CLASS_SMALL attack_verb = list("attacked", "struck", "hit") var/hacked = FALSE var/saber_color /obj/item/toy/sword/attack_self(mob/user) active = !( active ) if (active) to_chat(user, "<span class='notice'>I extend the plastic blade with a quick flick of your wrist.</span>") playsound(user, 'sound/blank.ogg', 20, TRUE) if(hacked) icon_state = "swordrainbow" item_state = "swordrainbow" else icon_state = "swordblue" item_state = "swordblue" w_class = WEIGHT_CLASS_BULKY else to_chat(user, "<span class='notice'>I push the plastic blade back down into the handle.</span>") playsound(user, 'sound/blank.ogg', 20, TRUE) icon_state = "sword0" item_state = "sword0" w_class = WEIGHT_CLASS_SMALL add_fingerprint(user) // Copied from /obj/item/melee/transforming/energy/sword/attackby /obj/item/toy/sword/attackby(obj/item/W, mob/living/user, params) if(istype(W, /obj/item/toy/sword)) if(HAS_TRAIT(W, TRAIT_NODROP) || HAS_TRAIT(src, TRAIT_NODROP)) to_chat(user, "<span class='warning'>\the [HAS_TRAIT(src, TRAIT_NODROP) ? src : W] is stuck to your hand, you can't attach it to \the [HAS_TRAIT(src, TRAIT_NODROP) ? W : src]!</span>") return else to_chat(user, "<span class='notice'>I attach the ends of the two plastic swords, making a single double-bladed toy! You're fake-cool.</span>") var/obj/item/twohanded/dualsaber/toy/newSaber = new /obj/item/twohanded/dualsaber/toy(user.loc) if(hacked) // That's right, we'll only check the "original" "sword". newSaber.hacked = TRUE newSaber.saber_color = "rainbow" qdel(W) qdel(src) else if(W.tool_behaviour == TOOL_MULTITOOL) if(!hacked) hacked = TRUE saber_color = "rainbow" to_chat(user, "<span class='warning'>RNBW_ENGAGE</span>") if(active) icon_state = "swordrainbow" user.update_inv_hands() else to_chat(user, "<span class='warning'>It's already fabulous!</span>") else return ..() /* * Foam armblade */ /obj/item/toy/foamblade name = "foam armblade" desc = "" icon = 'icons/obj/toy.dmi' icon_state = "foamblade" item_state = "arm_blade" lefthand_file = 'icons/mob/inhands/antag/changeling_lefthand.dmi' righthand_file = 'icons/mob/inhands/antag/changeling_righthand.dmi' attack_verb = list("pricked", "absorbed", "gored") w_class = WEIGHT_CLASS_SMALL resistance_flags = FLAMMABLE /obj/item/toy/windupToolbox name = "windup toolbox" desc = "" icon_state = "his_grace" item_state = "artistic_toolbox" lefthand_file = 'icons/mob/inhands/equipment/toolbox_lefthand.dmi' righthand_file = 'icons/mob/inhands/equipment/toolbox_righthand.dmi' var/active = FALSE icon = 'icons/obj/items_and_weapons.dmi' hitsound = 'sound/blank.ogg' attack_verb = list("robusted") /obj/item/toy/windupToolbox/attack_self(mob/user) if(!active) icon_state = "his_grace_awakened" to_chat(user, "<span class='notice'>I wind up [src], it begins to rumble.</span>") active = TRUE playsound(src, 'sound/blank.ogg', 100) Rumble() addtimer(CALLBACK(src, PROC_REF(stopRumble)), 600) else to_chat(user, "<span class='warning'>[src] is already active!</span>") /obj/item/toy/windupToolbox/proc/Rumble() var/static/list/transforms if(!transforms) var/matrix/M1 = matrix() var/matrix/M2 = matrix() var/matrix/M3 = matrix() var/matrix/M4 = matrix() M1.Translate(-1, 0) M2.Translate(0, 1) M3.Translate(1, 0) M4.Translate(0, -1) transforms = list(M1, M2, M3, M4) animate(src, transform=transforms[1], time=0.2, loop=-1) animate(transform=transforms[2], time=0.1) animate(transform=transforms[3], time=0.2) animate(transform=transforms[4], time=0.3) /obj/item/toy/windupToolbox/proc/stopRumble() icon_state = initial(icon_state) active = FALSE animate(src, transform=matrix()) /* * Subtype of Double-Bladed Energy Swords */ /obj/item/twohanded/dualsaber/toy name = "double-bladed toy sword" desc = "" force = 0 throwforce = 0 throw_speed = 1 throw_range = 5 force_unwielded = 0 force_wielded = 0 attack_verb = list("attacked", "struck", "hit") /obj/item/twohanded/dualsaber/toy/hit_reaction(mob/living/carbon/human/owner, atom/movable/hitby, attack_text = "the attack", final_block_chance = 0, damage = 0, attack_type = MELEE_ATTACK) return 0 /obj/item/twohanded/dualsaber/toy/IsReflect()//Stops Toy Dualsabers from reflecting energy projectiles return 0 /obj/item/toy/katana name = "replica katana" desc = "" icon = 'icons/obj/items_and_weapons.dmi' icon_state = "katana" item_state = "katana" lefthand_file = 'icons/mob/inhands/weapons/swords_lefthand.dmi' righthand_file = 'icons/mob/inhands/weapons/swords_righthand.dmi' flags_1 = CONDUCT_1 slot_flags = ITEM_SLOT_BELT | ITEM_SLOT_BACK force = 5 throwforce = 5 w_class = WEIGHT_CLASS_NORMAL attack_verb = list("attacked", "slashed", "stabbed", "sliced") hitsound = 'sound/blank.ogg' /* * Snap pops */ /obj/item/toy/snappop name = "powder pack" desc = "" icon = 'icons/obj/toy.dmi' icon_state = "snappop" w_class = WEIGHT_CLASS_TINY var/ash_type = /obj/item/ash /obj/item/toy/snappop/proc/pop_burst(n=3, c=1) var/datum/effect_system/spark_spread/s = new() s.set_up(n, c, src) s.start() new ash_type(loc) visible_message("<span class='warning'>[src] explodes!</span>", "<span class='hear'>I hear a explosion!</span>") playsound(src, 'sound/blank.ogg', 50, TRUE) qdel(src) /obj/item/toy/snappop/fire_act(added, maxstacks) pop_burst() /obj/item/toy/snappop/throw_impact(atom/hit_atom, datum/thrownthing/throwingdatum) if(!..()) pop_burst() /obj/item/toy/snappop/Crossed(H as mob|obj) if(ishuman(H)) //i guess carp and shit shouldn't set them off var/mob/living/carbon/M = H if(M.m_intent == MOVE_INTENT_RUN) to_chat(M, "<span class='danger'>I step on the snap pop!</span>") pop_burst(2, 0) /obj/item/toy/snappop/phoenix name = "magic powder pack" desc = "" ash_type = /obj/item/ash/snappop_phoenix /obj/item/ash/snappop_phoenix var/respawn_time = 300 /obj/item/ash/snappop_phoenix/Initialize() . = ..() addtimer(CALLBACK(src, PROC_REF(respawn)), respawn_time) /obj/item/ash/snappop_phoenix/proc/respawn() new /obj/item/toy/snappop/phoenix(get_turf(src)) qdel(src) /* * Mech prizes */ /obj/item/toy/prize icon = 'icons/obj/toy.dmi' icon_state = "ripleytoy" var/timer = 0 var/cooldown = 30 var/quiet = 0 w_class = WEIGHT_CLASS_SMALL //all credit to skasi for toy mech fun ideas /obj/item/toy/prize/attack_self(mob/user) if(timer < world.time) to_chat(user, "<span class='notice'>I play with [src].</span>") timer = world.time + cooldown if(!quiet) playsound(user, 'sound/blank.ogg', 20, TRUE) else . = ..() /obj/item/toy/prize/attack_hand(mob/user) . = ..() if(.) return if(loc == user) attack_self(user) /obj/item/toy/prize/ripley name = "toy Ripley" desc = "" /obj/item/toy/prize/fireripley name = "toy firefighting Ripley" desc = "" icon_state = "fireripleytoy" /obj/item/toy/prize/deathripley name = "toy deathsquad Ripley" desc = "" icon_state = "deathripleytoy" /obj/item/toy/prize/gygax name = "toy Gygax" desc = "" icon_state = "gygaxtoy" /obj/item/toy/prize/durand name = "toy Durand" desc = "" icon_state = "durandprize" /obj/item/toy/prize/honk name = "toy H.O.N.K." desc = "" icon_state = "honkprize" /obj/item/toy/prize/marauder name = "toy Marauder" desc = "" icon_state = "marauderprize" /obj/item/toy/prize/seraph name = "toy Seraph" desc = "" icon_state = "seraphprize" /obj/item/toy/prize/mauler name = "toy Mauler" desc = "" icon_state = "maulerprize" /obj/item/toy/prize/odysseus name = "toy Odysseus" desc = "" icon_state = "odysseusprize" /obj/item/toy/prize/phazon name = "toy Phazon" desc = "" icon_state = "phazonprize" /obj/item/toy/prize/reticence name = "toy Reticence" desc = "" icon_state = "reticenceprize" quiet = 1 /obj/item/toy/talking name = "talking action figure" desc = "" icon = 'icons/obj/toy.dmi' icon_state = "owlprize" w_class = WEIGHT_CLASS_SMALL var/cooldown = FALSE var/messages = list("I'm super generic!", "Mathematics class is of variable difficulty!") var/span = "danger" var/recharge_time = 30 var/chattering = FALSE var/phomeme /obj/item/toy/talking/attack_self(mob/user) if(!cooldown) activation_message(user) playsound(loc, 'sound/blank.ogg', 20, TRUE) INVOKE_ASYNC(src, PROC_REF(do_toy_talk), user) cooldown = TRUE addtimer(VARSET_CALLBACK(src, cooldown, FALSE), recharge_time) return ..() /obj/item/toy/talking/proc/activation_message(mob/user) user.visible_message( "<span class='notice'>[user] pulls the string on \the [src].</span>", "<span class='notice'>I pull the string on \the [src].</span>", "<span class='notice'>I hear a string being pulled.</span>") /obj/item/toy/talking/proc/generate_messages() return list(pick(messages)) /obj/item/toy/talking/proc/do_toy_talk(mob/user) for(var/message in generate_messages()) toy_talk(user, message) sleep(10) /obj/item/toy/talking/proc/toy_talk(mob/user, message) user.loc.visible_message("<span class='[span]'>[icon2html(src, viewers(user.loc))] [message]</span>") if(chattering) chatter(message, phomeme, user) /obj/item/toy/talking/codex_gigas name = "Toy Codex Gigas" desc = "" icon = 'icons/obj/library.dmi' icon_state = "demonomicon" lefthand_file = 'icons/mob/inhands/misc/books_lefthand.dmi' righthand_file = 'icons/mob/inhands/misc/books_righthand.dmi' w_class = WEIGHT_CLASS_SMALL recharge_time = 60 /obj/item/toy/talking/codex_gigas/activation_message(mob/user) user.visible_message( "<span class='notice'>[user] presses the button on \the [src].</span>", "<span class='notice'>I press the button on \the [src].</span>", "<span class='notice'>I hear a soft click.</span>") /obj/item/toy/talking/codex_gigas/generate_messages() var/datum/fakeDevil/devil = new var/list/messages = list() messages += "Some fun facts about: [devil.truename]" messages += "[GLOB.lawlorify[LORE][devil.bane]]" messages += "[GLOB.lawlorify[LORE][devil.obligation]]" messages += "[GLOB.lawlorify[LORE][devil.ban]]" messages += "[GLOB.lawlorify[LORE][devil.banish]]" return messages /obj/item/toy/talking/owl name = "owl action figure" desc = "" icon_state = "owlprize" messages = list("You won't get away this time, Griffin!", "Stop right there, criminal!", "Hoot! Hoot!", "I am the night!") chattering = TRUE phomeme = "owl" w_class = WEIGHT_CLASS_SMALL /obj/item/toy/talking/griffin name = "griffin action figure" desc = "" icon_state = "griffinprize" messages = list("You can't stop me, Owl!", "My plan is flawless! The vault is mine!", "Caaaawwww!", "You will never catch me!") chattering = TRUE phomeme = "griffin" w_class = WEIGHT_CLASS_SMALL /* || A Deck of Cards for playing various games of chance || */ /obj/item/toy/cards resistance_flags = FLAMMABLE max_integrity = 50 var/parentdeck = null var/deckstyle = "nanotrasen" var/card_hitsound = null var/card_force = 0 var/card_throwforce = 0 var/card_throw_speed = 1 var/card_throw_range = 7 var/list/card_attack_verb = list("attacked") /obj/item/toy/cards/suicide_act(mob/living/carbon/user) user.visible_message("<span class='suicide'>[user] is slitting [user.p_their()] wrists with \the [src]! It looks like [user.p_they()] [user.p_have()] a crummy hand!</span>") playsound(src, 'sound/blank.ogg', 50, TRUE) return BRUTELOSS /obj/item/toy/cards/proc/apply_card_vars(obj/item/toy/cards/newobj, obj/item/toy/cards/sourceobj) // Applies variables for supporting multiple types of card deck if(!istype(sourceobj)) return /obj/item/toy/cards/deck name = "deck of cards" desc = "" icon = 'icons/obj/toy.dmi' deckstyle = "nanotrasen" icon_state = "deck_nanotrasen_full" w_class = WEIGHT_CLASS_SMALL var/cooldown = 0 var/list/cards = list() /obj/item/toy/cards/deck/Initialize() . = ..() populate_deck() ///Generates all the cards within the deck. /obj/item/toy/cards/deck/proc/populate_deck() icon_state = "deck_[deckstyle]_full" for(var/suit in list("Hearts", "Spades", "Clubs", "Diamonds")) cards += "Ace of [suit]" for(var/i in 2 to 10) cards += "[i] of [suit]" for(var/person in list("Jack", "Queen", "King")) cards += "[person] of [suit]" //ATTACK HAND IGNORING PARENT RETURN VALUE //ATTACK HAND NOT CALLING PARENT /obj/item/toy/cards/deck/attack_hand(mob/user) draw_card(user) /obj/item/toy/cards/deck/proc/draw_card(mob/user) if(isliving(user)) var/mob/living/L = user if(!(L.mobility_flags & MOBILITY_PICKUP)) return var/choice = null if(cards.len == 0) to_chat(user, "<span class='warning'>There are no more cards to draw!</span>") return var/obj/item/toy/cards/singlecard/H = new/obj/item/toy/cards/singlecard(user.loc) choice = cards[1] H.cardname = choice H.parentdeck = src var/O = src H.apply_card_vars(H,O) src.cards -= choice H.pickup(user) user.put_in_hands(H) user.visible_message("<span class='notice'>[user] draws a card from the deck.</span>", "<span class='notice'>I draw a card from the deck.</span>") update_icon() /obj/item/toy/cards/deck/update_icon() if(cards.len > 26) icon_state = "deck_[deckstyle]_full" else if(cards.len > 10) icon_state = "deck_[deckstyle]_half" else if(cards.len > 0) icon_state = "deck_[deckstyle]_low" else if(cards.len == 0) icon_state = "deck_[deckstyle]_empty" /obj/item/toy/cards/deck/attack_self(mob/user) if(cooldown < world.time - 50) cards = shuffle(cards) playsound(src, 'sound/blank.ogg', 50, TRUE) user.visible_message("<span class='notice'>[user] shuffles the deck.</span>", "<span class='notice'>I shuffle the deck.</span>") cooldown = world.time /obj/item/toy/cards/deck/attackby(obj/item/I, mob/living/user, params) if(istype(I, /obj/item/toy/cards/singlecard)) var/obj/item/toy/cards/singlecard/SC = I if(SC.parentdeck == src) if(!user.temporarilyRemoveItemFromInventory(SC)) to_chat(user, "<span class='warning'>The card is stuck to your hand, you can't add it to the deck!</span>") return cards += SC.cardname user.visible_message("<span class='notice'>[user] adds a card to the bottom of the deck.</span>","<span class='notice'>I add the card to the bottom of the deck.</span>") qdel(SC) else to_chat(user, "<span class='warning'>I can't mix cards from other decks!</span>") update_icon() else if(istype(I, /obj/item/toy/cards/cardhand)) var/obj/item/toy/cards/cardhand/CH = I if(CH.parentdeck == src) if(!user.temporarilyRemoveItemFromInventory(CH)) to_chat(user, "<span class='warning'>The hand of cards is stuck to your hand, you can't add it to the deck!</span>") return cards += CH.currenthand user.visible_message("<span class='notice'>[user] puts [user.p_their()] hand of cards in the deck.</span>", "<span class='notice'>I put the hand of cards in the deck.</span>") qdel(CH) else to_chat(user, "<span class='warning'>I can't mix cards from other decks!</span>") update_icon() else return ..() /obj/item/toy/cards/deck/MouseDrop(atom/over_object) . = ..() var/mob/living/M = usr if(!istype(M) || !(M.mobility_flags & MOBILITY_PICKUP)) return if(Adjacent(usr)) if(over_object == M && loc != M) M.put_in_hands(src) to_chat(usr, "<span class='notice'>I pick up the deck.</span>") else if(istype(over_object, /atom/movable/screen/inventory/hand)) var/atom/movable/screen/inventory/hand/H = over_object if(M.putItemFromInventoryInHandIfPossible(src, H.held_index)) to_chat(usr, "<span class='notice'>I pick up the deck.</span>") else to_chat(usr, "<span class='warning'>I can't reach it from here!</span>") /obj/item/toy/cards/cardhand name = "hand of cards" desc = "" icon = 'icons/obj/toy.dmi' icon_state = "nanotrasen_hand2" w_class = WEIGHT_CLASS_TINY var/list/currenthand = list() var/choice = null /obj/item/toy/cards/cardhand/attack_self(mob/user) user.set_machine(src) interact(user) /obj/item/toy/cards/cardhand/ui_interact(mob/user) . = ..() var/dat = "You have:<BR>" for(var/t in currenthand) dat += "<A href='?src=[REF(src)];pick=[t]'>A [t].</A><BR>" dat += "Which card will you remove next?" var/datum/browser/popup = new(user, "cardhand", "Hand of Cards", 400, 240) popup.set_title_image(user.browse_rsc_icon(src.icon, src.icon_state)) popup.set_content(dat) popup.open() /obj/item/toy/cards/cardhand/Topic(href, href_list) if(..()) return if(usr.stat || !ishuman(usr)) return var/mob/living/carbon/human/cardUser = usr if(!(cardUser.mobility_flags & MOBILITY_USE)) return var/O = src if(href_list["pick"]) if (cardUser.is_holding(src)) var/choice = href_list["pick"] var/obj/item/toy/cards/singlecard/C = new/obj/item/toy/cards/singlecard(cardUser.loc) src.currenthand -= choice C.parentdeck = src.parentdeck C.cardname = choice C.apply_card_vars(C,O) C.pickup(cardUser) cardUser.put_in_hands(C) cardUser.visible_message("<span class='notice'>[cardUser] draws a card from [cardUser.p_their()] hand.</span>", "<span class='notice'>I take the [C.cardname] from your hand.</span>") interact(cardUser) if(src.currenthand.len < 3) src.icon_state = "[deckstyle]_hand2" else if(src.currenthand.len < 4) src.icon_state = "[deckstyle]_hand3" else if(src.currenthand.len < 5) src.icon_state = "[deckstyle]_hand4" if(src.currenthand.len == 1) var/obj/item/toy/cards/singlecard/N = new/obj/item/toy/cards/singlecard(src.loc) N.parentdeck = src.parentdeck N.cardname = src.currenthand[1] N.apply_card_vars(N,O) qdel(src) N.pickup(cardUser) cardUser.put_in_hands(N) to_chat(cardUser, "<span class='notice'>I also take [currenthand[1]] and hold it.</span>") cardUser << browse(null, "window=cardhand") return /obj/item/toy/cards/cardhand/attackby(obj/item/toy/cards/singlecard/C, mob/living/user, params) if(istype(C)) if(C.parentdeck == src.parentdeck) src.currenthand += C.cardname user.visible_message("<span class='notice'>[user] adds a card to [user.p_their()] hand.</span>", "<span class='notice'>I add the [C.cardname] to your hand.</span>") qdel(C) interact(user) if(currenthand.len > 4) src.icon_state = "[deckstyle]_hand5" else if(currenthand.len > 3) src.icon_state = "[deckstyle]_hand4" else if(currenthand.len > 2) src.icon_state = "[deckstyle]_hand3" else to_chat(user, "<span class='warning'>I can't mix cards from other decks!</span>") else return ..() /obj/item/toy/cards/cardhand/apply_card_vars(obj/item/toy/cards/newobj,obj/item/toy/cards/sourceobj) ..() newobj.deckstyle = sourceobj.deckstyle newobj.icon_state = "[deckstyle]_hand2" // Another dumb hack, without this the hand is invisible (or has the default deckstyle) until another card is added. newobj.card_hitsound = sourceobj.card_hitsound newobj.card_force = sourceobj.card_force newobj.card_throwforce = sourceobj.card_throwforce newobj.card_throw_speed = sourceobj.card_throw_speed newobj.card_throw_range = sourceobj.card_throw_range newobj.card_attack_verb = sourceobj.card_attack_verb newobj.resistance_flags = sourceobj.resistance_flags /obj/item/toy/cards/singlecard name = "card" desc = "" icon = 'icons/obj/toy.dmi' icon_state = "singlecard_down_nanotrasen" w_class = WEIGHT_CLASS_TINY var/cardname = null var/flipped = 0 pixel_x = -5 /obj/item/toy/cards/singlecard/examine(mob/user) . = ..() if(ishuman(user)) var/mob/living/carbon/human/cardUser = user if(cardUser.is_holding(src)) cardUser.visible_message("<span class='notice'>[cardUser] checks [cardUser.p_their()] card.</span>", "<span class='notice'>The card reads: [cardname].</span>") else . += "<span class='warning'>I need to have the card in your hand to check it!</span>" /obj/item/toy/cards/singlecard/verb/Flip() set name = "Flip Card" set hidden = 1 set src in range(1) if(!ishuman(usr) || !usr.canUseTopic(src, BE_CLOSE)) return if(!flipped) src.flipped = 1 if (cardname) src.icon_state = "sc_[cardname]_[deckstyle]" src.name = src.cardname else src.icon_state = "sc_Ace of Spades_[deckstyle]" src.name = "What Card" src.pixel_x = 5 else if(flipped) src.flipped = 0 src.icon_state = "singlecard_down_[deckstyle]" src.name = "card" src.pixel_x = -5 /obj/item/toy/cards/singlecard/attackby(obj/item/I, mob/living/user, params) if(istype(I, /obj/item/toy/cards/singlecard/)) var/obj/item/toy/cards/singlecard/C = I if(C.parentdeck == src.parentdeck) var/obj/item/toy/cards/cardhand/H = new/obj/item/toy/cards/cardhand(user.loc) H.currenthand += C.cardname H.currenthand += src.cardname H.parentdeck = C.parentdeck H.apply_card_vars(H,C) to_chat(user, "<span class='notice'>I combine the [C.cardname] and the [src.cardname] into a hand.</span>") qdel(C) qdel(src) H.pickup(user) user.put_in_active_hand(H) else to_chat(user, "<span class='warning'>I can't mix cards from other decks!</span>") if(istype(I, /obj/item/toy/cards/cardhand/)) var/obj/item/toy/cards/cardhand/H = I if(H.parentdeck == parentdeck) H.currenthand += cardname user.visible_message("<span class='notice'>[user] adds a card to [user.p_their()] hand.</span>", "<span class='notice'>I add the [cardname] to your hand.</span>") qdel(src) H.interact(user) if(H.currenthand.len > 4) H.icon_state = "[deckstyle]_hand5" else if(H.currenthand.len > 3) H.icon_state = "[deckstyle]_hand4" else if(H.currenthand.len > 2) H.icon_state = "[deckstyle]_hand3" else to_chat(user, "<span class='warning'>I can't mix cards from other decks!</span>") else return ..() /obj/item/toy/cards/singlecard/attack_self(mob/living/carbon/human/user) if(!ishuman(user) || !(user.mobility_flags & MOBILITY_USE)) return Flip() /obj/item/toy/cards/singlecard/apply_card_vars(obj/item/toy/cards/singlecard/newobj,obj/item/toy/cards/sourceobj) ..() newobj.deckstyle = sourceobj.deckstyle newobj.icon_state = "singlecard_down_[deckstyle]" // Without this the card is invisible until flipped. It's an ugly hack, but it works. newobj.card_hitsound = sourceobj.card_hitsound newobj.hitsound = newobj.card_hitsound newobj.card_force = sourceobj.card_force newobj.force = newobj.card_force newobj.card_throwforce = sourceobj.card_throwforce newobj.throwforce = newobj.card_throwforce newobj.card_throw_speed = sourceobj.card_throw_speed newobj.throw_speed = newobj.card_throw_speed newobj.card_throw_range = sourceobj.card_throw_range newobj.throw_range = newobj.card_throw_range newobj.card_attack_verb = sourceobj.card_attack_verb newobj.attack_verb = newobj.card_attack_verb /* || Syndicate playing cards, for pretending you're Gambit and playing poker for the nuke disk. || */ /obj/item/toy/cards/deck/syndicate name = "cards" desc = "a pack of cards." icon_state = "deck_syndicate_full" deckstyle = "syndicate" card_hitsound = 'sound/blank.ogg' card_force = 5 card_throwforce = 10 card_throw_speed = 1 card_throw_range = 7 card_attack_verb = list("attacked", "sliced", "diced", "slashed", "cut") resistance_flags = NONE /* * Fake nuke */ /obj/item/toy/nuke name = "\improper Nuclear Fission Explosive toy" desc = "" icon = 'icons/obj/toy.dmi' icon_state = "nuketoyidle" w_class = WEIGHT_CLASS_SMALL var/cooldown = 0 /obj/item/toy/nuke/attack_self(mob/user) if (cooldown < world.time) cooldown = world.time + 1800 //3 minutes user.visible_message("<span class='warning'>[user] presses a button on [src].</span>", "<span class='notice'>I activate [src], it plays a loud noise!</span>", "<span class='hear'>I hear the click of a button.</span>") sleep(5) icon_state = "nuketoy" playsound(src, 'sound/blank.ogg', 100, FALSE) sleep(135) icon_state = "nuketoycool" sleep(cooldown - world.time) icon_state = "nuketoyidle" else var/timeleft = (cooldown - world.time) to_chat(user, "<span class='alert'>Nothing happens, and '</span>[round(timeleft/10)]<span class='alert'>' appears on a small display.</span>") /* * Fake meteor */ /obj/item/toy/minimeteor name = "\improper Mini-Meteor" desc = "" icon = 'icons/obj/toy.dmi' icon_state = "minimeteor" w_class = WEIGHT_CLASS_SMALL /obj/item/toy/minimeteor/throw_impact(atom/hit_atom, datum/thrownthing/throwingdatum) if(!..()) playsound(src, 'sound/blank.ogg', 40, TRUE) for(var/mob/M in urange(10, src)) if(!M.stat) shake_camera(M, 3, 1) qdel(src) /* * Toy big red button */ /obj/item/toy/redbutton name = "big red button" desc = "" icon = 'icons/obj/assemblies.dmi' icon_state = "bigred" w_class = WEIGHT_CLASS_SMALL var/cooldown = 0 /obj/item/toy/redbutton/attack_self(mob/user) if (cooldown < world.time) cooldown = (world.time + 300) // Sets cooldown at 30 seconds user.visible_message("<span class='warning'>[user] presses the big red button.</span>", "<span class='notice'>I press the button, it plays a loud noise!</span>", "<span class='hear'>The button clicks loudly.</span>") playsound(src, 'sound/blank.ogg', 50, FALSE) for(var/mob/M in urange(10, src)) // Checks range if(!M.stat) // Checks to make sure whoever's getting shaken is alive/not the AI sleep(8) // Short delay to match up with the explosion sound shake_camera(M, 2, 1) // Shakes player camera 2 squares for 1 second. else to_chat(user, "<span class='alert'>Nothing happens.</span>") /* * Snowballs */ /obj/item/toy/snowball name = "snowball" desc = "" icon = 'icons/obj/toy.dmi' icon_state = "snowball" throwforce = 12 //pelt your enemies to death with lumps of snow /obj/item/toy/snowball/afterattack(atom/target as mob|obj|turf|area, mob/user) . = ..() if(user.dropItemToGround(src)) throw_at(target, throw_range, throw_speed) /obj/item/toy/snowball/throw_impact(atom/hit_atom, datum/thrownthing/throwingdatum) if(!..()) playsound(src, 'sound/blank.ogg', 20, TRUE) qdel(src) /* * Beach ball */ /obj/item/toy/beach_ball icon = 'icons/misc/beach.dmi' icon_state = "ball" name = "beach ball" item_state = "beachball" w_class = WEIGHT_CLASS_BULKY //Stops people from hiding it in their bags/pockets /* * Clockwork Watch */ /obj/item/toy/clockwork_watch name = "steampunk watch" desc = "" icon = 'icons/obj/clockwork_objects.dmi' icon_state = "dread_ipad" slot_flags = ITEM_SLOT_BELT w_class = WEIGHT_CLASS_SMALL var/cooldown = 0 /obj/item/toy/clockwork_watch/attack_self(mob/user) if (cooldown < world.time) cooldown = world.time + 1800 //3 minutes user.visible_message("<span class='warning'>[user] rotates a cogwheel on [src].</span>", "<span class='notice'>I rotate a cogwheel on [src], it plays a loud noise!</span>", "<span class='hear'>I hear cogwheels turning.</span>") playsound(src, 'sound/blank.ogg', 50, FALSE) else to_chat(user, "<span class='alert'>The cogwheels are already turning!</span>") /obj/item/toy/clockwork_watch/examine(mob/user) . = ..() . += "<span class='info'>Station Time: [station_time_timestamp()]</span>" /* * Toy Dagger */ /obj/item/toy/toy_dagger name = "toy dagger" desc = "" icon = 'icons/obj/wizard.dmi' icon_state = "render" item_state = "cultdagger" lefthand_file = 'icons/mob/inhands/weapons/swords_lefthand.dmi' righthand_file = 'icons/mob/inhands/weapons/swords_righthand.dmi' w_class = WEIGHT_CLASS_SMALL /* * Xenomorph action figure */ /obj/item/toy/toy_xeno icon = 'icons/obj/toy.dmi' icon_state = "toy_xeno" name = "xenomorph action figure" desc = "" w_class = WEIGHT_CLASS_SMALL var/cooldown = 0 /obj/item/toy/toy_xeno/attack_self(mob/user) if(cooldown <= world.time) cooldown = (world.time + 50) //5 second cooldown user.visible_message("<span class='notice'>[user] pulls back the string on [src].</span>") icon_state = "[initial(icon_state)]_used" sleep(5) audible_message("<span class='danger'>[icon2html(src, viewers(src))] Hiss!</span>") var/list/possible_sounds = list('sound/blank.ogg') var/chosen_sound = pick(possible_sounds) playsound(get_turf(src), chosen_sound, 50, TRUE) addtimer(VARSET_CALLBACK(src, icon_state, "[initial(icon_state)]"), 4.5 SECONDS) else to_chat(user, "<span class='warning'>The string on [src] hasn't rewound all the way!</span>") return // TOY MOUSEYS :3 :3 :3 /obj/item/toy/cattoy name = "toy mouse" desc = "" icon = 'icons/obj/toy.dmi' icon_state = "toy_mouse" w_class = WEIGHT_CLASS_SMALL var/cooldown = 0 resistance_flags = FLAMMABLE /* * Action Figures */ /obj/item/toy/figure name = "Non-Specific Action Figure action figure" desc = null icon = 'icons/obj/toy.dmi' icon_state = "nuketoy" var/cooldown = 0 var/toysay = "What the fuck did you do?" var/toysound = 'sound/blank.ogg' w_class = WEIGHT_CLASS_SMALL /obj/item/toy/figure/Initialize() . = ..() desc = "" /obj/item/toy/figure/attack_self(mob/user as mob) if(cooldown <= world.time) cooldown = world.time + 50 to_chat(user, "<span class='notice'>[src] says \"[toysay]\"</span>") playsound(user, toysound, 20, TRUE) /obj/item/toy/figure/cmo name = "Chief Medical Officer action figure" icon_state = "cmo" toysay = "Suit sensors!" /obj/item/toy/figure/assistant name = "Assistant action figure" icon_state = "assistant" toysay = "Grey tide world wide!" /obj/item/toy/figure/atmos name = "Atmospheric Technician action figure" icon_state = "atmos" toysay = "Glory to Atmosia!" /obj/item/toy/figure/bartender name = "Bartender action figure" icon_state = "bartender" toysay = "Where is Pun Pun?" /obj/item/toy/figure/borg name = "Cyborg action figure" icon_state = "borg" toysay = "I. LIVE. AGAIN." toysound = 'sound/blank.ogg' /obj/item/toy/figure/botanist name = "Botanist action figure" icon_state = "botanist" toysay = "Blaze it!" /obj/item/toy/figure/captain name = "Captain action figure" icon_state = "captain" toysay = "Any heads of staff?" /obj/item/toy/figure/cargotech name = "Cargo Technician action figure" icon_state = "cargotech" toysay = "For Cargonia!" /obj/item/toy/figure/ce name = "Chief Engineer action figure" icon_state = "ce" toysay = "Wire the solars!" /obj/item/toy/figure/chaplain name = "Chaplain action figure" icon_state = "chaplain" toysay = "Praise Space Jesus!" /obj/item/toy/figure/chef name = "Chef action figure" icon_state = "chef" toysay = " I'll make you into a burger!" /obj/item/toy/figure/chemist name = "Chemist action figure" icon_state = "chemist" toysay = "Get your pills!" /obj/item/toy/figure/clown name = "Clown action figure" icon_state = "clown" toysay = "Honk!" toysound = 'sound/blank.ogg' /obj/item/toy/figure/ian name = "Ian action figure" icon_state = "ian" toysay = "Arf!" /obj/item/toy/figure/detective name = "Detective action figure" icon_state = "detective" toysay = "This airlock has grey jumpsuit and insulated glove fibers on it." /obj/item/toy/figure/dsquad name = "Death Squad Officer action figure" icon_state = "dsquad" toysay = "Kill em all!" /obj/item/toy/figure/engineer name = "Engineer action figure" icon_state = "engineer" toysay = "Oh god, the singularity is loose!" /obj/item/toy/figure/geneticist name = "Geneticist action figure" icon_state = "geneticist" toysay = "Smash!" /obj/item/toy/figure/hop name = "Head of Personnel action figure" icon_state = "hop" toysay = "Giving out all access!" /obj/item/toy/figure/hos name = "Head of Security action figure" icon_state = "hos" toysay = "Go ahead, make my day." /obj/item/toy/figure/qm name = "Quartermaster action figure" icon_state = "qm" toysay = "Please sign this form in triplicate and we will see about geting you a welding mask within 3 business days." /obj/item/toy/figure/janitor name = "Janitor action figure" icon_state = "janitor" toysay = "Look at the signs, you idiot." /obj/item/toy/figure/lawyer name = "Lawyer action figure" icon_state = "lawyer" toysay = "My client is a dirty traitor!" /obj/item/toy/figure/curator name = "Curator action figure" icon_state = "curator" toysay = "One day while..." /obj/item/toy/figure/md name = "Medical Doctor action figure" icon_state = "md" toysay = "The patient is already dead!" /obj/item/toy/figure/mime name = "Mime action figure" icon_state = "mime" toysay = "..." toysound = null /obj/item/toy/figure/miner name = "Shaft Miner action figure" icon_state = "miner" toysay = "COLOSSUS RIGHT OUTSIDE THE BASE!" /obj/item/toy/figure/ninja name = "Ninja action figure" icon_state = "ninja" toysay = "Oh god! Stop shooting, I'm friendly!" /obj/item/toy/figure/wizard name = "Wizard action figure" icon_state = "wizard" toysay = "Ei Nath!" toysound = 'sound/blank.ogg' /obj/item/toy/figure/rd name = "Research Director action figure" icon_state = "rd" toysay = "Blowing all of the borgs!" /obj/item/toy/figure/roboticist name = "Roboticist action figure" icon_state = "roboticist" toysay = "Big stompy mechs!" toysound = 'sound/blank.ogg' /obj/item/toy/figure/scientist name = "Scientist action figure" icon_state = "scientist" toysay = "I call toxins." toysound = 'sound/blank.ogg' /obj/item/toy/figure/syndie name = "Nuclear Operative action figure" icon_state = "syndie" toysay = "Get that fucking disk!" /obj/item/toy/figure/secofficer name = "Security Officer action figure" icon_state = "secofficer" toysay = "I am the law!" toysound = 'sound/blank.ogg' /obj/item/toy/figure/virologist name = "Virologist action figure" icon_state = "virologist" toysay = "The cure is potassium!" /obj/item/toy/figure/warden name = "Warden action figure" icon_state = "warden" toysay = "Seventeen minutes for coughing at an officer!" /obj/item/toy/dummy name = "ventriloquist dummy" desc = "" icon = 'icons/obj/toy.dmi' icon_state = "assistant" item_state = "doll" var/doll_name = "Dummy" //Add changing looks when i feel suicidal about making 20 inhands for these. /obj/item/toy/dummy/attack_self(mob/user) var/new_name = stripped_input(usr,"What would you like to name the dummy?","Input a name",doll_name,MAX_NAME_LEN) if(!new_name) return doll_name = new_name to_chat(user, "<span class='notice'>I name the dummy as \"[doll_name]\".</span>") name = "[initial(name)] - [doll_name]" /obj/item/toy/dummy/talk_into(atom/movable/A, message, channel, list/spans, datum/language/language) var/mob/M = A if (istype(M)) M.log_talk(message, LOG_SAY, tag="dummy toy") say(message, language) return NOPASS /obj/item/toy/dummy/GetVoice() return doll_name /obj/item/toy/seashell name = "seashell" desc = "" icon = 'icons/misc/beach.dmi' icon_state = "shell1" var/static/list/possible_colors = list("" = 2, COLOR_PURPLE_GRAY = 1, COLOR_OLIVE = 1, COLOR_PALE_BLUE_GRAY = 1, COLOR_RED_GRAY = 1) /obj/item/toy/seashell/Initialize() . = ..() pixel_x = rand(-5, 5) pixel_y = rand(-5, 5) icon_state = "shell[rand(1,3)]" color = pickweight(possible_colors) setDir(pick(GLOB.cardinals))
1
0.946516
1
0.946516
game-dev
MEDIA
0.99059
game-dev
0.903957
1
0.903957
s1ddok/Fiber2D
11,319
Fiber2D/PhysicsBody.swift
// // PhysicsBody.swift // Fiber2D // // Created by Andrey Volodin on 18.09.16. // Copyright © 2016 s1ddok. All rights reserved. // import SwiftMath import CChipmunk2D /** * A body affect by physics. * * It can attach one or more shapes. * If you create body with createXXX, it will automatically compute mass and moment with density your specified(which is PHYSICSBODY_MATERIAL_DEFAULT by default, and the density value is 0.1f), and it based on the formula: mass = density * area. * If you create body with createEdgeXXX, the mass and moment will be inifinity by default. And it's a static body. * You can change mass and moment with `mass` and `moment`. And you can change the body to be dynamic or static by use `dynamic`. */ public class PhysicsBody: ComponentBase, Behaviour, FixedUpdatable, Pausable { // MARK: State /** Whether the body is at rest. */ public var isResting: Bool { get { return cpBodyIsSleeping(chipmunkBody) == 0 } set { let isResting = self.isResting if newValue && !isResting { cpBodySleep(chipmunkBody) } else if !newValue && isResting { cpBodyActivate(chipmunkBody) } } } /** * @brief Test the body is dynamic or not. * * A dynamic body will effect with gravity. */ public var isDynamic = true { didSet { guard isDynamic != oldValue else { return } if isDynamic { cpBodySetType(chipmunkBody, CP_BODY_TYPE_DYNAMIC) internalBodySetMass(chipmunkBody, cpFloat(_mass)) cpBodySetMoment(chipmunkBody, cpFloat(_moment)) } else { cpBodySetType(chipmunkBody, CP_BODY_TYPE_KINEMATIC); } } } /** if the body is affected by the physics world's gravitational force or not. */ public var isGravityEnabled = false /** Whether the body can be rotated. */ public var isRotationEnabled = true { didSet { if isRotationEnabled != oldValue { cpBodySetMoment(chipmunkBody, isRotationEnabled ? cpFloat(_moment) : cpFloat.infinity) } } } // MARK: Properties /** set body rotation offset, it's the rotation witch relative to node */ public var rotationOffset: Angle { get { return _rotationOffset } set { if abs((_rotationOffset - newValue).degrees) > 0.5 { let rot = rotation _rotationOffset = newValue rotation = rot } } } /** get the body rotation. */ public var rotation: Angle { get { let cpAngle = Angle(radians: Float(cpBodyGetAngle(chipmunkBody))) if cpAngle != _recordedAngle { _recordedAngle = cpAngle _recordedRotation = -_recordedAngle - rotationOffset } return _recordedRotation } set { _recordedRotation = newValue _recordedAngle = -rotation - rotationOffset cpBodySetAngle(chipmunkBody, cpFloat(_recordedAngle.radians)) } } /** get the body position. */ public var position: Point { get { let tt = cpBodyGetPosition(chipmunkBody) return Point(tt) - positionOffset } set { cpBodySetPosition(chipmunkBody, cpVect(newValue + positionOffset)) } } /** set body position offset, it's the position which is relative to the node */ public var positionOffset: Vector2f { get { return _positionOffset } set { if _positionOffset != newValue { let pos = self.position _positionOffset = newValue self.position = pos } } } internal var scale: (x: Float, y: Float) = (x: 1.0, y: 1.0) { didSet { for shape in shapes { _area -= shape.area if !_massSetByUser { add(mass: -shape.mass) } if !_momentSetByUser { add(moment: -shape.moment) } // shape.scale = scale _area += shape.area if !_massSetByUser { add(mass: shape.mass) } if !_momentSetByUser { add(moment: shape.moment) } } } } /** * The velocity of a body. */ public var velocity: Vector2f { get { return Vector2f(cpBodyGetVelocity(chipmunkBody)) } set { guard isDynamic else { print("physics warning: your can't set velocity for a static body.") return } cpBodySetVelocity(chipmunkBody, cpVect(velocity)) } } /** The max of velocity */ public var velocityLimit: Float = Float.infinity /** * The angular velocity of a body. */ public var angularVelocity: Float { get { return Float(cpBodyGetAngularVelocity(chipmunkBody)) } set { guard isDynamic else { print("You can't set angular velocity for a static body.") return } cpBodySetAngularVelocity(chipmunkBody, cpFloat(newValue)) } } /** The max of angular velocity */ public var angularVelocityLimit: Float = Float.infinity /** * Linear damping. * * it is used to simulate fluid or air friction forces on the body. * @param damping The value is 0.0f to 1.0f. */ public var linearDamping: Float = 0.0 { didSet { updateDamping() } } /** * Angular damping. * * It is used to simulate fluid or air friction forces on the body. * @param damping The value is 0.0f to 1.0f. */ public var angularDamping: Float = 0.0 { didSet { updateDamping() } } private func updateDamping() { _isDamping = linearDamping != 0.0 || angularDamping != 0.0 } internal(set) public var shapes = [PhysicsShape]() internal(set) public var joints = [PhysicsJoint]() /** get the world body added to. */ internal(set) public weak var world: PhysicsWorld? = nil override init() { chipmunkBody = cpBodyNew(cpFloat(_mass), cpFloat(_moment)) super.init() internalBodySetMass(chipmunkBody, cpFloat(_mass)) cpBodySetUserData(chipmunkBody, Unmanaged.passUnretained(self).toOpaque()) cpBodySetVelocityUpdateFunc(chipmunkBody, internalBodyUpdateVelocity) } public var paused: Bool = false public func fixedUpdate(delta: Time) { // damping compute if (_isDamping && isDynamic && !isResting) { chipmunkBody.pointee.v.x *= cpfclamp(1.0 - cpFloat(delta * linearDamping), 0.0, 1.0) chipmunkBody.pointee.v.y *= cpfclamp(1.0 - cpFloat(delta * linearDamping), 0.0, 1.0) chipmunkBody.pointee.w *= cpfclamp(1.0 - cpFloat(delta * angularDamping), 0.0, 1.0) } } // MARK: Component stuff public var enabled: Bool = true { didSet { if oldValue != enabled { if enabled { world?.addBodyOrDelay(body: self) paused = false } else { world?.removeBodyOrDelay(body: self) paused = true } } } } public override func onAdd(to owner: Node) { super.onAdd(to: owner) let contentSize = owner.contentSizeInPoints ownerCenterOffset = contentSize * 0.5 rotationOffset = owner.rotation } // MARK: Internal vars /** The rigid body of chipmunk. */ internal let chipmunkBody: UnsafeMutablePointer<cpBody> // offset between owner's center point and down left point internal var ownerCenterOffset = Vector2f.zero // it means body's moment is not calculated by shapes internal var _momentSetByUser = false internal var _momentDefault = true internal var _moment: Float = MOMENT_DEFAULT // it means body's mass is not calculated by shapes internal var _massSetByUser = false internal var _massDefault = true internal var _mass: Float = MASS_DEFAULT internal var _density: Float = 0.0 internal var _area: Float = 0.0 internal var _recordPos = Point.zero internal var _offset = Vector2f.zero internal var _isDamping = false internal var _recordScaleX: Float = 0.0 internal var _recordScaleY: Float = 0.0 internal var _recordedRotation: Angle = 0° // MARK: Private vars private var _rotationOffset: Angle = 0° private var _recordedAngle: Angle = 0° private var _positionOffset: Vector2f = Vector2f.zero } extension PhysicsBody { func addToPhysicsWorld() { if let physicsSystem = owner?.scene?.system(for: PhysicsSystem.self) { physicsSystem.world.add(body: self) physicsSystem.dirty = true } } /** remove the body from the world it added to */ func removeFromPhysicsWorld() { if let physicsSystem = owner?.scene?.system(for: PhysicsSystem.self) { physicsSystem.world.remove(body: self) physicsSystem.dirty = true } } } public extension PhysicsBody { /** * Create a body contains a circle. * * @param radius A float number, it is the circle's radius. * @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT. * @param offset A Vec2 object, it is the offset from the body's center of gravity in body local coordinates. * @return An autoreleased PhysicsBody object pointer. */ public static func circle(radius: Float, material: PhysicsMaterial = PhysicsMaterial.default, offset: Vector2f = Vector2f.zero) -> PhysicsBody { let circleShape = PhysicsShapeCircle(radius: radius, material: material, offset: offset) let body = PhysicsBody() body.add(shape: circleShape) return body } /** * Create a body contains a box shape. * * @param size Size contains this box's width and height. * @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT. * @param offset A Vec2 object, it is the offset from the body's center of gravity in body local coordinates. * @return An autoreleased PhysicsBody object pointer. */ public static func box(size: Size, material: PhysicsMaterial = PhysicsMaterial.default, offset: Vector2f = Vector2f.zero) -> PhysicsBody { let boxShape = PhysicsShapeBox(size: size, material: material, offset: offset) let body = PhysicsBody() body.add(shape: boxShape) return body } }
1
0.786194
1
0.786194
game-dev
MEDIA
0.861674
game-dev
0.721649
1
0.721649
adventuregamestudio/ags
9,832
Engine/ac/dynobj/scriptgame.cpp
//============================================================================= // // Adventure Game Studio (AGS) // // Copyright (C) 1999-2011 Chris Jones and 2011-2025 various contributors // The full list of copyright holders can be found in the Copyright.txt // file, which is part of this source code distribution. // // The AGS source code is provided under the Artistic License 2.0. // A copy of this license can be found in the file License.txt and at // https://opensource.org/license/artistic-2-0/ // //============================================================================= #include "ac/dynobj/scriptgame.h" #include "ac/gamesetupstruct.h" #include "ac/game.h" #include "ac/gamesetup.h" #include "ac/gamestate.h" #include "ac/gui.h" #include "debug/debug_log.h" #include "script/cc_common.h" // cc_error using namespace AGS::Engine; extern GameSetupStruct game; CCScriptGame GameStaticManager; int32_t CCScriptGame::ReadInt32(const void *address, intptr_t offset) { const int index = offset / sizeof(int32_t); if (index >= 5 && index < 5 + MAXGLOBALVARS) return play.globalvars[index - 5]; switch (index) { case 0: return play.score; case 1: return play.usedmode; case 2: return play.disabled_user_interface; case 3: return play.gscript_timer; case 4: return play.debug_mode; // 5 -> 54: play.globalvars case 55: return play.messagetime; case 56: return play.usedinv; case 57: return play.inv_top; case 58: return play.inv_numdisp; case 59: return play.inv_numorder; case 60: return play.inv_numinline; case 61: return play.text_speed; case 62: return play.sierra_inv_color; case 63: return play.talkanim_speed; case 64: return play.inv_item_wid; case 65: return play.inv_item_hit; case 66: return play.speech_text_shadow; case 67: return play.swap_portrait_side; case 68: return play.speech_textwindow_gui; case 69: return play.follow_change_room_timer; case 70: return play.totalscore; case 71: return play.skip_display; case 72: return play.no_multiloop_repeat; case 73: return play.roomscript_finished; case 74: return play.used_inv_on; case 75: return play.no_textbg_when_voice; case 76: return play.max_dialogoption_width; case 77: return play.no_hicolor_fadein; case 78: return play.bgspeech_game_speed; case 79: return play.bgspeech_stay_on_display; case 80: return play.unfactor_speech_from_textlength; case 81: return play.mp3_loop_before_end; case 82: return play.speech_music_drop; case 83: return play.in_cutscene; case 84: return play.fast_forward; case 85: return play.room_width; case 86: return play.room_height; case 87: return play.game_speed_modifier; case 88: return play.score_sound; case 89: return play.takeover_data; case 90: return 0; // play.replay_hotkey case 91: return play.dialog_options_pad_x; case 92: return play.dialog_options_pad_y; case 93: return play.narrator_speech; case 94: return play.ambient_sounds_persist; case 95: return play.lipsync_speed; case 96: return play.close_mouth_speech_time; case 97: return play.disable_antialiasing; case 98: return play.text_speed_modifier; case 99: return play.text_align; case 100: return play.speech_bubble_width; case 101: return play.min_dialogoption_width; case 102: return play.disable_dialog_parser; case 103: return play.anim_background_speed; case 104: return play.top_bar_backcolor; case 105: return play.top_bar_textcolor; case 106: return play.top_bar_bordercolor; case 107: return play.top_bar_borderwidth; case 108: return play.top_bar_ypos; case 109: return play.screenshot_width; case 110: return play.screenshot_height; case 111: return play.top_bar_font; case 112: return play.speech_text_align; case 113: return play.auto_use_walkto_points; case 114: return play.inventory_greys_out; case 115: return play.skip_speech_specific_key; case 116: return play.abort_key; case 117: return play.fade_to_red; case 118: return play.fade_to_green; case 119: return play.fade_to_blue; case 120: return play.show_single_dialog_option; case 121: return play.keep_screen_during_instant_transition; case 122: return play.read_dialog_option_colour; case 123: return play.stop_dialog_at_end; case 124: return play.speech_portrait_placement; case 125: return play.speech_portrait_x; case 126: return play.speech_portrait_y; case 127: return play.speech_display_post_time_ms; case 128: return play.dialog_options_highlight_color; default: cc_error("ScriptGame: unsupported variable offset %d", offset); return 0; } } void CCScriptGame::WriteInt32(void *address, intptr_t offset, int32_t val) { const int index = offset / sizeof(int32_t); if (index >= 5 && index < 5 + MAXGLOBALVARS) { play.globalvars[index - 5] = val; return; } switch (index) { case 0: play.score = val; break; case 1: play.usedmode = val; break; case 2: play.disabled_user_interface = val; break; case 3: play.gscript_timer = val; break; case 4: set_debug_mode(val != 0); break; // play.debug_mode // 5 -> 54: play.globalvars case 55: play.messagetime = val; break; case 56: play.usedinv = val; break; case 57: play.inv_top = val; GUIE::MarkInventoryForUpdate(game.playercharacter, true); break; case 58: // play.inv_numdisp case 59: // play.inv_numorder case 60: // play.inv_numinline debug_script_warn("ScriptGame: attempt to write in readonly variable at offset %d, value %d", offset, val); break; case 61: if (usetup.Access.TextReadSpeed <= 0) play.text_speed = val; break; case 62: play.sierra_inv_color = val; break; case 63: play.talkanim_speed = val; break; case 64: play.inv_item_wid = val; break; case 65: play.inv_item_hit = val; break; case 66: play.speech_text_shadow = val; break; case 67: play.swap_portrait_side = val; break; case 68: play.speech_textwindow_gui = val; break; case 69: play.follow_change_room_timer = val; break; case 70: play.totalscore = val; break; case 71: if (usetup.Access.TextSkipStyle == kSkipSpeechNone) play.skip_display = static_cast<SkipSpeechStyle>(val); break; case 72: play.no_multiloop_repeat = val; break; case 73: play.roomscript_finished = val; break; case 74: play.used_inv_on = val; break; case 75: play.no_textbg_when_voice = val; break; case 76: play.max_dialogoption_width = val; break; case 77: play.no_hicolor_fadein = val; break; case 78: play.bgspeech_game_speed = val; break; case 79: play.bgspeech_stay_on_display = val; break; case 80: play.unfactor_speech_from_textlength = val; break; case 81: play.mp3_loop_before_end = val; break; case 82: play.speech_music_drop = val; break; case 83: // play.in_cutscene case 84: // play.fast_forward; case 85: // play.room_width; case 86: // play.room_height; debug_script_warn("ScriptGame: attempt to write in readonly variable at offset %d, value %d", offset, val); break; case 87: play.game_speed_modifier = val; break; case 88: play.score_sound = val; break; case 89: play.takeover_data = val; break; case 90: break; // play.replay_hotkey case 91: play.dialog_options_pad_x = val; break; case 92: play.dialog_options_pad_y = val; break; case 93: play.narrator_speech = val; break; case 94: play.ambient_sounds_persist = val; break; case 95: play.lipsync_speed = val; break; case 96: play.close_mouth_speech_time = val; break; case 97: play.disable_antialiasing = val; break; case 98: play.text_speed_modifier = val; break; case 99: play.text_align = ReadScriptAlignment(val); break; case 100: play.speech_bubble_width = val; break; case 101: play.min_dialogoption_width = val; break; case 102: play.disable_dialog_parser = val; break; case 103: play.anim_background_speed = val; break; case 104: play.top_bar_backcolor = val; break; case 105: play.top_bar_textcolor = val; break; case 106: play.top_bar_bordercolor = val; break; case 107: play.top_bar_borderwidth = val; break; case 108: play.top_bar_ypos = val; break; case 109: play.screenshot_width = val; break; case 110: play.screenshot_height = val; break; case 111: play.top_bar_font = val; break; case 112: play.speech_text_align = ReadScriptAlignment(val); break; case 113: play.auto_use_walkto_points = val; break; case 114: play.inventory_greys_out = val; break; case 115: play.skip_speech_specific_key = val; break; case 116: play.abort_key = val; break; case 117: // play.fade_to_red; case 118: // play.fade_to_green; case 119: // play.fade_to_blue; debug_script_warn("ScriptGame: attempt to write in readonly variable at offset %d, value %d", offset, val); break; case 120: play.show_single_dialog_option = val; break; case 121: play.keep_screen_during_instant_transition = val; break; case 122: play.read_dialog_option_colour = val; break; case 123: play.stop_dialog_at_end = val; break; case 124: play.speech_portrait_placement = val; break; case 125: play.speech_portrait_x = val; break; case 126: play.speech_portrait_y = val; break; case 127: play.speech_display_post_time_ms = val; break; case 128: play.dialog_options_highlight_color = val; break; default: cc_error("ScriptGame: unsupported variable offset %d", offset); break; } }
1
0.57171
1
0.57171
game-dev
MEDIA
0.66813
game-dev
0.702215
1
0.702215
LearnCocos2D/cocos2d-iphone-arc-templates
5,277
cocos2d-1.x-Box2D-ARC-iOS/cocos2d-1.x-Box2D-ARC-iOS/libs/Box2D/Common/b2Settings.h
/* * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * 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 B2_SETTINGS_H #define B2_SETTINGS_H #include <cassert> #include <cmath> #define B2_NOT_USED(x) ((void)(x)) #define b2Assert(A) assert(A) typedef signed char int8; typedef signed short int16; typedef signed int int32; typedef unsigned char uint8; typedef unsigned short uint16; typedef unsigned int uint32; typedef float float32; #define b2_maxFloat FLT_MAX #define b2_epsilon FLT_EPSILON #define b2_pi 3.14159265359f /// @file /// Global tuning constants based on meters-kilograms-seconds (MKS) units. /// // Collision /// The maximum number of contact points between two convex shapes. #define b2_maxManifoldPoints 2 /// The maximum number of vertices on a convex polygon. #define b2_maxPolygonVertices 8 /// This is used to fatten AABBs in the dynamic tree. This allows proxies /// to move by a small amount without triggering a tree adjustment. /// This is in meters. #define b2_aabbExtension 0.1f /// This is used to fatten AABBs in the dynamic tree. This is used to predict /// the future position based on the current displacement. /// This is a dimensionless multiplier. #define b2_aabbMultiplier 2.0f /// A small length used as a collision and constraint tolerance. Usually it is /// chosen to be numerically significant, but visually insignificant. #define b2_linearSlop 0.005f /// A small angle used as a collision and constraint tolerance. Usually it is /// chosen to be numerically significant, but visually insignificant. #define b2_angularSlop (2.0f / 180.0f * b2_pi) /// The radius of the polygon/edge shape skin. This should not be modified. Making /// this smaller means polygons will have an insufficient buffer for continuous collision. /// Making it larger may create artifacts for vertex collision. #define b2_polygonRadius (2.0f * b2_linearSlop) // Dynamics /// Maximum number of contacts to be handled to solve a TOI impact. #define b2_maxTOIContacts 32 /// A velocity threshold for elastic collisions. Any collision with a relative linear /// velocity below this threshold will be treated as inelastic. #define b2_velocityThreshold 1.0f /// The maximum linear position correction used when solving constraints. This helps to /// prevent overshoot. #define b2_maxLinearCorrection 0.2f /// The maximum angular position correction used when solving constraints. This helps to /// prevent overshoot. #define b2_maxAngularCorrection (8.0f / 180.0f * b2_pi) /// The maximum linear velocity of a body. This limit is very large and is used /// to prevent numerical problems. You shouldn't need to adjust this. #define b2_maxTranslation 2.0f #define b2_maxTranslationSquared (b2_maxTranslation * b2_maxTranslation) /// The maximum angular velocity of a body. This limit is very large and is used /// to prevent numerical problems. You shouldn't need to adjust this. #define b2_maxRotation (0.5f * b2_pi) #define b2_maxRotationSquared (b2_maxRotation * b2_maxRotation) /// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so /// that overlap is removed in one time step. However using values close to 1 often lead /// to overshoot. #define b2_contactBaumgarte 0.2f // Sleep /// The time that a body must be still before it will go to sleep. #define b2_timeToSleep 0.5f /// A body cannot sleep if its linear velocity is above this tolerance. #define b2_linearSleepTolerance 0.01f /// A body cannot sleep if its angular velocity is above this tolerance. #define b2_angularSleepTolerance (2.0f / 180.0f * b2_pi) // Memory Allocation /// Implement this function to use your own memory allocator. void* b2Alloc(int32 size); /// If you implement b2Alloc, you should also implement this function. void b2Free(void* mem); /// Version numbering scheme. /// See http://en.wikipedia.org/wiki/Software_versioning struct b2Version { int32 major; ///< significant changes int32 minor; ///< incremental changes int32 revision; ///< bug fixes }; /// Current version. extern b2Version b2_version; /// Friction mixing law. Feel free to customize this. inline float32 b2MixFriction(float32 friction1, float32 friction2) { return sqrtf(friction1 * friction2); } /// Restitution mixing law. Feel free to customize this. inline float32 b2MixRestitution(float32 restitution1, float32 restitution2) { return restitution1 > restitution2 ? restitution1 : restitution2; } #endif
1
0.935181
1
0.935181
game-dev
MEDIA
0.719991
game-dev
0.900264
1
0.900264
shanecoughlan/OpenGEM
29,600
source/OpenGEM-7-RC1-SDK/OpenGEM-7-SDK/PRINTER DRIVERS AND SOURCE CODE/GEM Printer Drivers - Source Code/COMMON/MONOPRIN.C
/************************************************************************* ** Copyright 1999, Caldera Thin Clients, Inc. ** ** This software is licenced under the GNU Public License. ** ** Please see LICENSE.TXT for further information. ** ** ** ** Historical Copyright ** ** ** ** ** ** Copyright (c) 1987, Digital Research, Inc. All Rights Reserved. ** ** The Software Code contained in this listing is proprietary to ** ** Digital Research, Inc., Monterey, California and is covered by U.S. ** ** and other copyright protection. Unauthorized copying, adaptation, ** ** distribution, use or display is prohibited and may be subject to ** ** civil and criminal penalties. Disclosure to others is prohibited. ** ** For the terms and conditions of software code use refer to the ** ** appropriate Digital Research License Agreement. ** ** ** *************************************************************************/ #include "portab.h" #include "gsxdef.h" #include "defines.h" #define FF_ALWAYS 1 /* adv_form() param */ #if Y_ASPECT > X_ASPECT GLOBAL WORD q_circle[MAX_L_WIDTH]; #else GLOBAL WORD q_circle[(MAX_L_WIDTH*X_ASPECT/Y_ASPECT)/2 + 1]; #endif GLOBAL WORD TOKEN = 0; GLOBAL WORD WINDOW = 0; GLOBAL WORD XW_MAX = 0; GLOBAL WORD XW_MIN = 0; GLOBAL WORD YCL_MAX = 0; GLOBAL WORD YCL_MIN = 0; GLOBAL WORD YW_MAX = 0; GLOBAL WORD YW_MIN = 0; GLOBAL WORD angle = 0; GLOBAL WORD beg_ang = 0; GLOBAL WORD copies = 0; GLOBAL WORD d_clip = 0; GLOBAL WORD d_fa_color = 0; GLOBAL WORD d_fa_index = 0; GLOBAL WORD d_fa_style = 0; GLOBAL WORD d_fill_per = 0; GLOBAL WORD d_ln_beg = 0; GLOBAL WORD d_ln_color = 0; GLOBAL WORD d_ln_end = 0; GLOBAL WORD d_ln_index = 0; GLOBAL WORD d_ln_width = 0; GLOBAL WORD d_mk_color = 0; GLOBAL WORD d_mk_height = 0; GLOBAL WORD d_mk_index = 0; GLOBAL WORD d_mk_scale = 0; GLOBAL WORD d_patmsk = 0; GLOBAL WORD d_qc_fill = 0; GLOBAL WORD d_qc_line = 0; GLOBAL WORD d_qc_mark = 0; GLOBAL WORD d_qi_fill = 0; GLOBAL WORD d_qi_line = 0; GLOBAL WORD d_qi_mark = 0; GLOBAL WORD d_wrt_mode = 0; GLOBAL WORD d_xmn_clip = 0; GLOBAL WORD d_xmx_clip = 0; GLOBAL WORD d_ycl_max = 0; GLOBAL WORD d_ycl_min = 0; GLOBAL WORD del_ang = 0; GLOBAL WORD deltay1 = 0; GLOBAL WORD deltay2 = 0; GLOBAL WORD deltay = 0; GLOBAL WORD end_ang = 0; GLOBAL WORD fcl_xmax = 0; GLOBAL WORD fcl_xmin = 0; GLOBAL WORD fcl_ymax = 0; GLOBAL WORD fcl_ymin = 0; GLOBAL WORD fill_color = 0; GLOBAL WORD fill_index = 0; GLOBAL WORD fill_intersect = 0; GLOBAL WORD fill_maxy = 0; GLOBAL WORD fill_miny = 0; GLOBAL WORD fill_per = 0; GLOBAL WORD fill_qc = 0; GLOBAL WORD fill_qi = 0; GLOBAL WORD fill_style = 0; GLOBAL WORD line_beg = 0; GLOBAL WORD line_color = 0; GLOBAL WORD line_end = 0; GLOBAL WORD line_index = 0; GLOBAL WORD line_qc = 0; GLOBAL WORD line_qi = 0; GLOBAL WORD line_qw = 0; GLOBAL WORD line_width = 0; GLOBAL WORD mark_color = 0; GLOBAL WORD mark_height = 0; GLOBAL WORD mark_index = 0; GLOBAL WORD mark_qc = 0; GLOBAL WORD mark_qi = 0; GLOBAL WORD mark_scale = 0; GLOBAL WORD n_steps = 0; GLOBAL WORD need_update = 0; GLOBAL WORD new_clip = 0; GLOBAL WORD num_qc_lines = 0; GLOBAL WORD odeltay = 0; GLOBAL WORD p_orient = 0; GLOBAL WORD patmsk = 0; GLOBAL WORD s_begsty = 0; GLOBAL WORD s_endsty = 0; GLOBAL WORD s_fill_color = 0; GLOBAL WORD s_fill_per = 0; GLOBAL WORD s_patmsk = 0; GLOBAL WORD start = 0; GLOBAL WORD tray = 0; GLOBAL WORD write_qm = 0; GLOBAL WORD xc = 0; GLOBAL WORD xmn_rect = 0; GLOBAL WORD xmx_rect = 0; GLOBAL WORD xrad = 0; GLOBAL WORD y = 0; GLOBAL WORD yc = 0; GLOBAL WORD ymn_rect = 0; GLOBAL WORD ymx_rect = 0; GLOBAL WORD yrad = 0; GLOBAL WORD *d_patptr = 0; GLOBAL WORD *patptr = 0; GLOBAL WORD *s_patptr = 0; EXTERN BOOLEAN Abort; EXTERN BOOLEAN Bitmap; EXTERN BOOLEAN dv_loaded; EXTERN WORD clip; EXTERN WORD FLIP_Y; EXTERN WORD VMU; EXTERN WORD WRT_MODE; EXTERN WORD xmn_clip; EXTERN WORD xmx_clip; EXTERN WORD Y1; EXTERN WORD Y2; EXTERN WORD ymn_clip; EXTERN WORD ymx_clip; EXTERN WORD YS_MAX; EXTERN WORD YS_MIN; EXTERN WORD g_devdcnt; EXTERN WORD g_devdout; EXTERN WORD loaded; EXTERN BYTE CURALPHA; EXTERN BYTE REQALPHA; EXTERN WORD CONTRL[]; EXTERN WORD dev_tab[]; EXTERN WORD INTIN[]; EXTERN WORD INTOUT[]; EXTERN WORD LINE_STYL[]; EXTERN WORD MAP_COL[]; EXTERN WORD PTSIN[]; EXTERN WORD PTSOUT[]; EXTERN WORD siz_tab[]; EXTERN WORD UD_PATRN[]; EXTERN WORD range(); EXTERN VOID v_pmarker(); EXTERN VOID v_pline(); EXTERN VOID Put_Poly(); EXTERN VOID s_orient(); EXTERN VOID PT_OP_BY(); EXTERN VOID dqt_extent(); EXTERN VOID bound_rect(); EXTERN VOID PT_PTSIN(); EXTERN VOID PT_INTIN(); EXTERN VOID just_chk(); EXTERN VOID GT_PTSIN(); EXTERN VOID GT_INTIN(); EXTERN VOID v_gtext(); EXTERN VOID plygn(); EXTERN VOID v_filrec(); EXTERN WORD MUL_DIV(); EXTERN VOID PT_OP_WD(); EXTERN VOID GT_WORD(); EXTERN VOID v_gdp(); EXTERN VOID st_fl_ptr(); EXTERN VOID GT_BYTE(); EXTERN WORD dvt_fres(); EXTERN VOID open_sp(); EXTERN VOID clearmem(); EXTERN VOID init_p(); EXTERN VOID init_dev(); EXTERN VOID save_text_defaults(); EXTERN VOID reset_text_defaults(); EXTERN VOID dini_dev(); EXTERN VOID dinit_p(); EXTERN VOID close_sp(); EXTERN VOID adv_form(); EXTERN VOID out_win(); EXTERN VOID clear_sp(); EXTERN VOID dvt_clear(); EXTERN VOID ini_bufs(); EXTERN VOID c_image(); /* image.c */ EXTERN WORD r_image(); /* image.c */ EXTERN VOID clear_image(); /* image.c */ EXTERN VOID init_lfu(); EXTERN VOID q_scan(); EXTERN VOID alpha_text(); EXTERN VOID Get_Poly(); EXTERN VOID save_defaults(); #if cdo_text EXTERN VOID dvt_dflag(); EXTERN BOOLEAN font_type(); #define DEVICE 1 /* font_type() return */ #endif #if autocopy EXTERN VOID set_copies(); #endif /**************************************************/ VOID v_nop() { } /* end v_nop() */ /**************************************************/ VOID init_rect() { xmx_rect = ymx_rect = 0; xmn_rect = xres; ymn_rect = yres; new_clip = TRUE; } /* end init_rect() */ /**************************************************/ VOID chk_clip() { if (xmn_clip < xmn_rect) xmn_rect = xmn_clip; if (xmx_clip > xmx_rect) xmx_rect = xmx_clip; if (YCL_MIN < ymn_rect) ymn_rect = YCL_MIN; if (YCL_MAX > ymx_rect) ymx_rect = YCL_MAX; new_clip = FALSE; } /* end chk_clip() */ /**************************************************/ VOID c_escape() { switch (CONTRL[5]) { case 1: /* inquire addressable character cells */ CONTRL[4] = 2; INTOUT[0] = INTOUT[1] = -1; break; case 20: /* advance form */ adv_form(FF_ALWAYS); break; case 21: /* output window */ need_update = TRUE; out_win(); break; case 22: /* clear display list */ clear_sp(); dvt_clear(); ini_bufs(); clearmem(); clear_image(); save_defaults(); init_lfu(); init_rect(); Bitmap = g_devdcnt = FALSE; break; case 23: /* output bit image */ case 101: /* output rotated bit image */ if (new_clip) chk_clip(); need_update= TRUE; c_image(); Bitmap = TRUE; break; case 24: /* inquire printer scan heights */ q_scan(); break; case 25: /* output alpha text */ need_update = TRUE; alpha_text(); Bitmap = TRUE; break; case 27: /* set page orientation */ p_orient = INTIN[0]; s_orient(); break; case 28: /* set # copies */ #if autocopy set_copies(INTIN[0]); #else if (INTIN[0] > 0) copies = INTIN[0]; #endif break; case 29: /* set paper tray */ tray = INTIN[0]; break; } /* end switch */ } /* end c_escape() */ /**************************************************/ VOID r_escape() { GT_BYTE(); if ((TOKEN == 23 || TOKEN == 101) && (!g_devdout)) r_image(); } /* end r_escape() */ /**************************************************/ VOID c_pline() { if (new_clip) chk_clip(); Put_Poly(0); Bitmap = need_update = TRUE; } /* end c_pline() */ /**************************************************/ VOID r_pline() { WORD offset; Get_Poly(); if (!g_devdout) { offset = ( (line_beg | line_end) & ARROWED) ? 4*num_qc_lines : num_qc_lines; if (Y1 - offset <= YS_MAX && Y2 + offset >= YS_MIN) v_pline(); } } /* end r_pline() */ /**************************************************/ VOID c_pmarker() { if (new_clip) chk_clip(); Put_Poly((mark_height + 1) << 1); Bitmap = need_update = TRUE; } /* end c_pmarker() */ /**************************************************/ VOID r_pmarker() { Get_Poly(); if (!g_devdout && Y1 <= YS_MAX && Y2 >= YS_MIN) v_pmarker(); } /* end r_pmarker() */ /**************************************************/ VOID c_gtext() { WORD i, x_save, y_save; #if cdo_text if (font_type() == DEVICE) dvt_dflag(); else if (new_clip) chk_clip(); #endif if (!loaded && !dv_loaded && (CONTRL[3] <= 0)) return; #if cdo_text if (font_type() != DEVICE) { #endif /* If the writing mode is replace, output appropriate bar. */ if (WRT_MODE == 0) { /* Output commands to set the fill area color to */ /* background and the fill area style to solid. */ /* Turn the perimeter visibility off. */ if (fill_color) { TOKEN = 0; CONTRL[0] = 25; PT_OP_BY(); } /* End if: must send fill color. */ if (fill_style != 1) { TOKEN = 1; CONTRL[0] = 23; PT_OP_BY(); } /* End if: must send fill area style. */ if (fill_per) { TOKEN = FALSE; CONTRL[0] = 104; PT_OP_BY(); } /* End if: turn off fill perimeter visibility. */ /* Find the text extents. */ x_save = PTSIN[0]; y_save = PTSIN[1]; dqt_extent(); CONTRL[2] = 0; /* Get the bounding rectangle and output a bar. */ bound_rect(); for (i = 0; i < 4; i++) PTSIN[i] = PTSOUT[i]; CONTRL[0] = 11; TOKEN = 1; PT_OP_BY(); CONTRL[1] = 2; PT_PTSIN(); /* Restore. */ if (fill_color) { TOKEN = fill_color; CONTRL[0] = 25; PT_OP_BY(); } /* End if: must restore fill color. */ if (fill_style != 1) { TOKEN = fill_style; CONTRL[0] = 23; PT_OP_BY(); } /* End if: must restore fill area style. */ if (fill_per) { TOKEN = fill_per; CONTRL[0] = 104; PT_OP_BY(); } /* End if: restore fill perimeter visibility. */ /* Restore the parameter arrays. */ PTSIN[0] = x_save; PTSIN[1] = y_save; CONTRL[0] = 8; } /* End if: replace mode. */ #if cdo_text } /* end if: font_type() != DEVICE */ #endif CONTRL[1] = 1; TOKEN = CONTRL[3]; PT_OP_BY(); PT_PTSIN(); PT_INTIN(); need_update = TRUE; just_chk(); } /* end c_gtext() */ /**************************************************/ VOID r_gtext() { GT_BYTE(); CONTRL [3] = TOKEN; CONTRL[1] = 1; GT_PTSIN(); GT_INTIN(); v_gtext(); } /* end r_gtext() */ /**************************************************/ VOID c_fillarea() { if (new_clip) chk_clip(); Put_Poly(0); Bitmap = need_update = TRUE; } /* end c_fillarea() */ /**************************************************/ VOID r_fillarea() { Get_Poly(); if (!g_devdout && Y1 <= YS_MAX && Y2 >= YS_MIN) plygn(); } /* end r_fillarea() */ /**************************************************/ VOID clip_x(xptr) WORD *xptr; { WORD x; x = *xptr; if (x < xmn_clip) *xptr = xmn_clip; else if (x > xmx_clip) *xptr = xmx_clip; } /* end clip_x() */ /**************************************************/ VOID clip_y(yptr) WORD *yptr; { WORD y; y = *yptr; if (y < YCL_MIN) *yptr = YCL_MIN; else if (y > YCL_MAX) *yptr = YCL_MAX; } /* end clip_y() */ /**************************************************/ VOID arb_corner(xy, type) WORD xy[], type; { WORD temp; /* Fix the x coordinate values, if necessary. */ if (xy[0] > xy[2]) { temp = xy[0]; xy[0] = xy[2]; xy[2] = temp; } /* End if: "x" values need to be swapped. */ /* Fix y values based on whether traditional (ll, ur) or raster-op */ /* (ul, lr) format is desired. */ if ((type == LLUR && xy[1] < xy[3]) || (type == ULLR && xy[1] > xy[3])) { temp = xy[1]; xy[1] = xy[3]; xy[3] = temp; } /* End if: "y" values need to be swapped. */ } /* end arb_corner() */ /**************************************************/ VOID c_filrec() { WORD isdev; #if MIN_L_WIDTH > 1 WORD dx, dy; #endif isdev = 0; if ((PTSIN[0] < xmn_clip && PTSIN[2] < xmn_clip) || (PTSIN[0] > xmx_clip && PTSIN[2] > xmx_clip) || (PTSIN[1] < YCL_MIN && PTSIN[3] < YCL_MIN) || (PTSIN[1] > YCL_MAX && PTSIN[3] > YCL_MAX)) return; clip_x(&PTSIN[0]); clip_y(&PTSIN[1]); clip_x(&PTSIN[2]); clip_y(&PTSIN[3]); #if cdo_rule #if no_tintrule if ((fill_style == 1) || (fill_style == 2 && fill_index == 7 && fill_color != 0)) { g_devdcnt = TRUE; arb_corner(PTSIN, ULLR); isdev = 1; } /* End if: solid. */ else { if (new_clip) chk_clip(); arb_corner(PTSIN, LLUR); Bitmap = TRUE; } /* End else: patterned. */ #else g_devdcnt = TRUE; arb_corner(PTSIN, ULLR); isdev = 1; #endif #else if (new_clip) chk_clip(); arb_corner(PTSIN, LLUR); Bitmap = TRUE; #endif #if MIN_L_WIDTH > 1 dx = PTSIN[2] - PTSIN[0]; if (dx < 0) dx = -dx; dy = PTSIN[3] - PTSIN[1]; if (dy < 0) dy = -dy; if (dx < MIN_L_WIDTH) PTSIN[2] = PTSIN[0] + MIN_L_WIDTH; if (dy < MIN_L_WIDTH) { if (PTSIN[3] < PTSIN[1]) PTSIN[3] = PTSIN[1] - MIN_L_WIDTH; else PTSIN[1] = PTSIN[3] - MIN_L_WIDTH; PTSIN[2] += MIN_L_WIDTH; } /* End if: y must be stretched. */ if (isdev) arb_corner(PTSIN, ULLR); else arb_corner(PTSIN, LLUR); #endif Put_Poly(0); need_update = TRUE; } /* end c_filrec */ /**************************************************/ VOID r_filrec() { Get_Poly(); v_filrec(); } /* end r_filrec() */ /**************************************************/ VOID c_gdp() { WORD i; TOKEN = CONTRL[5]; if (TOKEN > 0 && TOKEN < 12) { PT_OP_BY(); if (TOKEN < 10) { Bitmap = TRUE; if (new_clip) chk_clip(); } switch (TOKEN) { case 1: /* GDP BAR */ case 8: /* GDP ROUNDED RECTANGLE */ case 9: /* GDP FILLED ROUNDED RECTANGLE */ CONTRL[1] = 2; arb_corner(PTSIN, LLUR); PT_PTSIN(); break; case 2: /* GDP ARC */ case 3: /* GDP PIE */ CONTRL[1] = 5; yrad = MUL_DIV(PTSIN[6], xsize, ysize); PTSIN[8] = PTSIN[1] - yrad; PTSIN[9] = PTSIN[1] + yrad; PT_PTSIN(); CONTRL[3] = 2; PT_INTIN(); break; case 4: /* GDP CIRCLE */ CONTRL[1] = 4; yrad = MUL_DIV(PTSIN[4], xsize, ysize); PTSIN[6] = PTSIN[1] - yrad; PTSIN[7] = PTSIN[1] + yrad; PT_PTSIN(); break; case 5: /* GDP ELLIPSE */ CONTRL[1] = 3; PTSIN[4] = PTSIN[1] - PTSIN[3]; PTSIN[5] = PTSIN[1] + PTSIN[3]; PT_PTSIN(); break; case 6: /* GDP ELLIPTICAL ARC */ case 7: /* GDP ELLIPTICAL PIE */ CONTRL[1] = 3; PTSIN[4] = PTSIN[1] - PTSIN[3]; PTSIN[5] = PTSIN[1] + PTSIN[3]; PT_PTSIN(); CONTRL[3] = 2; PT_INTIN(); break; case 10: /* GDP JUSTIFIED TEXT */ CONTRL[1] = 2; PT_PTSIN(); TOKEN = CONTRL[3]; PT_OP_WD(); PT_INTIN(); just_chk(); #if cdo_text if (font_type() == DEVICE) dvt_dflag(); #endif break; case 11: /* GDP ESCAPEMENT TEXT */ TOKEN = CONTRL[3]; PT_OP_WD(); PT_INTIN(); CONTRL[1] = CONTRL[3] + 1; for (i = 2; i < CONTRL[1]; i++) PTSIN[i] = PTSIN[(i - 1) << 1]; CONTRL[1] = (CONTRL[1] + 1) >> 1; PT_PTSIN(); just_chk(); #if cdo_text if (font_type() == DEVICE) dvt_dflag(); #endif break; } } need_update = TRUE; } /* end c_gdp() */ /**************************************************/ VOID r_gdp() { WORD offset; GT_BYTE(); CONTRL[5] = TOKEN; switch (TOKEN) { case 2: /* GDP ARC */ case 6: /* GDP ELLIPTICAL ARC */ case 8: /* GDP ROUNDED RECTANGLE */ offset = ( (line_beg | line_end) & ARROWED) ? 4*num_qc_lines : num_qc_lines; break; case 1: /* GDP BAR */ case 3: /* GDP PIE */ case 4: /* GDP CIRCLE */ case 5: /* GDP ELLIPSE */ case 7: /* GDP ELLIPTICAL PIE */ case 9: /* GDP FILLED ROUNDED RECTANGLE */ case 10: /* GDP JUSTIFIED TEXT */ case 11: /* GDP ESCAPEMENT TEXT */ offset = 0; break; } /* End switch. */ switch (TOKEN) { case 1: /* GDP BAR */ case 8: /* GDP ROUNDED RECTANGLE */ case 9: /* GDP FILLED ROUNDED RECTANGLE */ CONTRL[1] = 2; GT_PTSIN(); if (PTSIN[1] + offset < YS_MIN || PTSIN[3] - offset > YS_MAX) return; break; case 2: /* GDP ARC */ case 3: /* GDP PIE */ CONTRL[1] = 5; GT_PTSIN(); CONTRL[3] = 2; GT_INTIN(); if (PTSIN[9] + offset < YS_MIN || PTSIN[8] - offset > YS_MAX) return; break; case 4: /* GDP CIRCLE */ CONTRL[1] = 4; GT_PTSIN(); if (PTSIN[7] < YS_MIN || PTSIN[6] > YS_MAX) return; break; case 5: /* GDP ELLIPSE */ CONTRL[1] = 3; GT_PTSIN(); if (PTSIN[5] < YS_MIN || PTSIN[4] > YS_MAX) return; break; case 6: /* GDP ELLIPTICAL ARC */ case 7: /* GDP ELLIPTICAL PIE */ CONTRL[1] = 3; GT_PTSIN(); CONTRL[3] = 2; GT_INTIN(); if (PTSIN[5] + offset < YS_MIN || PTSIN[4] - offset > YS_MAX) return; break; case 10: /* GDP JUSTIFIED TEXT */ CONTRL[1] = 2; GT_PTSIN(); GT_BYTE(); GT_WORD(); CONTRL[3] = TOKEN; GT_INTIN(); break; case 11: /* GDP ESCAPEMENT TEXT */ GT_BYTE(); GT_WORD(); CONTRL[3] = TOKEN; GT_INTIN(); CONTRL[1] = (CONTRL[3] + 2) >> 1; GT_PTSIN(); break; } /* End switch. */ v_gdp(); } /* end r_gdp() */ /**************************************************/ VOID csl_type() { CONTRL[4]=1; TOKEN = range(INTIN[0] - 1, 0, MAX_LINE_STYLE, 0); if (TOKEN != line_index) { line_qi = (line_index = TOKEN) + 1; PT_OP_BY(); } INTOUT[0] = line_qi; } /* end csl_type() */ /**************************************************/ VOID rsl_type() { GT_BYTE(); line_qi = (line_index = TOKEN) + 1; } /* end rsl_type() */ /**************************************************/ VOID csl_width() { TOKEN = PTSIN[0]; if (TOKEN > MAX_L_WIDTH) TOKEN = MAX_L_WIDTH; else if (TOKEN <= MIN_L_WIDTH) TOKEN = 1; /* Make the line width an odd number (one less, if even). */ TOKEN = (((TOKEN - 1) >> 1) << 1) + 1; if (TOKEN != line_width) { line_width = TOKEN; PT_OP_WD(); } CONTRL[2] = 1; PTSOUT[0] = line_qw = line_width; PTSOUT[1] = 0; } /* end csl_width() */ /**************************************************/ VOID rsl_width() { WORD i, x, y, d; #if Y_ASPECT > X_ASPECT WORD j, low, high; #endif /* Return if the line width is being set to one. */ GT_WORD(); if ( (line_qw = line_width = TOKEN) == 1) return; /* Initialize the circle DDA. "y" is set to the radius. */ x = 0; y = (line_width + 1) >> 1; d = 3 - 2*y; /* Do an octant, starting at north. The values for the next octant */ /* (clockwise) will be filled by transposing x and y. */ while (x < y) { q_circle[y] = x; q_circle[x] = y; if (d < 0) d = d + 4*x + 6; else { d = d + 4*(x - y) + 10; y--; } /* End else. */ x++; } /* End while. */ if (x == y) q_circle[x] = x; /* Calculate the number of vertical pixels required. */ num_qc_lines = ((line_width*xsize/ysize) >> 1) + 1; /* Fake a pixel averaging when converting to non-1:1 aspect ratio. */ #if Y_ASPECT > X_ASPECT low = 0; for (i = 0; i < num_qc_lines; i++) { high = (((i << 1) + 1)*ysize/xsize) >> 1; d = 0; for (j = low; j <= high; j++) d += q_circle[j]; q_circle[i] = d/(high - low + 1); low = high + 1; } /* End for loop. */ #else for (i = num_qc_lines - 1; i >= 0; i--) q_circle[i] = q_circle[((i << 1)*ysize/xsize + 1) >> 1]; #endif } /* end rsl_width() */ /**************************************************/ VOID csl_ends() { CONTRL[4] = 2; INTOUT[0] = line_beg = INTIN[0] = range(INTIN[0], 0, 2, 0); INTOUT[1] = line_end = INTIN[1] = range(INTIN[1], 0, 2, 0); PT_OP_BY(); PT_INTIN(); } /* end csl_ends() */ /**************************************************/ VOID rsl_ends() { CONTRL[3] = 2; GT_BYTE(); GT_INTIN(); line_beg = INTIN[0]; line_end = INTIN[1]; } /* end rsl_ends() */ /**************************************************/ VOID csl_color() { CONTRL[4]=1; INTOUT[0] = line_qc = TOKEN = range(INTIN[0], 0, MAX_COLOR - 1, 1); if (MAP_COL[line_qc] != line_color) { TOKEN = line_color = MAP_COL[line_qc]; PT_OP_BY(); } } /* end csl_color() */ /**************************************************/ VOID rsl_color() { GT_BYTE(); line_color = TOKEN; } /* end rsl_color() */ /**************************************************/ VOID csm_type() { if ( (TOKEN = range(INTIN[0] - 1, 0, MAX_MARK_INDEX - 1 , 2)) != mark_index) { mark_qc = (mark_index = TOKEN) + 1; PT_OP_BY(); } CONTRL[4] = 1; INTOUT[0] = mark_qc; } /* end csm_type() */ /**************************************************/ VOID rsm_type() { GT_BYTE(); mark_qc = (mark_index = TOKEN) + 1; } /* end rsm_type() */ /**************************************************/ VOID csm_height() { /* Limit the requested marker height to a reasonable value. */ if ( (TOKEN = PTSIN[1]) < DEF_MKHT) TOKEN = DEF_MKHT; else if (TOKEN > MAX_MKHT) TOKEN = MAX_MKHT; /* If this marker height is different than the last one, put it */ /* into the display list and update the globals. */ if (TOKEN != mark_height) { mark_scale = ((mark_height = TOKEN) + DEF_MKHT/2)/DEF_MKHT; PT_OP_WD(); } /* Set the marker height internals and the return parameters. */ CONTRL[2] = 1; PTSOUT[0] = mark_scale*DEF_MKWD; PTSOUT[1] = mark_scale*DEF_MKHT; FLIP_Y = 1; } /* end csm_height() */ /**************************************************/ VOID rsm_height() { GT_WORD(); mark_scale = ( (mark_height = TOKEN) + DEF_MKHT/2)/DEF_MKHT; } /* end rsm_height() */ /**************************************************/ VOID csm_color() { CONTRL[4] = 1; INTOUT[0] = mark_qc = TOKEN = range(INTIN[0], 0, MAX_COLOR - 1, 1); if (MAP_COL[mark_qc] != mark_color) { TOKEN = mark_color = MAP_COL[mark_qc]; PT_OP_BY(); } } /* end csm_color() */ /**************************************************/ VOID rsm_color() { GT_BYTE(); mark_color = TOKEN; } /* end rsm_color() */ /**************************************************/ VOID csf_interior() { CONTRL[4]=1; if ( (INTOUT[0] = TOKEN = range(INTIN[0], 0, MX_FIL_STYLE, 0)) != fill_style) { fill_style = TOKEN; PT_OP_BY(); } } /* end csf_interior() */ /**************************************************/ VOID rsf_interior() { GT_BYTE(); fill_style = TOKEN; st_fl_ptr(); } /* end rsf_interior() */ /**************************************************/ VOID csf_style() { CONTRL[4]=1; INTOUT[0] = fill_qi = (TOKEN = range(INTIN[0] - 1, 0, MX_FIL_INDEX - 1, 0)) + 1; if (TOKEN != fill_index) { fill_index = TOKEN; PT_OP_BY(); } } /* end csf_style() */ /**************************************************/ VOID rsf_style() { GT_BYTE(); fill_qi = (fill_index = TOKEN) + 1; st_fl_ptr(); } /* end rsf_style() */ /**************************************************/ VOID csf_color() { CONTRL[4]=1; INTOUT[0] = fill_qc = TOKEN = range(INTIN[0], 0, MAX_COLOR - 1, 1); if (MAP_COL[fill_qc] != fill_color) { TOKEN = fill_color = MAP_COL[fill_qc]; PT_OP_BY(); } } /* end csf_color() */ /**************************************************/ VOID rsf_color() { GT_BYTE(); fill_color = TOKEN; } /* end rsf_color() */ /**************************************************/ VOID cswr_mode() { CONTRL[4]=1; INTOUT[0] = write_qm = (TOKEN = range(INTIN[0] - 1, 0, MAX_WRITE_MODE, 0)) + 1; if (TOKEN != WRT_MODE) { WRT_MODE = TOKEN; PT_OP_BY(); } } /* end cswr_mode() */ /**************************************************/ VOID rswr_mode() { GT_BYTE(); WRT_MODE = TOKEN; } /* end rswr_mode() */ /**************************************************/ VOID csf_perimeter() { CONTRL[4]=1; if ((INTOUT[0] = TOKEN = (INTIN[0]) ? TRUE : FALSE) != fill_per) { fill_per = TOKEN; PT_OP_BY(); } } /* end csf_perimeter() */ /**************************************************/ VOID rsf_perimeter() { GT_BYTE(); fill_per = TOKEN; } /* end rsf_perimeter() */ /**************************************************/ VOID csf_udfl() { CONTRL[3] = 16; PT_OP_BY(); PT_INTIN(); } /* end csf_udfl() */ /**************************************************/ VOID rsf_udfl() { WORD i; CONTRL[3] = 16; GT_BYTE(); GT_INTIN(); for (i = 0; i < 16; i++) UD_PATRN[i] = INTIN[i]; } /* end rsf_udfl() */ /**************************************************/ VOID csl_udsty() { if ((TOKEN = INTIN[0]) != LINE_STYL[6]) { LINE_STYL[6] = TOKEN; PT_OP_WD(); } } /* end csl_udsty() */ /**************************************************/ VOID rsl_udsty() { GT_WORD(); LINE_STYL[6] = TOKEN; } /* end rsl_udsty() */ /**************************************************/ VOID c_clip() { TOKEN = clip = INTIN[0]; /* enable/disable clipping */ if (clip) { arb_corner(PTSIN, ULLR); if (PTSIN[0] < 0) PTSIN[0] = 0; if (PTSIN[2] > xres) PTSIN[2] = xres; if (PTSIN[1] < 0) PTSIN[1] = 0; if (PTSIN[3] > yres) PTSIN[3] = yres; } else { PTSIN[0] = PTSIN[1] = 0; PTSIN[2] = xres; PTSIN[3] = yres; } /* End else: clipping turned off. */ xmn_clip = PTSIN[0]; YCL_MIN = PTSIN[1]; xmx_clip = PTSIN[2]; YCL_MAX = PTSIN[3]; PT_OP_BY(); CONTRL[1] = 2; PT_PTSIN(); new_clip = TRUE; } /* end c_clip() */ /**************************************************/ VOID r_clip() { GT_BYTE(); clip = WINDOW | TOKEN; CONTRL[1] = 2; GT_PTSIN(); xmn_clip = (XW_MIN > PTSIN[0]) ? XW_MIN : PTSIN[0]; YCL_MIN = (YW_MIN > PTSIN[1]) ? YW_MIN : PTSIN[1]; ymn_clip = (YS_MIN > YCL_MIN) ? YS_MIN : YCL_MIN; xmx_clip = (XW_MAX < PTSIN[2]) ? XW_MAX : PTSIN[2]; YCL_MAX = (YW_MAX < PTSIN[3]) ? YW_MAX : PTSIN[3]; ymx_clip = (YS_MAX < YCL_MAX) ? YS_MAX : YCL_MAX; if (g_devdout) { fcl_xmin = dvt_fres(xmn_clip); fcl_ymin = dvt_fres(YCL_MIN); fcl_xmax = dvt_fres(xmx_clip); fcl_ymax = dvt_fres(YCL_MAX); } /* End if: device dependent output time. */ } /* end r_clip() */ /**************************************************/ VOID Get_Poly() { WORD i; GT_BYTE(); CONTRL[1] = TOKEN; i = ((CONTRL[1] = TOKEN) << 1) - 1; GT_PTSIN(); CONTRL[1]--; Y2 = PTSIN[i]; Y1 = PTSIN[i-1]; } /* end Get_Poly() */ /**************************************************/ VOID put_poly(extent_offset) WORD extent_offset; { WORD i, j, k; if (CONTRL[1] > 0) { Y1 = Y2 = PTSIN[1]; j = 1; for (i = 2; i <= CONTRL[1]; i++) { j += 2; k = PTSIN[j]; if (k > Y2) Y2 = k; else if (k < Y1) Y1 = k; } PTSIN[i = CONTRL[1] << 1] = Y1 - extent_offset; PTSIN[++i] = Y2 + extent_offset; CONTRL[1] = TOKEN = CONTRL[1] + 1; PT_OP_BY(); PT_PTSIN(); } } /* end put_poly() */ /************************************************ * Called ONCE ONLY, from v_opnwk() in monout.c * ************************************************/ VOID init_g() { Abort = FALSE; save_defaults(); open_sp(); clearmem(); init_p(); if (!Abort) { init_dev(); CURALPHA = 0xff; REQALPHA = 0; VMU = 0; } /* End if: successful. */ } /* end init_g() */ /**************************************************/ VOID save_defaults() { d_clip = clip; d_xmn_clip = xmn_clip; d_ycl_min = YCL_MIN; d_xmx_clip = xmx_clip; d_ycl_max = YCL_MAX; d_ln_index = line_index; d_qi_line = line_qi; d_ln_color = line_color; d_qc_line = line_qc; d_mk_index = mark_index; d_qi_mark = mark_qi; d_mk_color = mark_color; d_qc_mark = mark_qc; d_fa_style = fill_style; d_fa_index = fill_index; d_qi_fill = fill_qi; d_fa_color = fill_color; d_qc_fill = fill_qc; d_patmsk = patmsk; d_patptr = patptr; d_wrt_mode = WRT_MODE; d_mk_height = mark_height; d_mk_scale = mark_scale; d_ln_width = line_width; d_ln_beg = line_beg; d_ln_end = line_end; d_fill_per = fill_per; save_text_defaults(); } /* end save_defaults() */ /**************************************************/ VOID reset_defaults() { clip = d_clip; xmn_clip = d_xmn_clip; YCL_MIN = d_ycl_min; xmx_clip = d_xmx_clip; YCL_MAX = d_ycl_max; line_index = d_ln_index; line_qi = d_qi_line; line_color = d_ln_color; line_qc = d_qc_line; mark_index = d_mk_index; mark_qi = d_qi_mark; mark_color = d_mk_color; mark_qc = d_qc_mark; fill_style = d_fa_style; fill_index = d_fa_index; fill_qi = d_qi_fill; fill_color = d_fa_color; fill_qc = d_qc_fill; patmsk = d_patmsk; patptr = d_patptr; WRT_MODE = d_wrt_mode; mark_height = d_mk_height; mark_scale = d_mk_scale; line_width = d_ln_width; line_beg = d_ln_beg; line_end = d_ln_end; fill_per = d_fill_per; reset_text_defaults(); } /* end reset_defaults() */ /**************************************** * Called from v_clswk() in monout.c * * and from v_opnwk() if (abort) * ****************************************/ VOID dinit_g() { dini_dev(); dinit_p(); close_sp(); } /* end dinit_g() */ /**************************************************/ WORD range(value, low, high, def) WORD value, low, high, def; { if (value < low || value > high) return(def); else return(value); } /* end range() */
1
0.968626
1
0.968626
game-dev
MEDIA
0.417033
game-dev
0.82648
1
0.82648
googleforgames/global-multiplayer-demo
7,424
game/Source/Droidshooter/DroidshooterGameMode.cpp
// Copyright 2023 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "DroidshooterGameMode.h" #include "DroidshooterPlayerPawn.h" #include "DroidshooterGameStateBase.h" #include "DroidshooterPlayerState.h" #include "Droidshooter.h" #include "EngineUtils.h" #include "GameFramework/PlayerStart.h" #include "HttpModule.h" #include "Interfaces/IHttpRequest.h" #include "Interfaces/IHttpResponse.h" #include "AgonesComponent.h" #include "Classes.h" #include <random> ADroidshooterGameMode::ADroidshooterGameMode() { // Causes the editor to hang. Loading classname during runtime is much better, check respawn function. /*static ConstructorHelpers::FClassFinder<APawn> PlayerPawnBlueprint(TEXT("/Game/Player/DS_PlayerPawnBP.DS_PlayerPawnBP_C")); if (PlayerPawnBlueprint.Class != NULL) { DefaultPawnClass = PlayerPawnBlueprint.Class; }*/ AgonesSDK = CreateDefaultSubobject<UAgonesComponent>(TEXT("AgonesSDK")); ApiKey = FPlatformMisc::GetEnvironmentVariable(TEXT("API_ACCESS_KEY")); } void ADroidshooterGameMode::InitGame(const FString& MapName, const FString& Options, FString& ErrorMessage) { Super::InitGame(MapName, Options, ErrorMessage); UE_LOG(LogDroidshooter, Log, TEXT("Game is running: %s %s"), *MapName, *Options); if (GetWorld()->IsNetMode(NM_DedicatedServer)) { UE_LOG(LogDroidshooter, Log, TEXT("Server Started for map: %s"), *MapName); FNetworkVersion::IsNetworkCompatibleOverride.BindLambda([](uint32 LocalNetworkVersion, uint32 RemoteNetworkVersion) { return true; }); if (FParse::Value(FCommandLine::Get(), TEXT("stats_api"), StatsApi)) { UE_LOG(LogDroidshooter, Log, TEXT("Stats API set from command line param: %s"), *StatsApi); } else { UE_LOG(LogDroidshooter, Log, TEXT("Stats API was NOT provided! Check your command line params")); } } for (TActorIterator<APlayerStart> It(GetWorld()); It; ++It) { FreePlayerStarts.Add(*It); UE_LOG(LogDroidshooter, Log, TEXT("Found player start: %s"), *(*It)->GetName()); } } void ADroidshooterGameMode::PreLogin(const FString& Options, const FString& Address, const FUniqueNetIdRepl& UniqueId, FString& ErrorMessage) { if (FreePlayerStarts.Num() == 0) { ErrorMessage = TEXT("Server full"); } Super::PreLogin(Options, Address, UniqueId, ErrorMessage); } FString ADroidshooterGameMode::InitNewPlayer(APlayerController* NewPlayerController, const FUniqueNetIdRepl& UniqueId, const FString& Options, const FString& Portal) { if (FreePlayerStarts.Num() == 0) { UE_LOG(LogDroidshooter, Log, TEXT("No free player starts in InitNewPlayer")); return FString(TEXT("No free player starts")); } NewPlayerController->StartSpot = FreePlayerStarts.Pop(); UE_LOG(LogDroidshooter, Log, TEXT("Using player start %s for %s"), *NewPlayerController->StartSpot->GetName(), *NewPlayerController->GetName()); return Super::InitNewPlayer(NewPlayerController, UniqueId, Options, Portal); } void ADroidshooterGameMode::Logout(AController* Exiting) { UE_LOG(LogDroidshooter, Log, TEXT("Player is disconnecting!")); Super::Logout(Exiting); for (TActorIterator<APlayerStart> It(GetWorld()); It; ++It) { if (FreePlayerStarts.Contains(*It)) { UE_LOG(LogDroidshooter, Log, TEXT("Playerstart in Iterator: %s"), *(*It)->GetName()); } else { UE_LOG(LogDroidshooter, Log, TEXT("Playerstart NOT in Iterator: %s. Adding again."), *(*It)->GetName()); FreePlayerStarts.Add(*It); } } } void ADroidshooterGameMode::Respawn(AController* Controller) { UE_LOG(LogDroidshooter, Log, TEXT("Respawning!")); if (Controller) { if (GetLocalRole() == ROLE_Authority) { std::random_device rd; // obtain a random number from hardware std::mt19937 gen(rd()); // seed the generator std::uniform_int_distribution<> distr(-10000, 10000); // define the range FString TheClassPath = "Class'/Game/Player/DS_PlayerPawnBP.DS_PlayerPawnBP_C'"; const TCHAR* TheClass = *TheClassPath; UClass* PlayerPawnBlueprintClass = LoadObject<UClass>(nullptr, TheClass); if (PlayerPawnBlueprintClass == NULL) return; FVector Location = FVector(distr(gen), distr(gen), 0); if (ADroidshooterPlayerPawn* Pawn = GetWorld()->SpawnActor<ADroidshooterPlayerPawn>(PlayerPawnBlueprintClass, Location, FRotator::ZeroRotator)) { Controller->Possess(Pawn); ADroidshooterPlayerState* PlayerState = Cast< ADroidshooterPlayerState>(Pawn->GetPlayerState()); // Reset health back to normal PlayerState->UpdateHealth(25.f); } } } } void ADroidshooterGameMode::PlayerHit() { if (ADroidshooterGameStateBase* GS = GetGameState<ADroidshooterGameStateBase>()) { UE_LOG(LogDroidshooter, Log, TEXT("Player was hit (in DroidshooterGameMode)")); GS->PlayerHit(); } } void ADroidshooterGameMode::DumpStats(FString token, const FString gameId, const int kills, const int deaths) { if (StatsApi.Len() == 0) { return; } UE_LOG(LogDroidshooter, Log, TEXT("--- Sending stats to %s with key %s (user's token: %s)"), *StatsApi, *ApiKey, *token); TSharedRef<FJsonObject> JsonRootObject = MakeShareable(new FJsonObject); TArray<TSharedPtr<FJsonValue>> JsonServerArray; JsonRootObject->Values.Add("GameId", MakeShareable(new FJsonValueString(gameId))); JsonRootObject->Values.Add("Token", MakeShareable(new FJsonValueString(token))); JsonRootObject->Values.Add("Kills", MakeShareable(new FJsonValueNumber(kills))); JsonRootObject->Values.Add("Deaths", MakeShareable(new FJsonValueNumber(deaths))); FString OutputString; TSharedRef< TJsonWriter<> > Writer = TJsonWriterFactory<>::Create(&OutputString); FJsonSerializer::Serialize(JsonRootObject, Writer); FString uriStats = StatsApi + TEXT("/stats"); FHttpModule& httpModule = FHttpModule::Get(); TSharedRef<IHttpRequest, ESPMode::ThreadSafe> pRequest = httpModule.CreateRequest(); pRequest->SetHeader("Authorization", "Basic " + ApiKey); pRequest->SetVerb(TEXT("POST")); pRequest->SetURL(uriStats); pRequest->SetHeader(TEXT("User-Agent"), "X-UnrealEngine-Agent"); pRequest->SetHeader("Content-Type", TEXT("application/json")); pRequest->SetHeader(TEXT("Accepts"), TEXT("application/json")); pRequest->SetContentAsString(OutputString); // Set the callback, which will execute when the HTTP call is complete pRequest->OnProcessRequestComplete().BindLambda( [&]( FHttpRequestPtr pRequest, FHttpResponsePtr pResponse, bool connectedSuccessfully) mutable { if (connectedSuccessfully) { /* Eventual check for error codes & retry */ UE_LOG(LogDroidshooter, Log, TEXT("Stats data sent for one player.")); } else { switch (pRequest->GetStatus()) { case EHttpRequestStatus::Failed_ConnectionError: UE_LOG(LogDroidshooter, Log, TEXT("Connection failed.")); default: UE_LOG(LogDroidshooter, Log, TEXT("Request failed.")); } } }); // Finally, submit the request for processing pRequest->ProcessRequest(); }
1
0.943495
1
0.943495
game-dev
MEDIA
0.869606
game-dev
0.962977
1
0.962977
libsdl-org/sdlwiki
1,366
SDL2/SDL_PumpEvents.md
# SDL_PumpEvents Pump the event loop, gathering events from the input devices. ## Header File Defined in [SDL_events.h](https://github.com/libsdl-org/SDL/blob/SDL2/include/SDL_events.h) ## Syntax ```c void SDL_PumpEvents(void); ``` ## Remarks This function updates the event queue and internal input device state. **WARNING**: This should only be run in the thread that initialized the video subsystem, and for extra safety, you should consider only doing those things on the main thread in any case. [SDL_PumpEvents](SDL_PumpEvents)() gathers all the pending input information from devices and places it in the event queue. Without calls to [SDL_PumpEvents](SDL_PumpEvents)() no events would ever be placed on the queue. Often the need for calls to [SDL_PumpEvents](SDL_PumpEvents)() is hidden from the user since [SDL_PollEvent](SDL_PollEvent)() and [SDL_WaitEvent](SDL_WaitEvent)() implicitly call [SDL_PumpEvents](SDL_PumpEvents)(). However, if you are not polling or waiting for events (e.g. you are filtering them), then you must call [SDL_PumpEvents](SDL_PumpEvents)() to force an event queue update. ## Version This function is available since SDL 2.0.0. ## See Also - [SDL_PollEvent](SDL_PollEvent) - [SDL_WaitEvent](SDL_WaitEvent) ---- [CategoryAPI](CategoryAPI), [CategoryAPIFunction](CategoryAPIFunction), [CategoryEvents](CategoryEvents)
1
0.698953
1
0.698953
game-dev
MEDIA
0.877409
game-dev
0.526949
1
0.526949
catapult-project/catapult
3,909
devil/devil/android/sdk/intent.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Manages intents and associated information. This is generally intended to be used with functions that calls Android's Am command. """ # Some common flag constants that can be used to construct intents. # Full list: http://developer.android.com/reference/android/content/Intent.html FLAG_ACTIVITY_CLEAR_TASK = 0x00008000 FLAG_ACTIVITY_CLEAR_TOP = 0x04000000 FLAG_ACTIVITY_NEW_TASK = 0x10000000 FLAG_ACTIVITY_REORDER_TO_FRONT = 0x00020000 FLAG_ACTIVITY_RESET_TASK_IF_NEEDED = 0x00200000 def _bitwise_or(flags): result = 0 for flag in flags: result |= flag return result class Intent(object): def __init__(self, action='android.intent.action.VIEW', activity=None, category=None, component=None, data=None, extras=None, flags=None, package=None): """Creates an Intent. Args: action: A string containing the action. activity: A string that, with |package|, can be used to specify the component. category: A string or list containing any categories. component: A string that specifies the component to send the intent to. data: A string containing a data URI. extras: A dict containing extra parameters to be passed along with the intent. flags: A sequence of flag constants to be passed with the intent. package: A string that, with activity, can be used to specify the component. """ self._action = action self._activity = activity if isinstance(category, list) or category is None: self._category = category else: self._category = [category] self._component = component self._data = data self._extras = extras self._flags = '0x%0.8x' % _bitwise_or(flags) if flags else None self._package = package if self._component and '/' in component: self._package, self._activity = component.split('/', 1) elif self._package and self._activity: self._component = '%s/%s' % (package, activity) @property def action(self): return self._action @property def activity(self): return self._activity @property def category(self): return self._category @property def component(self): return self._component @property def data(self): return self._data @property def extras(self): return self._extras @property def flags(self): return self._flags @property def package(self): return self._package @property def am_args(self): """Returns the intent as a list of arguments for the activity manager. For details refer to the specification at: - http://developer.android.com/tools/help/adb.html#IntentSpec """ args = [] if self.action: args.extend(['-a', self.action]) if self.data: args.extend(['-d', self.data]) if self.category: args.extend(arg for cat in self.category for arg in ('-c', cat)) if self.component: args.extend(['-n', self.component]) if self.flags: args.extend(['-f', self.flags]) if self.extras: for key, value in self.extras.items(): if value is None: args.extend(['--esn', key]) elif isinstance(value, str): args.extend(['--es', key, value]) elif isinstance(value, bool): args.extend(['--ez', key, str(value)]) elif isinstance(value, int): args.extend(['--ei', key, str(value)]) elif isinstance(value, float): args.extend(['--ef', key, str(value)]) else: raise NotImplementedError( 'Intent does not know how to pass %s extras' % type(value)) return args
1
0.652263
1
0.652263
game-dev
MEDIA
0.136066
game-dev
0.952655
1
0.952655
oot-pc-port/oot-pc-port
1,177
asm/non_matchings/overlays/actors/ovl_Fishing/func_80B75DA4.s
glabel func_80B75DA4 /* 0C404 80B75DA4 27BDFFE8 */ addiu $sp, $sp, 0xFFE8 ## $sp = FFFFFFE8 /* 0C408 80B75DA8 2401000B */ addiu $at, $zero, 0x000B ## $at = 0000000B /* 0C40C 80B75DAC AFBF0014 */ sw $ra, 0x0014($sp) /* 0C410 80B75DB0 AFA40018 */ sw $a0, 0x0018($sp) /* 0C414 80B75DB4 AFA60020 */ sw $a2, 0x0020($sp) /* 0C418 80B75DB8 14A10006 */ bne $a1, $at, .L80B75DD4 /* 0C41C 80B75DBC AFA70024 */ sw $a3, 0x0024($sp) /* 0C420 80B75DC0 8FA50028 */ lw $a1, 0x0028($sp) /* 0C424 80B75DC4 3C0480B8 */ lui $a0, %hi(D_80B7AFAC) ## $a0 = 80B80000 /* 0C428 80B75DC8 2484AFAC */ addiu $a0, $a0, %lo(D_80B7AFAC) ## $a0 = 80B7AFAC /* 0C42C 80B75DCC 0C0346BD */ jal func_800D1AF4 /* 0C430 80B75DD0 24A501C0 */ addiu $a1, $a1, 0x01C0 ## $a1 = 000001C0 .L80B75DD4: /* 0C434 80B75DD4 8FBF0014 */ lw $ra, 0x0014($sp) /* 0C438 80B75DD8 27BD0018 */ addiu $sp, $sp, 0x0018 ## $sp = 00000000 /* 0C43C 80B75DDC 03E00008 */ jr $ra /* 0C440 80B75DE0 00000000 */ nop
1
0.698185
1
0.698185
game-dev
MEDIA
0.936461
game-dev
0.727179
1
0.727179
flags/Reactor-3
6,323
docs/2013arrp.md
2013 ARRP TODO LIST Checks: [x] Ensure delete_on_finish (jobs.py) is allowing multiple people to complete the job. [x] Is `sight.look` working correctly after the update? [?] Would splitting up zone maps help performance? [?] Can we delete the `item` key from WORLD_INFO after we update ITEMS? Fixes: [x] Fix jobs menu [x] Refresh tile of deleted item [?] ALife get recoil even on idle [/] Non-random dialog choices [x] Judge dialog impact on `like` and `dislike` instead of gist name [ ] Unused function: `jobs.cancel_on` [x] LOS crash on menu exit [x] Item searching in `sight.look` [x] Speed-up `sight.scan_surroundings` [x] Skip chunk if the chunk before it is invisible [x] Trees need to spawn in the ground a bit [?] If we are not compatiable with someone, maybe we can override that with trust? [/] Some trees not generating higher than the ground [x] `is_target_of` is terribly inefficient [x] ALife wants cover during combat [x] Clear path of thrown life to prevent warping [?] Explosions through wall [x] Menu entry colors [x] Dialog topics need to lose their trust/danger score after a while [ ] `get_limb_stability` needs to factor in all injuries [ ] Thrown ALife do not properly enter/exit chunks [ ] ALife do nothing while in cover [ ] You can't wear an item if it is stored AND a storage item itself [ ] Item scoring should replace `combat.get_best_weapon`. Merge its contents. [/] Items need dereferencing inside ALife memory on delete Remembered items should still be able to reference deleted items in some way This kind of behavior lends itself to the sort of behavior we're desiring, i.e., a feeling of uncertainty, that the player and ALife can be led to non- existent items/etc. [/] Telling other ALife about items/chunks can lead to interesting behaviors e.g.: "I heard about <x> from <y>, maybe I should check it out." e.g.: An item is wanted, but not right away [ ] `5` is hardcoded as the lowest preferred ammo count for usable weapons [ ] Keep chunk_map from mapgen? [ ] Integrate color lerping into menu item creation [ ] Current dijkstra map crash could be due to the distances between points being too far. Maybe use A* until we're at a suitable distance? [ ] Show what non-tiles are in look mode (using the mouse or free look only) Grass, trees, etc [ ] How many times do we need to calculate `is_safe`? [ ] Item speed not lowered along with velocity in `collision_with_solid` [?] Change `alife_search` to check for non-combat targets too Would replace searching behavior in `alife_follow` [ ] Items can have negative speeds Cycles: [ ] ALife searching for group leader when not found at `last_pos` &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& & Gather group, loot this location, return to base & &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& WEAPON DISTANCES IN ALL LOGIC FUNCTIONS Dead Cycles [ ] Engage -> Spend ammo -> idle Future: [x] Re-announce group whenever (alife_group.py) [ ] Group relationships [/] Bushes/foliage [/] Tell about ALife's last position when asked [ ] Call out lie when misinforming people on group motive [ ] Blowback from weapons [/] Map gen: [ ] Dead-end roads [/] Driveways/side roads [ ] Flowers [ ] Road signs [ ] Double-wide roads for towns [x] `examine_keys`: List of keys to show in examine view [ ] Put items in storage [ ] Visual character descriptions in look mode [ ] Show what their state is ("running" etc) [ ] Different color icons for different groups [ ] ALife should also change the background of the tile they're standing on to a color representing their stance towards them [ ] Auto-pause [ ] Player can call for help [ ] "Situations" i.e., context-sensitive hints that pop up during combat like quicktime events ("call for help", "surrender", etc) [ ] "Battle view"? [ ] Improve relationship by attacking targets [ ] *Friendly added* [ ] Item name mods (torn, dented, etc) [ ] The "smartness" of an ALife could be determined by how quickly they react to situations (change states) [ ] Black Holes It's very early in the morning, a perfect time for raids, as the enemy is usually taking shelter from the rabid wildlife that come out at night. My squademate hangs back, slightly outside of town. If I can't do the raid myself, he'll be there for backup. I take a shot at the first person I see, destroying the target's <limb> Dialog [ ] What is our relationship like with <group>? [ ] Phrases could use a little more detail to represent the urgency/tension of the situation Caching Layers: [x] Zones [x] Dijkstra maps [ ] Memories Groups: [ ] Chunk ownership -> reference ownership [ ] Area of influence Refactor: [ ] `maps.get_chunk` -> `chunks.get_chunk` [ ] `maps.enter/leave_chunk` -> `chunks.enter/leave_chunk` ** PARTICLE EFFECTS ** In progress [x] Sticky combat pause [x] ALife pause to take cover & reload [ ] Potential to have the ALife get close to the player and melee [/] Particle effect for shooting [ ] ALife escaping surrender via safety maps [x] Incapacitate by non-leg wounds [/] Depending on distance, being incapacitated could cause the ALife to try and escape otherwise [x] Knocking out [ ] Searching after grenade explosions [ ] Run from grenades [x] Chunk map: track items ** To get ALife to escape from surrender, generate dijkstra map with all friendly ALife as goals. Take the score and compare it to the ALife's courage skill. We can translate their skill in courage to this score to find out whether to run away or not. ** If ALife begins dialog while entering or in the surrender state, change dialog based on intimidation Given the situation: Player tosses grenade into room Enemies are unaware They are injured by the explosion How do they react? Who do they blame? They don't know who threw the grenade, but we need to communicate action How do ALife track item ownership? Stranded functions: speech.determine_interesting_event Deprecate: Snapshots of ALife Make sure we add ourselves to the group list HOWEVER, drawing alignments should use the player's list, not the NPC's Group motives are NOT shared yet! issues in member list propagation can occur because there is no way to track when someone leaves a group Group joining permissions
1
0.99057
1
0.99057
game-dev
MEDIA
0.989035
game-dev
0.951087
1
0.951087
InsightSoftwareConsortium/ITK
1,510
Modules/ThirdParty/GDCM/src/gdcm/Source/DataStructureAndEncodingDefinition/gdcmDataSetEvent.h
/*========================================================================= Program: GDCM (Grassroots DICOM). A DICOM library Copyright (c) 2006-2011 Mathieu Malaterre All rights reserved. See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #ifndef GDCMDATASETEVENT_H #define GDCMDATASETEVENT_H #include "gdcmEvent.h" #include "gdcmDataSet.h" namespace gdcm { /** * \brief DataSetEvent * \details Special type of event triggered during the DataSet store/move process */ class DataSetEvent : public AnyEvent { public: typedef DataSetEvent Self; typedef AnyEvent Superclass; DataSetEvent(DataSet const *ds = nullptr):m_DataSet(ds) {} ~DataSetEvent() override = default; void operator=(const Self&) = delete; const DataSet *m_DataSet; const char * GetEventName() const override { return "DataSetEvent"; } bool CheckEvent(const ::gdcm::Event* e) const override { return (dynamic_cast<const Self*>(e) == nullptr ? false : true) ; } ::gdcm::Event* MakeObject() const override { return new Self; } DataSetEvent(const Self&s) : AnyEvent(s){} DataSet const & GetDataSet() const { return *m_DataSet; } }; } // end namespace gdcm #endif //GDCMANONYMIZEEVENT_H
1
0.868072
1
0.868072
game-dev
MEDIA
0.61667
game-dev
0.764443
1
0.764443
ms-iot/ros_msft_mrtk
9,436
SampleProject/Assets/MixedRealityToolkit.Services/InputSystem/NearInteractionTouchable.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Linq; using UnityEngine; using UnityEngine.Serialization; namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// Add a NearInteractionTouchable to your scene and configure a touchable surface /// in order to get PointerDown and PointerUp events whenever a PokePointer touches this surface. /// </summary> [AddComponentMenu("Scripts/MRTK/Services/NearInteractionTouchable")] public class NearInteractionTouchable : NearInteractionTouchableSurface { [SerializeField] protected Vector3 localForward = Vector3.forward; /// <summary> /// Local space forward direction /// </summary> public Vector3 LocalForward { get => localForward; } [SerializeField] protected Vector3 localUp = Vector3.up; /// <summary> /// Local space up direction /// </summary> public Vector3 LocalUp { get => localUp; } /// <summary> /// Returns true if the LocalForward and LocalUp vectors are orthogonal. /// </summary> /// <remarks> /// LocalRight is computed using the cross product and is always orthogonal to LocalForward and LocalUp. /// </remarks> public bool AreLocalVectorsOrthogonal => Vector3.Dot(localForward, localUp) == 0; [SerializeField] protected Vector3 localCenter = Vector3.zero; /// <summary> /// Local space object center /// </summary> public override Vector3 LocalCenter { get => localCenter; } /// <summary> /// Local space and gameObject right /// </summary> public Vector3 LocalRight { get { Vector3 cross = Vector3.Cross(localUp, localForward); if (cross == Vector3.zero) { // vectors are collinear return default right return Vector3.right; } else { return cross; } } } /// <summary> /// Forward direction of the gameObject /// </summary> public Vector3 Forward => transform.TransformDirection(localForward); /// <summary> /// Forward direction of the NearInteractionTouchable plane, the press direction needs to face the /// camera. /// </summary> public override Vector3 LocalPressDirection => -localForward; [SerializeField] protected Vector2 bounds = Vector2.zero; /// <summary> /// Bounds or size of the 2D NearInteractionTouchablePlane /// </summary> public override Vector2 Bounds { get => bounds; } /// <summary> /// Check if the touchableCollider is enabled and in the gameObject hierarchy /// </summary> public bool ColliderEnabled { get { return touchableCollider.enabled && touchableCollider.gameObject.activeInHierarchy; } } [SerializeField] [FormerlySerializedAs("collider")] [Tooltip("BoxCollider used to calculate bounds and local center, if not set before runtime the gameObjects's BoxCollider will be used by default")] private Collider touchableCollider; /// <summary> /// BoxCollider used to calculate bounds and local center, if not set before runtime the gameObjects's BoxCollider will be used by default /// </summary> public Collider TouchableCollider => touchableCollider; protected override void OnValidate() { if (Application.isPlaying) { // Don't validate during play mode return; } base.OnValidate(); touchableCollider = GetComponent<Collider>(); Debug.Assert(localForward.magnitude > 0); Debug.Assert(localUp.magnitude > 0); string hierarchy = gameObject.transform.EnumerateAncestors(true).Aggregate("", (result, next) => next.gameObject.name + "=>" + result); if (localUp.sqrMagnitude == 1 && localForward.sqrMagnitude == 1) { Debug.Assert(Vector3.Dot(localForward, localUp) == 0, $"localForward and localUp not perpendicular for object {hierarchy}. Did you set Local Forward correctly?"); } localForward = localForward.normalized; localUp = localUp.normalized; bounds.x = Mathf.Max(bounds.x, 0); bounds.y = Mathf.Max(bounds.y, 0); } void OnEnable() { if (touchableCollider == null) { SetTouchableCollider(GetComponent<BoxCollider>()); } } /// <summary> /// Set local forward direction and ensure that local up is perpendicular to the new local forward and /// local right direction. The forward position should be facing the camera. The direction is indicated in scene view by a /// white arrow in the center of the plane. /// </summary> public void SetLocalForward(Vector3 newLocalForward) { localForward = newLocalForward; localUp = Vector3.Cross(localForward, LocalRight).normalized; } /// <summary> /// Set new local up direction and ensure that local forward is perpendicular to the new local up and /// local right direction. /// </summary> public void SetLocalUp(Vector3 newLocalUp) { localUp = newLocalUp; localForward = Vector3.Cross(LocalRight, localUp).normalized; } /// <summary> /// Set the position (center) of the NearInteractionTouchable plane relative to the gameObject. /// The position of the plane should be in front of the gameObject. /// </summary> public void SetLocalCenter(Vector3 newLocalCenter) { localCenter = newLocalCenter; } /// <summary> /// Set the size (bounds) of the 2D NearInteractionTouchable plane. /// </summary> public void SetBounds(Vector2 newBounds) { bounds = newBounds; } /// <summary> /// Adjust the bounds, local center and local forward to match a given box collider. This method /// also changes the size of the box collider attached to the gameObject. /// Default Behavior: if touchableCollider is null at runtime, the object's box collider will be used /// to size and place the NearInteractionTouchable plane in front of the gameObject /// </summary> public void SetTouchableCollider(BoxCollider newCollider) { if (newCollider != null) { // Set touchableCollider for possible reference in the future touchableCollider = newCollider; SetLocalForward(-Vector3.forward); Vector2 adjustedSize = new Vector2( Math.Abs(Vector3.Dot(newCollider.size, LocalRight)), Math.Abs(Vector3.Dot(newCollider.size, LocalUp))); SetBounds(adjustedSize); // Set x and y center to match the newCollider but change the position of the // z axis so the plane is always in front of the object SetLocalCenter(newCollider.center + Vector3.Scale(newCollider.size / 2.0f, LocalForward)); // Set size and center of the gameObject's box collider to match the collider given, if there // is no box collider behind the NearInteractionTouchable plane, an event will not be raised BoxCollider attachedBoxCollider = GetComponent<BoxCollider>(); attachedBoxCollider.size = newCollider.size; attachedBoxCollider.center = newCollider.center; } else { Debug.LogWarning("BoxCollider is null, cannot set bounds of NearInteractionTouchable plane"); } } /// <inheritdoc /> public override float DistanceToTouchable(Vector3 samplePoint, out Vector3 normal) { normal = Forward; Vector3 localPoint = transform.InverseTransformPoint(samplePoint) - localCenter; // Get surface coordinates Vector3 planeSpacePoint = new Vector3( Vector3.Dot(localPoint, LocalRight), Vector3.Dot(localPoint, localUp), Vector3.Dot(localPoint, localForward)); // touchables currently can only be touched within the bounds of the rectangle. // We return infinity to ensure that any point outside the bounds does not get touched. if (planeSpacePoint.x < -bounds.x / 2 || planeSpacePoint.x > bounds.x / 2 || planeSpacePoint.y < -bounds.y / 2 || planeSpacePoint.y > bounds.y / 2) { return float.PositiveInfinity; } // Scale back to 3D space planeSpacePoint = transform.TransformSize(planeSpacePoint); return Math.Abs(planeSpacePoint.z); } } }
1
0.968559
1
0.968559
game-dev
MEDIA
0.787269
game-dev
0.963931
1
0.963931
chapel-lang/chapel
5,279
third-party/llvm/llvm-src/include/llvm/CodeGen/CommandFlags.h
//===-- CommandFlags.h - Command Line Flags Interface -----------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains codegen-specific flags that are shared between different // command line tools. The tools "llc" and "opt" both use this file to prevent // flag duplication. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_COMMANDFLAGS_H #define LLVM_CODEGEN_COMMANDFLAGS_H #include "llvm/ADT/FloatingPointMode.h" #include "llvm/Support/CodeGen.h" #include "llvm/Target/TargetOptions.h" #include <optional> #include <string> #include <vector> namespace llvm { class Module; class AttrBuilder; class Function; class Triple; class TargetMachine; namespace codegen { std::string getMArch(); std::string getMCPU(); std::vector<std::string> getMAttrs(); Reloc::Model getRelocModel(); std::optional<Reloc::Model> getExplicitRelocModel(); ThreadModel::Model getThreadModel(); CodeModel::Model getCodeModel(); std::optional<CodeModel::Model> getExplicitCodeModel(); uint64_t getLargeDataThreshold(); std::optional<uint64_t> getExplicitLargeDataThreshold(); llvm::ExceptionHandling getExceptionModel(); std::optional<CodeGenFileType> getExplicitFileType(); CodeGenFileType getFileType(); FramePointerKind getFramePointerUsage(); bool getEnableUnsafeFPMath(); bool getEnableNoInfsFPMath(); bool getEnableNoNaNsFPMath(); bool getEnableNoSignedZerosFPMath(); bool getEnableApproxFuncFPMath(); bool getEnableNoTrappingFPMath(); DenormalMode::DenormalModeKind getDenormalFPMath(); DenormalMode::DenormalModeKind getDenormalFP32Math(); bool getEnableHonorSignDependentRoundingFPMath(); llvm::FloatABI::ABIType getFloatABIForCalls(); llvm::FPOpFusion::FPOpFusionMode getFuseFPOps(); SwiftAsyncFramePointerMode getSwiftAsyncFramePointer(); bool getDontPlaceZerosInBSS(); bool getEnableGuaranteedTailCallOpt(); bool getEnableAIXExtendedAltivecABI(); bool getDisableTailCalls(); bool getStackSymbolOrdering(); bool getStackRealign(); std::string getTrapFuncName(); bool getUseCtors(); bool getDisableIntegratedAS(); bool getDataSections(); std::optional<bool> getExplicitDataSections(); bool getFunctionSections(); std::optional<bool> getExplicitFunctionSections(); bool getIgnoreXCOFFVisibility(); bool getXCOFFTracebackTable(); std::string getBBSections(); unsigned getTLSSize(); bool getEmulatedTLS(); std::optional<bool> getExplicitEmulatedTLS(); bool getEnableTLSDESC(); std::optional<bool> getExplicitEnableTLSDESC(); bool getUniqueSectionNames(); bool getUniqueBasicBlockSectionNames(); bool getSeparateNamedSections(); llvm::EABI getEABIVersion(); llvm::DebuggerKind getDebuggerTuningOpt(); bool getEnableStackSizeSection(); bool getEnableAddrsig(); bool getEmitCallSiteInfo(); bool getEnableMachineFunctionSplitter(); bool getEnableDebugEntryValues(); bool getValueTrackingVariableLocations(); std::optional<bool> getExplicitValueTrackingVariableLocations(); bool getForceDwarfFrameSection(); bool getXRayFunctionIndex(); bool getDebugStrictDwarf(); unsigned getAlignLoops(); bool getJMCInstrument(); bool getXCOFFReadOnlyPointers(); /// Create this object with static storage to register codegen-related command /// line options. struct RegisterCodeGenFlags { RegisterCodeGenFlags(); }; bool getEnableBBAddrMap(); llvm::BasicBlockSection getBBSectionsMode(llvm::TargetOptions &Options); /// Common utility function tightly tied to the options listed here. Initializes /// a TargetOptions object with CodeGen flags and returns it. /// \p TheTriple is used to determine the default value for options if /// options are not explicitly specified. If those triple dependant options /// value do not have effect for your component, a default Triple() could be /// passed in. TargetOptions InitTargetOptionsFromCodeGenFlags(const llvm::Triple &TheTriple); std::string getCPUStr(); std::string getFeaturesStr(); std::vector<std::string> getFeatureList(); void renderBoolStringAttr(AttrBuilder &B, StringRef Name, bool Val); /// Set function attributes of function \p F based on CPU, Features, and command /// line flags. void setFunctionAttributes(StringRef CPU, StringRef Features, Function &F); /// Set function attributes of functions in Module M based on CPU, /// Features, and command line flags. void setFunctionAttributes(StringRef CPU, StringRef Features, Module &M); /// Should value-tracking variable locations / instruction referencing be /// enabled by default for this triple? bool getDefaultValueTrackingVariableLocations(const llvm::Triple &T); /// Creates a TargetMachine instance with the options defined on the command /// line. This can be used for tools that do not need further customization of /// the TargetOptions. Expected<std::unique_ptr<TargetMachine>> createTargetMachineForTriple( StringRef TargetTriple, CodeGenOptLevel OptLevel = CodeGenOptLevel::Default); } // namespace codegen } // namespace llvm #endif // LLVM_CODEGEN_COMMANDFLAGS_H
1
0.944056
1
0.944056
game-dev
MEDIA
0.306796
game-dev
0.742677
1
0.742677
RyseInventory/RyseInventory
16,962
plugin/src/main/java/io/github/rysefoxx/inventory/plugin/animator/IntelligentMaterialAnimator.java
/* * MIT License * * Copyright (c) 2022. Rysefoxx * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package io.github.rysefoxx.inventory.plugin.animator; import com.google.common.base.Preconditions; import io.github.rysefoxx.inventory.plugin.content.IntelligentItem; import io.github.rysefoxx.inventory.plugin.content.InventoryContents; import io.github.rysefoxx.inventory.plugin.enums.TimeSetting; import io.github.rysefoxx.inventory.plugin.pagination.RyseInventory; import io.github.rysefoxx.inventory.plugin.util.StringConstants; import io.github.rysefoxx.inventory.plugin.util.TimeUtils; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitTask; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.annotation.Nonnegative; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * @author Rysefoxx(Rysefoxx # 6772) | * @since 4/12/2022 */ public class IntelligentMaterialAnimator { private static Plugin plugin; private List<String> frames = new ArrayList<>(); private HashMap<Character, Material> frameMaterial = new HashMap<>(); private int period = 20; private int delay = 0; private int slot = -1; private BukkitTask task; private boolean loop; private RyseInventory inventory; private IntelligentItem intelligentItem; private Object identifier; private InventoryContents contents; @Contract("_ -> new") public static @NotNull Builder builder(@NotNull Plugin plugin) { IntelligentMaterialAnimator.plugin = plugin; return new Builder(); } /** * This starts the animation for the item. */ public void animate() { this.inventory.addMaterialAnimator(this); animateItem(); } /** * This stops the animation for the item. * * @return true if the animation was stopped. */ public boolean stop() { if (this.task == null || !Bukkit.getScheduler().isQueued(this.task.getTaskId())) return false; this.task.cancel(); return true; } /** * It loops through the frames, and updates the material of the item in the inventory */ private void animateItem() { int finalLength = getFrameLength(); this.task = Bukkit.getScheduler().runTaskTimer(plugin, new Runnable() { final List<String> framesCopy = frames; final ItemStack itemStack = new ItemStack(intelligentItem.getItemStack()); int materialState = 0; int subStringIndex = 0; int currentFrameIndex = 0; Material currentMaterial; @Override public void run() { char[] currentFrames = framesCopy.get(this.currentFrameIndex).toCharArray(); resetWhenFrameFinished(currentFrames); if (cancelIfListIsEmpty()) return; currentFrames = updateFramesWhenRequired(currentFrames); char singleFrame = currentFrames[this.materialState]; this.currentMaterial = frameMaterial.get(singleFrame); this.materialState++; this.subStringIndex++; this.itemStack.setType(this.currentMaterial); contents.update(slot, this.itemStack); } private char @NotNull [] updateFramesWhenRequired(char @NotNull [] currentFrames) { if (this.materialState < currentFrames.length) return currentFrames; this.materialState = 0; if (this.framesCopy.size() > 1 && (this.currentFrameIndex + 1 != this.framesCopy.size())) { this.currentFrameIndex++; currentFrames = this.framesCopy.get(this.currentFrameIndex).toCharArray(); } return currentFrames; } private boolean cancelIfListIsEmpty() { if (this.framesCopy.isEmpty()) { inventory.removeMaterialAnimator(IntelligentMaterialAnimator.this); return true; } return false; } private void resetWhenFrameFinished(char[] currentFrames) { if (this.subStringIndex < finalLength) return; if (!loop) this.framesCopy.remove(0); this.materialState = 0; this.subStringIndex = 0; if (!this.framesCopy.isEmpty()) this.currentMaterial = frameMaterial.get(currentFrames[this.materialState]); if (this.currentFrameIndex + 1 >= this.framesCopy.size()) this.currentFrameIndex = 0; } }, this.delay, this.period); } /** * This function returns the task that is currently running. * * @return The task that is being run. */ @ApiStatus.Internal public @NotNull BukkitTask getTask() { return this.task; } /** * Returns the identifier of this object, or null if it has none. * * @return The identifier of the object. */ public @Nullable Object getIdentifier() { return this.identifier; } /** * This function returns the length of the frames array. * * @return The length of the frames array. */ @Contract(pure = true) private int getFrameLength() { int length = 0; for (String frame : frames) { length += frame.length(); } return length; } public static class Builder { private IntelligentMaterialAnimator preset; private IntelligentItem intelligentItem; private List<String> frames = new ArrayList<>(); private HashMap<Character, Material> frameMaterial = new HashMap<>(); private int period = 20; private int delay = 0; private int slot = -1; private boolean loop; private Object identifier; /** * This tells which item is to be animated. * * @param intelligentItem The item that is to be animated. * @return The Builder to perform further editing. */ public @NotNull Builder item(@NotNull IntelligentItem intelligentItem) { this.intelligentItem = intelligentItem; return this; } /** * Takes over all properties of the passed animator. * * @param preset The animator to be copied. * @return The Builder to perform further editing. * <p> * When copying the animator, the identification is not copied if present! */ public @NotNull Builder copy(@NotNull IntelligentMaterialAnimator preset) { this.preset = preset; return this; } /** * Keeps the animation running until the player closes the inventory. * * @return The Builder to perform further editing. */ public @NotNull Builder loop() { this.loop = true; return this; } /** * This tells us in which slot the animation should take place. * * @param slot The slot in which the animation should take place. * @return The Builder to perform further editing. * @throws IllegalArgumentException if slot is greater than 53 */ public @NotNull Builder slot(@Nonnegative int slot) throws IllegalArgumentException { if (slot > 53) throw new IllegalArgumentException(StringConstants.INVALID_SLOT); this.slot = slot; return this; } /** * Assigns a material to a frame. * * @param frame The frame that should receive the material. * @param material The material you want the frame to have. * @return The Builder to perform further editing. */ public @NotNull Builder material(char frame, @NotNull Material material) { this.frameMaterial.put(frame, material); return this; } /** * Several frames are assigned individual materials. * * @param frames The frames that should receive the material. * @param materials The materials you want the frame to have. * @return The Builder to perform further editing. * @throws IllegalArgumentException If the parameters are not equal. */ public @NotNull Builder materials(@NotNull List<Character> frames, Material @NotNull ... materials) throws IllegalArgumentException { Preconditions.checkArgument(frames.size() == materials.length, StringConstants.INVALID_MATERIAL_FRAME); for (int i = 0; i < frames.size(); i++) material(frames.get(i), materials[i]); return this; } /** * Several frames are assigned individual materials. * * @param frames The frames that should receive the material. * @param materials The materials you want the frame to have. * @return The Builder to perform further editing. * @throws IllegalArgumentException If the parameters are not equal. */ public @NotNull Builder materials(Character @NotNull [] frames, Material @NotNull ... materials) { Preconditions.checkArgument(frames.length == materials.length, StringConstants.INVALID_MATERIAL_FRAME); for (int i = 0; i < frames.length; i++) material(frames[i], materials[i]); return this; } /** * Several frames are assigned individual materials. * * @param frames The frames that should receive the material. * @param materials The materials you want the frame to have. * @return The Builder to perform further editing. * @throws IllegalArgumentException If the parameters are not equal. */ public @NotNull Builder materials(Character @NotNull [] frames, @NotNull List<Material> materials) { Preconditions.checkArgument(frames.length == materials.size(), StringConstants.INVALID_MATERIAL_FRAME); for (int i = 0; i < frames.length; i++) material(frames[i], materials.get(i)); return this; } /** * Adds another frame. * * @param frame The frame that should be added. * @return The Builder to perform further editing. * @throws IllegalArgumentException If no material has been assigned to the frame yet. e.g {@link Builder#material(char, Material)} */ public @NotNull Builder frame(@NotNull String frame) throws IllegalArgumentException { this.frames.add(frame); return this; } /** * Adds several frames. * * @param frames The frames that should be added. * @return The Builder to perform further editing. * @throws IllegalArgumentException If no material has been assigned to the frame yet. e.g {@link Builder#material(char, Material)} */ public @NotNull Builder frames(String @NotNull ... frames) { for (String frame : frames) frame(frame); return this; } /** * Adds several frames. * * @param frames The frames that should be added. * @return The Builder to perform further editing. * @throws IllegalArgumentException If no material has been assigned to the frame yet. e.g {@link Builder#material(char, Material)} */ public @NotNull Builder frames(@NotNull List<String> frames) { frames.forEach(this::frame); return this; } /** * Sets the speed of the animation in the scheduler. * * @param time The time. * @param setting The time setting. * @return The Builder to perform further editing. */ public @NotNull Builder period(@Nonnegative int time, @NotNull TimeSetting setting) { this.period = TimeUtils.buildTime(time, setting); return this; } /** * Specifies the delay before the animation starts. * * @param time The delay. * @param setting The time setting. * @return The Builder to perform further editing. */ public @NotNull Builder delay(@Nonnegative int time, @NotNull TimeSetting setting) { this.delay = TimeUtils.buildTime(time, setting); return this; } /** * Gives the Animation an identification * * @param identifier The ID through which you can get the animation * @return The Builder to perform further editing * <p> * When copying the animator, the identification is not copied if present! */ public @NotNull Builder identifier(@NotNull Object identifier) { this.identifier = identifier; return this; } /** * This creates the animation class but does not start it yet! {@link IntelligentMaterialAnimator#animate()} * * @param contents The contents of the inventory. * @return The animation class * @throws IllegalArgumentException if no slot was specified, if frameMaterial is empty, if frames is empty or if no material has been assigned to a frame. * @throws NullPointerException if item is null. */ public IntelligentMaterialAnimator build(@NotNull InventoryContents contents) throws IllegalArgumentException, NullPointerException { if (this.preset != null) { this.intelligentItem = this.preset.intelligentItem; this.frames = this.preset.frames; this.frameMaterial = this.preset.frameMaterial; this.period = this.preset.period; this.delay = this.preset.delay; this.slot = this.preset.slot; this.loop = this.preset.loop; } if (this.slot == -1) throw new IllegalArgumentException("Please specify a slot where the item is located."); if (this.frameMaterial.isEmpty()) throw new IllegalArgumentException("Please specify a material for each frame."); if (this.intelligentItem == null) throw new NullPointerException("Please specify an item to animate."); if (this.frames.isEmpty()) throw new IllegalArgumentException("No frames have been defined yet!"); for (String frame : this.frames) { for (char c : frame.toCharArray()) { if (frameMaterial.containsKey(c)) continue; throw new IllegalArgumentException("You created the frame " + frame + ", but the letter " + c + " was not assigned a material."); } } IntelligentMaterialAnimator animator = new IntelligentMaterialAnimator(); animator.intelligentItem = this.intelligentItem; animator.delay = this.delay; animator.frameMaterial = this.frameMaterial; animator.frames = this.frames; animator.loop = this.loop; animator.period = this.period; animator.slot = this.slot; animator.identifier = this.identifier; animator.contents = contents; animator.inventory = contents.pagination().inventory(); return animator; } } }
1
0.752456
1
0.752456
game-dev
MEDIA
0.497739
game-dev
0.765479
1
0.765479
solana-developers/program-examples
41,915
tokens/token-2022/nft-meta-data-pointer/anchor-example/unity/ExtensionNft/Assets/DOTween 4/Modules/DOTweenModuleUI.cs
// Author: Daniele Giardini - http://www.demigiant.com // Created: 2018/07/13 #if true // MODULE_MARKER using System; using System.Globalization; using UnityEngine; using UnityEngine.UI; using DG.Tweening.Core; using DG.Tweening.Core.Enums; using DG.Tweening.Plugins; using DG.Tweening.Plugins.Options; using Outline = UnityEngine.UI.Outline; using Text = UnityEngine.UI.Text; #pragma warning disable 1591 namespace DG.Tweening { public static class DOTweenModuleUI { #region Shortcuts #region CanvasGroup /// <summary>Tweens a CanvasGroup's alpha color to the given value. /// Also stores the canvasGroup as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<float, float, FloatOptions> DOFade(this CanvasGroup target, float endValue, float duration) { TweenerCore<float, float, FloatOptions> t = DOTween.To(() => target.alpha, x => target.alpha = x, endValue, duration); t.SetTarget(target); return t; } #endregion #region Graphic /// <summary>Tweens an Graphic's color to the given value. /// Also stores the image as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Color, Color, ColorOptions> DOColor(this Graphic target, Color endValue, float duration) { TweenerCore<Color, Color, ColorOptions> t = DOTween.To(() => target.color, x => target.color = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens an Graphic's alpha color to the given value. /// Also stores the image as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Color, Color, ColorOptions> DOFade(this Graphic target, float endValue, float duration) { TweenerCore<Color, Color, ColorOptions> t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration); t.SetTarget(target); return t; } #endregion #region Image /// <summary>Tweens an Image's color to the given value. /// Also stores the image as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Color, Color, ColorOptions> DOColor(this Image target, Color endValue, float duration) { TweenerCore<Color, Color, ColorOptions> t = DOTween.To(() => target.color, x => target.color = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens an Image's alpha color to the given value. /// Also stores the image as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Color, Color, ColorOptions> DOFade(this Image target, float endValue, float duration) { TweenerCore<Color, Color, ColorOptions> t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens an Image's fillAmount to the given value. /// Also stores the image as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach (0 to 1)</param><param name="duration">The duration of the tween</param> public static TweenerCore<float, float, FloatOptions> DOFillAmount(this Image target, float endValue, float duration) { if (endValue > 1) endValue = 1; else if (endValue < 0) endValue = 0; TweenerCore<float, float, FloatOptions> t = DOTween.To(() => target.fillAmount, x => target.fillAmount = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens an Image's colors using the given gradient /// (NOTE 1: only uses the colors of the gradient, not the alphas - NOTE 2: creates a Sequence, not a Tweener). /// Also stores the image as the tween's target so it can be used for filtered operations</summary> /// <param name="gradient">The gradient to use</param><param name="duration">The duration of the tween</param> public static Sequence DOGradientColor(this Image target, Gradient gradient, float duration) { Sequence s = DOTween.Sequence(); GradientColorKey[] colors = gradient.colorKeys; int len = colors.Length; for (int i = 0; i < len; ++i) { GradientColorKey c = colors[i]; if (i == 0 && c.time <= 0) { target.color = c.color; continue; } float colorDuration = i == len - 1 ? duration - s.Duration(false) // Verifies that total duration is correct : duration * (i == 0 ? c.time : c.time - colors[i - 1].time); s.Append(target.DOColor(c.color, colorDuration).SetEase(Ease.Linear)); } s.SetTarget(target); return s; } #endregion #region LayoutElement /// <summary>Tweens an LayoutElement's flexibleWidth/Height to the given value. /// Also stores the LayoutElement as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOFlexibleSize(this LayoutElement target, Vector2 endValue, float duration, bool snapping = false) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => new Vector2(target.flexibleWidth, target.flexibleHeight), x => { target.flexibleWidth = x.x; target.flexibleHeight = x.y; }, endValue, duration); t.SetOptions(snapping).SetTarget(target); return t; } /// <summary>Tweens an LayoutElement's minWidth/Height to the given value. /// Also stores the LayoutElement as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOMinSize(this LayoutElement target, Vector2 endValue, float duration, bool snapping = false) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => new Vector2(target.minWidth, target.minHeight), x => { target.minWidth = x.x; target.minHeight = x.y; }, endValue, duration); t.SetOptions(snapping).SetTarget(target); return t; } /// <summary>Tweens an LayoutElement's preferredWidth/Height to the given value. /// Also stores the LayoutElement as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOPreferredSize(this LayoutElement target, Vector2 endValue, float duration, bool snapping = false) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => new Vector2(target.preferredWidth, target.preferredHeight), x => { target.preferredWidth = x.x; target.preferredHeight = x.y; }, endValue, duration); t.SetOptions(snapping).SetTarget(target); return t; } #endregion #region Outline /// <summary>Tweens a Outline's effectColor to the given value. /// Also stores the Outline as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Color, Color, ColorOptions> DOColor(this Outline target, Color endValue, float duration) { TweenerCore<Color, Color, ColorOptions> t = DOTween.To(() => target.effectColor, x => target.effectColor = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens a Outline's effectColor alpha to the given value. /// Also stores the Outline as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Color, Color, ColorOptions> DOFade(this Outline target, float endValue, float duration) { TweenerCore<Color, Color, ColorOptions> t = DOTween.ToAlpha(() => target.effectColor, x => target.effectColor = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens a Outline's effectDistance to the given value. /// Also stores the Outline as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOScale(this Outline target, Vector2 endValue, float duration) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.effectDistance, x => target.effectDistance = x, endValue, duration); t.SetTarget(target); return t; } #endregion #region RectTransform /// <summary>Tweens a RectTransform's anchoredPosition to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorPos(this RectTransform target, Vector2 endValue, float duration, bool snapping = false) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, endValue, duration); t.SetOptions(snapping).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's anchoredPosition X to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorPosX(this RectTransform target, float endValue, float duration, bool snapping = false) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(endValue, 0), duration); t.SetOptions(AxisConstraint.X, snapping).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's anchoredPosition Y to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorPosY(this RectTransform target, float endValue, float duration, bool snapping = false) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(0, endValue), duration); t.SetOptions(AxisConstraint.Y, snapping).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's anchoredPosition3D to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector3, Vector3, VectorOptions> DOAnchorPos3D(this RectTransform target, Vector3 endValue, float duration, bool snapping = false) { TweenerCore<Vector3, Vector3, VectorOptions> t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, endValue, duration); t.SetOptions(snapping).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's anchoredPosition3D X to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector3, Vector3, VectorOptions> DOAnchorPos3DX(this RectTransform target, float endValue, float duration, bool snapping = false) { TweenerCore<Vector3, Vector3, VectorOptions> t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, new Vector3(endValue, 0, 0), duration); t.SetOptions(AxisConstraint.X, snapping).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's anchoredPosition3D Y to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector3, Vector3, VectorOptions> DOAnchorPos3DY(this RectTransform target, float endValue, float duration, bool snapping = false) { TweenerCore<Vector3, Vector3, VectorOptions> t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, new Vector3(0, endValue, 0), duration); t.SetOptions(AxisConstraint.Y, snapping).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's anchoredPosition3D Z to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector3, Vector3, VectorOptions> DOAnchorPos3DZ(this RectTransform target, float endValue, float duration, bool snapping = false) { TweenerCore<Vector3, Vector3, VectorOptions> t = DOTween.To(() => target.anchoredPosition3D, x => target.anchoredPosition3D = x, new Vector3(0, 0, endValue), duration); t.SetOptions(AxisConstraint.Z, snapping).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's anchorMax to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorMax(this RectTransform target, Vector2 endValue, float duration, bool snapping = false) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchorMax, x => target.anchorMax = x, endValue, duration); t.SetOptions(snapping).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's anchorMin to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOAnchorMin(this RectTransform target, Vector2 endValue, float duration, bool snapping = false) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.anchorMin, x => target.anchorMin = x, endValue, duration); t.SetOptions(snapping).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's pivot to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOPivot(this RectTransform target, Vector2 endValue, float duration) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.pivot, x => target.pivot = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens a RectTransform's pivot X to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOPivotX(this RectTransform target, float endValue, float duration) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.pivot, x => target.pivot = x, new Vector2(endValue, 0), duration); t.SetOptions(AxisConstraint.X).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's pivot Y to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOPivotY(this RectTransform target, float endValue, float duration) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.pivot, x => target.pivot = x, new Vector2(0, endValue), duration); t.SetOptions(AxisConstraint.Y).SetTarget(target); return t; } /// <summary>Tweens a RectTransform's sizeDelta to the given value. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, VectorOptions> DOSizeDelta(this RectTransform target, Vector2 endValue, float duration, bool snapping = false) { TweenerCore<Vector2, Vector2, VectorOptions> t = DOTween.To(() => target.sizeDelta, x => target.sizeDelta = x, endValue, duration); t.SetOptions(snapping).SetTarget(target); return t; } /// <summary>Punches a RectTransform's anchoredPosition towards the given direction and then back to the starting one /// as if it was connected to the starting position via an elastic. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="punch">The direction and strength of the punch (added to the RectTransform's current position)</param> /// <param name="duration">The duration of the tween</param> /// <param name="vibrato">Indicates how much will the punch vibrate</param> /// <param name="elasticity">Represents how much (0 to 1) the vector will go beyond the starting position when bouncing backwards. /// 1 creates a full oscillation between the punch direction and the opposite direction, /// while 0 oscillates only between the punch and the start position</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static Tweener DOPunchAnchorPos(this RectTransform target, Vector2 punch, float duration, int vibrato = 10, float elasticity = 1, bool snapping = false) { return DOTween.Punch(() => target.anchoredPosition, x => target.anchoredPosition = x, punch, duration, vibrato, elasticity) .SetTarget(target).SetOptions(snapping); } /// <summary>Shakes a RectTransform's anchoredPosition with the given values. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="duration">The duration of the tween</param> /// <param name="strength">The shake strength</param> /// <param name="vibrato">Indicates how much will the shake vibrate</param> /// <param name="randomness">Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). /// Setting it to 0 will shake along a single direction.</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> /// <param name="fadeOut">If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not</param> /// <param name="randomnessMode">Randomness mode</param> public static Tweener DOShakeAnchorPos(this RectTransform target, float duration, float strength = 100, int vibrato = 10, float randomness = 90, bool snapping = false, bool fadeOut = true, ShakeRandomnessMode randomnessMode = ShakeRandomnessMode.Full) { return DOTween.Shake(() => target.anchoredPosition, x => target.anchoredPosition = x, duration, strength, vibrato, randomness, true, fadeOut, randomnessMode) .SetTarget(target).SetSpecialStartupMode(SpecialStartupMode.SetShake).SetOptions(snapping); } /// <summary>Shakes a RectTransform's anchoredPosition with the given values. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="duration">The duration of the tween</param> /// <param name="strength">The shake strength on each axis</param> /// <param name="vibrato">Indicates how much will the shake vibrate</param> /// <param name="randomness">Indicates how much the shake will be random (0 to 180 - values higher than 90 kind of suck, so beware). /// Setting it to 0 will shake along a single direction.</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> /// <param name="fadeOut">If TRUE the shake will automatically fadeOut smoothly within the tween's duration, otherwise it will not</param> /// <param name="randomnessMode">Randomness mode</param> public static Tweener DOShakeAnchorPos(this RectTransform target, float duration, Vector2 strength, int vibrato = 10, float randomness = 90, bool snapping = false, bool fadeOut = true, ShakeRandomnessMode randomnessMode = ShakeRandomnessMode.Full) { return DOTween.Shake(() => target.anchoredPosition, x => target.anchoredPosition = x, duration, strength, vibrato, randomness, fadeOut, randomnessMode) .SetTarget(target).SetSpecialStartupMode(SpecialStartupMode.SetShake).SetOptions(snapping); } #region Special /// <summary>Tweens a RectTransform's anchoredPosition to the given value, while also applying a jump effect along the Y axis. /// Returns a Sequence instead of a Tweener. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param> /// <param name="jumpPower">Power of the jump (the max height of the jump is represented by this plus the final Y offset)</param> /// <param name="numJumps">Total number of jumps</param> /// <param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static Sequence DOJumpAnchorPos(this RectTransform target, Vector2 endValue, float jumpPower, int numJumps, float duration, bool snapping = false) { if (numJumps < 1) numJumps = 1; float startPosY = 0; float offsetY = -1; bool offsetYSet = false; // Separate Y Tween so we can elaborate elapsedPercentage on that insted of on the Sequence // (in case users add a delay or other elements to the Sequence) Sequence s = DOTween.Sequence(); Tween yTween = DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(0, jumpPower), duration / (numJumps * 2)) .SetOptions(AxisConstraint.Y, snapping).SetEase(Ease.OutQuad).SetRelative() .SetLoops(numJumps * 2, LoopType.Yoyo) .OnStart(()=> startPosY = target.anchoredPosition.y); s.Append(DOTween.To(() => target.anchoredPosition, x => target.anchoredPosition = x, new Vector2(endValue.x, 0), duration) .SetOptions(AxisConstraint.X, snapping).SetEase(Ease.Linear) ).Join(yTween) .SetTarget(target).SetEase(DOTween.defaultEaseType); s.OnUpdate(() => { if (!offsetYSet) { offsetYSet = true; offsetY = s.isRelative ? endValue.y : endValue.y - startPosY; } Vector2 pos = target.anchoredPosition; pos.y += DOVirtual.EasedValue(0, offsetY, s.ElapsedDirectionalPercentage(), Ease.OutQuad); target.anchoredPosition = pos; }); return s; } #endregion #endregion #region ScrollRect /// <summary>Tweens a ScrollRect's horizontal/verticalNormalizedPosition to the given value. /// Also stores the ScrollRect as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static Tweener DONormalizedPos(this ScrollRect target, Vector2 endValue, float duration, bool snapping = false) { return DOTween.To(() => new Vector2(target.horizontalNormalizedPosition, target.verticalNormalizedPosition), x => { target.horizontalNormalizedPosition = x.x; target.verticalNormalizedPosition = x.y; }, endValue, duration) .SetOptions(snapping).SetTarget(target); } /// <summary>Tweens a ScrollRect's horizontalNormalizedPosition to the given value. /// Also stores the ScrollRect as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static Tweener DOHorizontalNormalizedPos(this ScrollRect target, float endValue, float duration, bool snapping = false) { return DOTween.To(() => target.horizontalNormalizedPosition, x => target.horizontalNormalizedPosition = x, endValue, duration) .SetOptions(snapping).SetTarget(target); } /// <summary>Tweens a ScrollRect's verticalNormalizedPosition to the given value. /// Also stores the ScrollRect as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static Tweener DOVerticalNormalizedPos(this ScrollRect target, float endValue, float duration, bool snapping = false) { return DOTween.To(() => target.verticalNormalizedPosition, x => target.verticalNormalizedPosition = x, endValue, duration) .SetOptions(snapping).SetTarget(target); } #endregion #region Slider /// <summary>Tweens a Slider's value to the given value. /// Also stores the Slider as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<float, float, FloatOptions> DOValue(this Slider target, float endValue, float duration, bool snapping = false) { TweenerCore<float, float, FloatOptions> t = DOTween.To(() => target.value, x => target.value = x, endValue, duration); t.SetOptions(snapping).SetTarget(target); return t; } #endregion #region Text /// <summary>Tweens a Text's color to the given value. /// Also stores the Text as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Color, Color, ColorOptions> DOColor(this Text target, Color endValue, float duration) { TweenerCore<Color, Color, ColorOptions> t = DOTween.To(() => target.color, x => target.color = x, endValue, duration); t.SetTarget(target); return t; } /// <summary> /// Tweens a Text's text from one integer to another, with options for thousands separators /// </summary> /// <param name="fromValue">The value to start from</param> /// <param name="endValue">The end value to reach</param> /// <param name="duration">The duration of the tween</param> /// <param name="addThousandsSeparator">If TRUE (default) also adds thousands separators</param> /// <param name="culture">The <see cref="CultureInfo"/> to use (InvariantCulture if NULL)</param> public static TweenerCore<int, int, NoOptions> DOCounter( this Text target, int fromValue, int endValue, float duration, bool addThousandsSeparator = true, CultureInfo culture = null ){ int v = fromValue; CultureInfo cInfo = !addThousandsSeparator ? null : culture ?? CultureInfo.InvariantCulture; TweenerCore<int, int, NoOptions> t = DOTween.To(() => v, x => { v = x; target.text = addThousandsSeparator ? v.ToString("N0", cInfo) : v.ToString(); }, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens a Text's alpha color to the given value. /// Also stores the Text as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end value to reach</param><param name="duration">The duration of the tween</param> public static TweenerCore<Color, Color, ColorOptions> DOFade(this Text target, float endValue, float duration) { TweenerCore<Color, Color, ColorOptions> t = DOTween.ToAlpha(() => target.color, x => target.color = x, endValue, duration); t.SetTarget(target); return t; } /// <summary>Tweens a Text's text to the given value. /// Also stores the Text as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The end string to tween to</param><param name="duration">The duration of the tween</param> /// <param name="richTextEnabled">If TRUE (default), rich text will be interpreted correctly while animated, /// otherwise all tags will be considered as normal text</param> /// <param name="scrambleMode">The type of scramble mode to use, if any</param> /// <param name="scrambleChars">A string containing the characters to use for scrambling. /// Use as many characters as possible (minimum 10) because DOTween uses a fast scramble mode which gives better results with more characters. /// Leave it to NULL (default) to use default ones</param> public static TweenerCore<string, string, StringOptions> DOText(this Text target, string endValue, float duration, bool richTextEnabled = true, ScrambleMode scrambleMode = ScrambleMode.None, string scrambleChars = null) { if (endValue == null) { if (Debugger.logPriority > 0) Debugger.LogWarning("You can't pass a NULL string to DOText: an empty string will be used instead to avoid errors"); endValue = ""; } TweenerCore<string, string, StringOptions> t = DOTween.To(() => target.text, x => target.text = x, endValue, duration); t.SetOptions(richTextEnabled, scrambleMode, scrambleChars) .SetTarget(target); return t; } #endregion #region Blendables #region Graphic /// <summary>Tweens a Graphic's color to the given value, /// in a way that allows other DOBlendableColor tweens to work together on the same target, /// instead than fight each other as multiple DOColor would do. /// Also stores the Graphic as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The value to tween to</param><param name="duration">The duration of the tween</param> public static Tweener DOBlendableColor(this Graphic target, Color endValue, float duration) { endValue = endValue - target.color; Color to = new Color(0, 0, 0, 0); return DOTween.To(() => to, x => { Color diff = x - to; to = x; target.color += diff; }, endValue, duration) .Blendable().SetTarget(target); } #endregion #region Image /// <summary>Tweens a Image's color to the given value, /// in a way that allows other DOBlendableColor tweens to work together on the same target, /// instead than fight each other as multiple DOColor would do. /// Also stores the Image as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The value to tween to</param><param name="duration">The duration of the tween</param> public static Tweener DOBlendableColor(this Image target, Color endValue, float duration) { endValue = endValue - target.color; Color to = new Color(0, 0, 0, 0); return DOTween.To(() => to, x => { Color diff = x - to; to = x; target.color += diff; }, endValue, duration) .Blendable().SetTarget(target); } #endregion #region Text /// <summary>Tweens a Text's color BY the given value, /// in a way that allows other DOBlendableColor tweens to work together on the same target, /// instead than fight each other as multiple DOColor would do. /// Also stores the Text as the tween's target so it can be used for filtered operations</summary> /// <param name="endValue">The value to tween to</param><param name="duration">The duration of the tween</param> public static Tweener DOBlendableColor(this Text target, Color endValue, float duration) { endValue = endValue - target.color; Color to = new Color(0, 0, 0, 0); return DOTween.To(() => to, x => { Color diff = x - to; to = x; target.color += diff; }, endValue, duration) .Blendable().SetTarget(target); } #endregion #endregion #region Shapes /// <summary>Tweens a RectTransform's anchoredPosition so that it draws a circle around the given center. /// Also stores the RectTransform as the tween's target so it can be used for filtered operations.<para/> /// IMPORTANT: SetFrom(value) requires a <see cref="Vector2"/> instead of a float, where the X property represents the "from degrees value"</summary> /// <param name="center">Circle-center/pivot around which to rotate (in UI anchoredPosition coordinates)</param> /// <param name="endValueDegrees">The end value degrees to reach (to rotate counter-clockwise pass a negative value)</param> /// <param name="duration">The duration of the tween</param> /// <param name="relativeCenter">If TRUE the <see cref="center"/> coordinates will be considered as relative to the target's current anchoredPosition</param> /// <param name="snapping">If TRUE the tween will smoothly snap all values to integers</param> public static TweenerCore<Vector2, Vector2, CircleOptions> DOShapeCircle( this RectTransform target, Vector2 center, float endValueDegrees, float duration, bool relativeCenter = false, bool snapping = false ) { TweenerCore<Vector2, Vector2, CircleOptions> t = DOTween.To( CirclePlugin.Get(), () => target.anchoredPosition, x => target.anchoredPosition = x, center, duration ); t.SetOptions(endValueDegrees, relativeCenter, snapping).SetTarget(target); return t; } #endregion #endregion // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ // ███ INTERNAL CLASSES ████████████████████████████████████████████████████████████████████████████████████████████████ // █████████████████████████████████████████████████████████████████████████████████████████████████████████████████████ public static class Utils { /// <summary> /// Converts the anchoredPosition of the first RectTransform to the second RectTransform, /// taking into consideration offset, anchors and pivot, and returns the new anchoredPosition /// </summary> public static Vector2 SwitchToRectTransform(RectTransform from, RectTransform to) { Vector2 localPoint; Vector2 fromPivotDerivedOffset = new Vector2(from.rect.width * 0.5f + from.rect.xMin, from.rect.height * 0.5f + from.rect.yMin); Vector2 screenP = RectTransformUtility.WorldToScreenPoint(null, from.position); screenP += fromPivotDerivedOffset; RectTransformUtility.ScreenPointToLocalPointInRectangle(to, screenP, null, out localPoint); Vector2 pivotDerivedOffset = new Vector2(to.rect.width * 0.5f + to.rect.xMin, to.rect.height * 0.5f + to.rect.yMin); return to.anchoredPosition + localPoint - pivotDerivedOffset; } } } } #endif
1
0.929233
1
0.929233
game-dev
MEDIA
0.406734
game-dev
0.96637
1
0.96637
cloudhu/ChineseChessVR
2,173
Assets/VRTK/Examples/Resources/Scripts/LightSaber.cs
namespace VRTK.Examples { using UnityEngine; public class LightSaber : VRTK_InteractableObject { private bool beamActive = false; private Vector2 beamLimits = new Vector2(0f, 1.2f); private float currentBeamSize; private float beamExtendSpeed = 0; private GameObject blade; private Color activeColor; private Color targetColor; private Color[] bladePhaseColors; public override void StartUsing(GameObject usingObject) { base.StartUsing(usingObject); beamExtendSpeed = 5f; bladePhaseColors = new Color[2] { Color.blue, Color.cyan }; activeColor = bladePhaseColors[0]; targetColor = bladePhaseColors[1]; } public override void StopUsing(GameObject usingObject) { base.StopUsing(usingObject); beamExtendSpeed = -5f; } protected void Start() { blade = transform.Find("Blade").gameObject; currentBeamSize = beamLimits.x; SetBeamSize(); } protected override void Update() { base.Update(); currentBeamSize = Mathf.Clamp(blade.transform.localScale.y + (beamExtendSpeed * Time.deltaTime), beamLimits.x, beamLimits.y); SetBeamSize(); PulseBeam(); } private void SetBeamSize() { blade.transform.localScale = new Vector3(1f, currentBeamSize, 1f); beamActive = (currentBeamSize >= beamLimits.y ? true : false); } private void PulseBeam() { if (beamActive) { Color bladeColor = Color.Lerp(activeColor, targetColor, Mathf.PingPong(Time.time, 1)); blade.transform.FindChild("Beam").GetComponent<MeshRenderer>().material.color = bladeColor; if (bladeColor == targetColor) { var previouslyActiveColor = activeColor; activeColor = targetColor; targetColor = previouslyActiveColor; } } } } }
1
0.822178
1
0.822178
game-dev
MEDIA
0.732554
game-dev,graphics-rendering
0.986288
1
0.986288
aurora-sim/Aurora-Sim
46,113
Aurora/Modules/World/Land/LandObject.cs
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * 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 the Aurora-Sim Project 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 DEVELOPERS ``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 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. */ using Aurora.Framework; using Aurora.Framework.ClientInterfaces; using Aurora.Framework.ConsoleFramework; using Aurora.Framework.Modules; using Aurora.Framework.PresenceInfo; using Aurora.Framework.SceneInfo; using Aurora.Framework.SceneInfo.Entities; using Aurora.Framework.Services; using Aurora.Framework.Utilities; using OpenMetaverse; using System; using System.Collections.Generic; using System.Linq; namespace Aurora.Modules.Land { /// <summary> /// Keeps track of a specific piece of land's information /// </summary> public class LandObject : ILandObject { #region Member Variables protected LandData m_landData = new LandData(); private int m_lastSeqId; protected IParcelManagementModule m_parcelManagementModule; protected IScene m_scene; #endregion #region ILandObject Members public LandData LandData { get { return m_landData; } set { //Fix the land data HERE if (m_scene != null) //Not sure that this ever WILL be null... but we'll be safe... value.Maturity = m_scene.RegionInfo.RegionSettings.Maturity; m_landData = value; } } public UUID RegionUUID { get { return m_scene.RegionInfo.RegionID; } } /// <summary> /// Set the media url for this land parcel /// </summary> /// <param name="url"></param> public void SetMediaUrl(string url) { LandData.MediaURL = url; SendLandUpdateToAvatarsOverMe(); } /// <summary> /// Set the music url for this land parcel /// </summary> /// <param name="url"></param> public void SetMusicUrl(string url) { LandData.MusicURL = url; SendLandUpdateToAvatarsOverMe(); } #endregion #region Constructors public LandObject(UUID owner_id, bool is_group_owned, IScene scene) { m_scene = scene; LandData.Maturity = m_scene.RegionInfo.RegionSettings.Maturity; LandData.OwnerID = owner_id; LandData.GroupID = is_group_owned ? owner_id : UUID.Zero; LandData.IsGroupOwned = is_group_owned; LandData.RegionID = scene.RegionInfo.RegionID; LandData.ScopeID = scene.RegionInfo.ScopeID; LandData.RegionHandle = scene.RegionInfo.RegionHandle; m_parcelManagementModule = scene.RequestModuleInterface<IParcelManagementModule>(); //We don't set up the InfoID here... it will just be overwriten } // this is needed for non-convex parcels (example: rectangular parcel, and in the exact center // another, smaller rectangular parcel). Both will have the same initial coordinates. private void findPointInParcel(ILandObject land, ref uint refX, ref uint refY) { // the point we started with already is in the parcel if (land.ContainsPoint((int) refX, (int) refY) && refX != 0 && refY != 0) return; // ... otherwise, we have to search for a point within the parcel uint startX = (uint) land.LandData.AABBMin.X; uint startY = (uint) land.LandData.AABBMin.Y; uint endX = (uint) land.LandData.AABBMax.X; uint endY = (uint) land.LandData.AABBMax.Y; // default: center of the parcel refX = (startX + endX)/2; refY = (startY + endY)/2; // If the center point is within the parcel, take that one if (land.ContainsPoint((int) refX, (int) refY)) return; // otherwise, go the long way. for (uint y = startY; y <= endY; ++y) { for (uint x = startX; x <= endX; ++x) { if (land.ContainsPoint((int) x, (int) y)) { // found a point refX = x; refY = y; return; } } } } #endregion #region Member Functions #region General Functions /// <summary> /// Checks to see if this land object contains a point /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns>Returns true if the piece of land contains the specified point</returns> public bool ContainsPoint(int x, int y) { IParcelManagementModule parcelManModule = m_scene.RequestModuleInterface<IParcelManagementModule>(); if (parcelManModule == null) return false; if (x >= 0 && y >= 0 && x < m_scene.RegionInfo.RegionSizeX && y < m_scene.RegionInfo.RegionSizeY) { return (parcelManModule.LandIDList[x/4, y/4] == LandData.LocalID); } else { return false; } } public ILandObject Copy() { ILandObject newLand = new LandObject(LandData.OwnerID, LandData.IsGroupOwned, m_scene); //Place all new variables here! newLand.LandData = LandData.Copy(); return newLand; } #endregion #region Packet Request Handling public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, IClientAPI remote_client) { IEstateModule estateModule = m_scene.RequestModuleInterface<IEstateModule>(); ulong regionFlags = 336723974 & ~((uint) (OpenMetaverse.RegionFlags.AllowLandmark | OpenMetaverse.RegionFlags.AllowSetHome)); if (estateModule != null) regionFlags = estateModule.GetRegionFlags(); int seq_id; if (snap_selection && (sequence_id == 0)) seq_id = m_lastSeqId; else { seq_id = sequence_id; m_lastSeqId = seq_id; } int MaxPrimCounts = 0; IPrimCountModule primCountModule = m_scene.RequestModuleInterface<IPrimCountModule>(); if (primCountModule != null) { MaxPrimCounts = primCountModule.GetParcelMaxPrimCount(this); } remote_client.SendLandProperties(seq_id, snap_selection, request_result, LandData, (float) m_scene.RegionInfo.RegionSettings.ObjectBonus, MaxPrimCounts, m_scene.RegionInfo.ObjectCapacity, (uint) regionFlags); } public void UpdateLandProperties(LandUpdateArgs args, IClientAPI remote_client) { if (m_scene.RegionInfo.EstateSettings.AllowParcelChanges) { try { bool snap_selection = false; if (args.AuthBuyerID != LandData.AuthBuyerID || args.SalePrice != LandData.SalePrice) { if (m_scene.Permissions.CanSellParcel(remote_client.AgentId, this) && m_scene.RegionInfo.RegionSettings.AllowLandResell) { LandData.AuthBuyerID = args.AuthBuyerID; LandData.SalePrice = args.SalePrice; snap_selection = true; } else { remote_client.SendAlertMessage("Permissions: You cannot set this parcel for sale"); args.ParcelFlags &= ~(uint) ParcelFlags.ForSale; args.ParcelFlags &= ~(uint) ParcelFlags.ForSaleObjects; args.ParcelFlags &= ~(uint) ParcelFlags.SellParcelObjects; } } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.LandSetSale)) { if (!LandData.IsGroupOwned) { LandData.GroupID = args.GroupID; } } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.FindPlaces)) LandData.Category = args.Category; if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.ChangeMedia)) { LandData.MediaAutoScale = args.MediaAutoScale; LandData.MediaID = args.MediaID; LandData.MediaURL = args.MediaURL; LandData.MusicURL = args.MusicURL; LandData.MediaType = args.MediaType; LandData.MediaDescription = args.MediaDescription; LandData.MediaWidth = args.MediaWidth; LandData.MediaHeight = args.MediaHeight; LandData.MediaLoop = args.MediaLoop; LandData.ObscureMusic = args.ObscureMusic; LandData.ObscureMedia = args.ObscureMedia; } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.LandOptions)) { if (m_scene.RegionInfo.RegionSettings.BlockFly && ((args.ParcelFlags & (uint)ParcelFlags.AllowFly) == (uint)ParcelFlags.AllowFly)) //Vanquish flying as per estate settings! args.ParcelFlags &= ~(uint)ParcelFlags.AllowFly; if (m_scene.RegionInfo.RegionSettings.RestrictPushing && ((args.ParcelFlags & (uint)ParcelFlags.RestrictPushObject) == (uint)ParcelFlags.RestrictPushObject)) //Vanquish pushing as per estate settings! args.ParcelFlags &= ~(uint)ParcelFlags.RestrictPushObject; if (!m_scene.RegionInfo.EstateSettings.AllowLandmark && ((args.ParcelFlags & (uint)ParcelFlags.AllowLandmark) == (uint)ParcelFlags.AllowLandmark)) //Vanquish landmarks as per estate settings! args.ParcelFlags &= ~(uint)ParcelFlags.AllowLandmark; if (m_scene.RegionInfo.RegionSettings.BlockShowInSearch && ((args.ParcelFlags & (uint)ParcelFlags.ShowDirectory) == (uint)ParcelFlags.ShowDirectory)) //Vanquish show in search as per estate settings! args.ParcelFlags &= ~(uint)ParcelFlags.ShowDirectory; if ((args.ParcelFlags & (uint)ParcelFlags.ShowDirectory) == (uint)ParcelFlags.ShowDirectory && (LandData.Flags & (uint)ParcelFlags.ShowDirectory) != (uint)ParcelFlags.ShowDirectory) { //If the flags have changed, we need to charge them.. maybe // We really need to check per month or whatever IScheduledMoneyModule scheduledMoneyModule = m_scene.RequestModuleInterface<IScheduledMoneyModule>(); IMoneyModule moneyModule = m_scene.RequestModuleInterface<IMoneyModule>(); if (scheduledMoneyModule != null) { if ((args.ParcelFlags & (uint)ParcelFlags.ShowDirectory) == (uint)ParcelFlags.ShowDirectory) { //Flag is set if (!scheduledMoneyModule.Charge(remote_client.AgentId, moneyModule.DirectoryFeeCharge, "Parcel Show in Search Fee - " + LandData.GlobalID, 7, TransactionType.ParcelDirFee, "ShowInDirectory" + LandData.GlobalID.ToString(), true)) { remote_client.SendAlertMessage( "You don't have enough money to set this parcel in search."); args.ParcelFlags &= (uint)ParcelFlags.ShowDirectory; } } else { scheduledMoneyModule.RemoveFromScheduledCharge("ShowInDirectory" + LandData.GlobalID.ToString()); } } } LandData.Flags = args.ParcelFlags; } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.SetLandingPoint)) { LandData.LandingType = args.LandingType; LandData.UserLocation = args.UserLocation; LandData.UserLookAt = args.UserLookAt; } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.LandChangeIdentity)) { LandData.Description = args.Desc; LandData.Name = args.Name; LandData.SnapshotID = args.SnapshotID; LandData.Private = args.Privacy; } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.LandManagePasses)) { LandData.PassHours = args.PassHours; LandData.PassPrice = args.PassPrice; } LandData.Status = LandData.OwnerID == m_parcelManagementModule.GodParcelOwner ? ParcelStatus.Abandoned : LandData.AuthBuyerID != UUID.Zero ? ParcelStatus.LeasePending : ParcelStatus.Leased; m_parcelManagementModule.UpdateLandObject(this); SendLandUpdateToAvatarsOverMe(snap_selection); } catch (Exception ex) { MainConsole.Instance.Warn("[LAND]: Error updating land object " + this.LandData.Name + " in region " + this.m_scene.RegionInfo.RegionName + " : " + ex); } } } public void UpdateLandSold(UUID avatarID, UUID groupID, bool groupOwned, uint AuctionID, int claimprice, int area) { if ((LandData.Flags & (uint) ParcelFlags.SellParcelObjects) == (uint) ParcelFlags.SellParcelObjects) { //Sell all objects on the parcel too IPrimCountModule primCountModule = m_scene.RequestModuleInterface<IPrimCountModule>(); IPrimCounts primCounts = primCountModule.GetPrimCounts(LandData.GlobalID); foreach (ISceneEntity obj in primCounts.Objects.Where(obj => obj.OwnerID == LandData.OwnerID)) { //Fix the owner/last owner obj.SetOwnerId(avatarID); //Then update all clients around obj.ScheduleGroupUpdate(PrimUpdateFlags.FullUpdate); } } LandData.OwnerID = avatarID; LandData.GroupID = groupID; LandData.IsGroupOwned = groupOwned; LandData.AuctionID = 0; LandData.ClaimDate = Util.UnixTimeSinceEpoch(); LandData.ClaimPrice = claimprice; LandData.SalePrice = 0; LandData.AuthBuyerID = UUID.Zero; LandData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects | ParcelFlags.ShowDirectory); m_parcelManagementModule.UpdateLandObject(this); SendLandUpdateToAvatarsOverMe(true); //Send a full update to the client as well IScenePresence SP = m_scene.GetScenePresence(avatarID); SendLandUpdateToClient(SP.ControllingClient); } public void DeedToGroup(UUID groupID) { LandData.OwnerID = groupID; LandData.GroupID = groupID; LandData.IsGroupOwned = true; // Reset show in directory flag on deed LandData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects | ParcelFlags.ShowDirectory); m_parcelManagementModule.UpdateLandObject(this); } public bool IsEitherBannedOrRestricted(UUID avatar) { if (IsBannedFromLand(avatar)) { return true; } else if (IsRestrictedFromLand(avatar)) { return true; } return false; } public bool IsBannedFromLand(UUID avatar) { if (m_scene.Permissions.IsAdministrator(avatar)) return false; if (LandData.ParcelAccessList.Count > 0) { ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry {AgentID = avatar, Flags = AccessList.Ban}; entry = LandData.ParcelAccessList.Find(delegate(ParcelManager.ParcelAccessEntry pae) { if (entry.AgentID == pae.AgentID && entry.Flags == pae.Flags) return true; return false; }); //See if they are on the list, but make sure the owner isn't banned if (entry.AgentID == avatar && LandData.OwnerID != avatar) { //They are banned, so lets send them a notice about this parcel return true; } } return false; } public bool IsRestrictedFromLand(UUID avatar) { if (m_scene.Permissions.GenericParcelPermission(avatar, this, (ulong) 1)) return false; if ((LandData.Flags & (uint) ParcelFlags.UsePassList) > 0 || (LandData.Flags & (uint) ParcelFlags.UseAccessList) > 0) { if (LandData.ParcelAccessList.Count > 0) { ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry(); bool found = false; foreach ( ParcelManager.ParcelAccessEntry pae in LandData.ParcelAccessList.Where( pae => avatar == pae.AgentID && AccessList.Access == pae.Flags)) { found = true; entry = pae; break; } //If they are not on the access list and are not the owner if (!found) { if ((LandData.Flags & (uint) ParcelFlags.UseAccessGroup) != 0) { IScenePresence SP = m_scene.GetScenePresence(avatar); if (SP != null && LandData.GroupID == SP.ControllingClient.ActiveGroupId) { //They are a part of the group, let them in return false; } else { //They are not allowed in this parcel, but not banned, so lets send them a notice about this parcel return true; } } else { //No group checking, not on the access list, restricted return true; } } else { //If it does, we need to check the time if (entry.Time.Ticks < DateTime.Now.Ticks) { //Time expired, remove them LandData.ParcelAccessList.Remove(entry); return true; } return false; } } else if ((LandData.Flags & (uint) ParcelFlags.UseAccessGroup) > 0) { IScenePresence SP = m_scene.GetScenePresence(avatar); if (SP != null && LandData.GroupID == SP.ControllingClient.ActiveGroupId) { //They are a part of the group, let them in return false; } else { //They are not allowed in this parcel, but not banned, so lets send them a notice about this parcel return true; } } return true; } return false; } public void SendLandUpdateToClient(IClientAPI remote_client) { SendLandProperties(0, false, 0, remote_client); } public void SendLandUpdateToClient(bool snap_selection, IClientAPI remote_client) { SendLandProperties(0, snap_selection, 0, remote_client); } public void SendLandUpdateToAvatarsOverMe() { SendLandUpdateToAvatarsOverMe(true); } public void SendLandUpdateToAvatarsOverMe(bool snap_selection) { m_scene.ForEachScenePresence(delegate(IScenePresence avatar) { if (avatar.IsChildAgent) return; if (avatar.CurrentParcel.LandData.LocalID == LandData.LocalID) { if (((avatar.CurrentParcel.LandData.Flags & (uint) ParcelFlags.AllowDamage) != 0) || m_scene.RegionInfo.RegionSettings.AllowDamage) avatar.Invulnerable = false; else avatar.Invulnerable = true; SendLandUpdateToClient(snap_selection, avatar.ControllingClient); } }); } #endregion #region AccessList Functions public List<List<UUID>> CreateAccessListArrayByFlag(AccessList flag) { List<List<UUID>> list = new List<List<UUID>>(); int num = 0; list.Add(new List<UUID>()); foreach ( ParcelManager.ParcelAccessEntry entry in LandData.ParcelAccessList.Where(entry => entry.Flags == flag)) { if (list[num].Count > ParcelManagementModule.LAND_MAX_ENTRIES_PER_PACKET) { num++; list.Add(new List<UUID>()); } list[num].Add(entry.AgentID); } if (list[0].Count == 0) { list[num].Add(UUID.Zero); } return list; } public void SendAccessList(UUID agentID, UUID sessionID, uint flags, int sequenceID, IClientAPI remote_client) { if (flags == (uint) AccessList.Access || flags == (uint) AccessList.Both) { List<List<UUID>> avatars = CreateAccessListArrayByFlag(AccessList.Access); foreach (List<UUID> accessListAvs in avatars) { remote_client.SendLandAccessListData(accessListAvs, (uint) AccessList.Access, LandData.LocalID); } } if (flags == (uint) AccessList.Ban || flags == (uint) AccessList.Both) { List<List<UUID>> avatars = CreateAccessListArrayByFlag(AccessList.Ban); foreach (List<UUID> accessListAvs in avatars) { remote_client.SendLandAccessListData(accessListAvs, (uint) AccessList.Ban, LandData.LocalID); } } } public void UpdateAccessList(uint flags, List<ParcelManager.ParcelAccessEntry> entries, IClientAPI remote_client) { if (entries.Count == 1 && entries[0].AgentID == UUID.Zero) entries.Clear(); List<ParcelManager.ParcelAccessEntry> toRemove = LandData.ParcelAccessList.Where(entry => entry.Flags == (AccessList) flags).ToList(); foreach (ParcelManager.ParcelAccessEntry entry in toRemove) { LandData.ParcelAccessList.Remove(entry); } foreach (ParcelManager.ParcelAccessEntry temp in entries.Select(entry => new ParcelManager.ParcelAccessEntry { AgentID = entry.AgentID, Time = DateTime.MaxValue, Flags = (AccessList) flags }) .Where( temp => !LandData.ParcelAccessList.Contains(temp))) { LandData.ParcelAccessList.Add(temp); } m_parcelManagementModule.UpdateLandObject(this); } #endregion #region Update Functions /// <summary> /// Update all settings in land such as area, bitmap byte array, etc /// </summary> public void ForceUpdateLandInfo() { UpdateAABBAndAreaValues(); } /// <summary> /// Updates the AABBMin and AABBMax values after area/shape modification of the land object /// </summary> private void UpdateAABBAndAreaValues() { ITerrainChannel heightmap = m_scene.RequestModuleInterface<ITerrainChannel>(); IParcelManagementModule parcelManModule = m_scene.RequestModuleInterface<IParcelManagementModule>(); int min_x = m_scene.RegionInfo.RegionSizeX/4; int min_y = m_scene.RegionInfo.RegionSizeY/4; int max_x = 0; int max_y = 0; int tempArea = 0; int x, y; for (x = 0; x < m_scene.RegionInfo.RegionSizeX/4; x++) { for (y = 0; y < m_scene.RegionInfo.RegionSizeY/4; y++) { if (parcelManModule.LandIDList[x, y] == LandData.LocalID) { if (min_x > x) min_x = x; if (min_y > y) min_y = y; if (max_x < x) max_x = x; if (max_y < y) max_y = y; tempArea += 16; //16sqm peice of land } } } int tx = min_x*4; if (tx > (m_scene.RegionInfo.RegionSizeX - 1)) tx = (m_scene.RegionInfo.RegionSizeX - 1); int ty = min_y*4; if (ty > (m_scene.RegionInfo.RegionSizeY - 1)) ty = (m_scene.RegionInfo.RegionSizeY - 1); float min = heightmap != null ? heightmap[tx, ty] : 0; LandData.AABBMin = new Vector3((min_x*4), (min_y*4), min); tx = max_x*4; if (tx > (m_scene.RegionInfo.RegionSizeX - 1)) tx = (m_scene.RegionInfo.RegionSizeX - 1); ty = max_y*4; if (ty > (m_scene.RegionInfo.RegionSizeY - 1)) ty = (m_scene.RegionInfo.RegionSizeY - 1); min = heightmap != null ? heightmap[tx, ty] : 0; LandData.AABBMax = new Vector3((max_x*4), (max_y*4), min); LandData.Area = tempArea; } #endregion #region Object Select and Object Owner Listing public void SendForceObjectSelect(int local_id, int request_type, List<UUID> returnIDs, IClientAPI remote_client) { if (m_scene.Permissions.CanEditParcel(remote_client.AgentId, this)) { List<uint> resultLocalIDs = new List<uint>(); try { IPrimCountModule primCountModule = m_scene.RequestModuleInterface<IPrimCountModule>(); IPrimCounts primCounts = primCountModule.GetPrimCounts(LandData.GlobalID); foreach (ISceneEntity obj in primCounts.Objects.Where(obj => obj.LocalId > 0)) { if (request_type == ParcelManagementModule.LAND_SELECT_OBJECTS_OWNER && obj.OwnerID == LandData.OwnerID) { resultLocalIDs.Add(obj.LocalId); } else if (request_type == ParcelManagementModule.LAND_SELECT_OBJECTS_GROUP && obj.GroupID == LandData.GroupID && LandData.GroupID != UUID.Zero) { resultLocalIDs.Add(obj.LocalId); } else if (request_type == ParcelManagementModule.LAND_SELECT_OBJECTS_OTHER && obj.OwnerID != remote_client.AgentId) { resultLocalIDs.Add(obj.LocalId); } else if (request_type == (int) ObjectReturnType.List && returnIDs.Contains(obj.OwnerID)) { resultLocalIDs.Add(obj.LocalId); } else if (request_type == (int) ObjectReturnType.Sell && obj.OwnerID == remote_client.AgentId) { resultLocalIDs.Add(obj.LocalId); } } } catch (InvalidOperationException) { MainConsole.Instance.Error("[LAND]: Unable to force select the parcel objects. Arr."); } remote_client.SendForceClientSelectObjects(resultLocalIDs); } } /// <summary> /// Notify the parcel owner each avatar that owns prims situated on their land. This notification includes /// aggreagete details such as the number of prims. /// </summary> /// <param name="remote_client"> /// <see cref="IClientAPI" /> /// </param> public void SendLandObjectOwners(IClientAPI remote_client) { if (m_scene.Permissions.CanViewObjectOwners(remote_client.AgentId, this)) { IPrimCountModule primCountModule = m_scene.RequestModuleInterface<IPrimCountModule>(); if (primCountModule != null) { IPrimCounts primCounts = primCountModule.GetPrimCounts(LandData.GlobalID); Dictionary<UUID, LandObjectOwners> owners = new Dictionary<UUID, LandObjectOwners>(); foreach (ISceneEntity grp in primCounts.Objects) { bool newlyAdded = false; LandObjectOwners landObj; if (!owners.TryGetValue(grp.OwnerID, out landObj)) { landObj = new LandObjectOwners(); owners.Add(grp.OwnerID, landObj); newlyAdded = true; } landObj.Count += grp.PrimCount; //Only do all of this once if (newlyAdded) { if (grp.GroupID != UUID.Zero && grp.GroupID == grp.OwnerID) landObj.GroupOwned = true; else landObj.GroupOwned = false; if (landObj.GroupOwned) landObj.Online = false; else { IAgentInfoService presenceS = m_scene.RequestModuleInterface<IAgentInfoService>(); UserInfo info = presenceS.GetUserInfo(grp.OwnerID.ToString()); if (info != null) landObj.Online = info.IsOnline; } landObj.OwnerID = grp.OwnerID; } if (grp.RootChild.Rezzed > landObj.TimeLastRezzed) landObj.TimeLastRezzed = grp.RootChild.Rezzed; } remote_client.SendLandObjectOwners(new List<LandObjectOwners>(owners.Values)); } } } #endregion #region Object Returning public List<ISceneEntity> GetPrimsOverByOwner(UUID targetID, int flags) { List<ISceneEntity> prims = new List<ISceneEntity>(); IPrimCountModule primCountModule = m_scene.RequestModuleInterface<IPrimCountModule>(); IPrimCounts primCounts = primCountModule.GetPrimCounts(LandData.GlobalID); foreach (ISceneEntity obj in primCounts.Objects.Where(obj => obj.OwnerID == m_landData.OwnerID)) { if (flags == 4) { bool containsScripts = obj.ChildrenEntities().Any(child => child.Inventory.ContainsScripts()); if (!containsScripts) continue; } prims.Add(obj); } return prims; } public void ReturnLandObjects(uint type, UUID[] owners, UUID[] tasks, IClientAPI remote_client) { Dictionary<UUID, List<ISceneEntity>> returns = new Dictionary<UUID, List<ISceneEntity>>(); IPrimCountModule primCountModule = m_scene.RequestModuleInterface<IPrimCountModule>(); IPrimCounts primCounts = primCountModule.GetPrimCounts(LandData.GlobalID); if (type == (uint) ObjectReturnType.Owner) { foreach (ISceneEntity obj in primCounts.Objects.Where(obj => obj.OwnerID == m_landData.OwnerID)) { if (!returns.ContainsKey(obj.OwnerID)) returns[obj.OwnerID] = new List<ISceneEntity>(); if (!returns[obj.OwnerID].Contains(obj)) returns[obj.OwnerID].Add(obj); } } else if (type == (uint) ObjectReturnType.Group && m_landData.GroupID != UUID.Zero) { foreach (ISceneEntity obj in primCounts.Objects.Where(obj => obj.GroupID == m_landData.GroupID)) { if (!returns.ContainsKey(obj.OwnerID)) returns[obj.OwnerID] = new List<ISceneEntity>(); if (!returns[obj.OwnerID].Contains(obj)) returns[obj.OwnerID].Add(obj); } } else if (type == (uint) ObjectReturnType.Other) { foreach (ISceneEntity obj in primCounts.Objects.Where(obj => obj.OwnerID != m_landData.OwnerID && (obj.GroupID != m_landData.GroupID || m_landData.GroupID == UUID.Zero))) { if (!returns.ContainsKey(obj.OwnerID)) returns[obj.OwnerID] = new List<ISceneEntity>(); if (!returns[obj.OwnerID].Contains(obj)) returns[obj.OwnerID].Add(obj); } } else if (type == (uint) ObjectReturnType.List) { List<UUID> ownerlist = new List<UUID>(owners); foreach (ISceneEntity obj in primCounts.Objects.Where(obj => ownerlist.Contains(obj.OwnerID))) { if (!returns.ContainsKey(obj.OwnerID)) returns[obj.OwnerID] = new List<ISceneEntity>(); if (!returns[obj.OwnerID].Contains(obj)) returns[obj.OwnerID].Add(obj); } } else if (type == 1) { List<UUID> Tasks = new List<UUID>(tasks); foreach (ISceneEntity obj in primCounts.Objects.Where(obj => Tasks.Contains(obj.UUID))) { if (!returns.ContainsKey(obj.OwnerID)) returns[obj.OwnerID] = new List<ISceneEntity>(); if (!returns[obj.OwnerID].Contains(obj)) returns[obj.OwnerID].Add(obj); } } foreach ( List<ISceneEntity> ol in returns.Values.Where(ol => m_scene.Permissions.CanReturnObjects(this, remote_client.AgentId, ol))) { //The return system will take care of the returned objects m_parcelManagementModule.AddReturns(ol[0].OwnerID, ol[0].Name, ol[0].AbsolutePosition, "Parcel Owner Return", ol); //m_scene.returnObjects(ol.ToArray(), remote_client.AgentId); } } public void DisableLandObjects(uint type, UUID[] owners, UUID[] tasks, IClientAPI remote_client) { Dictionary<UUID, List<ISceneEntity>> disabled = new Dictionary<UUID, List<ISceneEntity>>(); IPrimCountModule primCountModule = m_scene.RequestModuleInterface<IPrimCountModule>(); IPrimCounts primCounts = primCountModule.GetPrimCounts(LandData.GlobalID); if (type == (uint) ObjectReturnType.Owner) { foreach (ISceneEntity obj in primCounts.Objects.Where(obj => obj.OwnerID == m_landData.OwnerID)) { if (!disabled.ContainsKey(obj.OwnerID)) disabled[obj.OwnerID] = new List<ISceneEntity>(); disabled[obj.OwnerID].Add(obj); } } else if (type == (uint) ObjectReturnType.Group && m_landData.GroupID != UUID.Zero) { foreach (ISceneEntity obj in primCounts.Objects.Where(obj => obj.GroupID == m_landData.GroupID)) { if (!disabled.ContainsKey(obj.OwnerID)) disabled[obj.OwnerID] = new List<ISceneEntity>(); disabled[obj.OwnerID].Add(obj); } } else if (type == (uint) ObjectReturnType.Other) { foreach (ISceneEntity obj in primCounts.Objects.Where(obj => obj.OwnerID != m_landData.OwnerID && (obj.GroupID != m_landData.GroupID || m_landData.GroupID == UUID.Zero))) { if (!disabled.ContainsKey(obj.OwnerID)) disabled[obj.OwnerID] = new List<ISceneEntity>(); disabled[obj.OwnerID].Add(obj); } } else if (type == (uint) ObjectReturnType.List) { List<UUID> ownerlist = new List<UUID>(owners); foreach (ISceneEntity obj in primCounts.Objects.Where(obj => ownerlist.Contains(obj.OwnerID))) { if (!disabled.ContainsKey(obj.OwnerID)) disabled[obj.OwnerID] = new List<ISceneEntity>(); disabled[obj.OwnerID].Add(obj); } } else if (type == 1) { List<UUID> Tasks = new List<UUID>(tasks); foreach (ISceneEntity obj in primCounts.Objects.Where(obj => Tasks.Contains(obj.UUID))) { if (!disabled.ContainsKey(obj.OwnerID)) disabled[obj.OwnerID] = new List<ISceneEntity>(); disabled[obj.OwnerID].Add(obj); } } IScriptModule[] modules = m_scene.RequestModuleInterfaces<IScriptModule>(); foreach (List<ISceneEntity> ol in disabled.Values) { foreach (ISceneEntity group in ol) { if (m_scene.Permissions.CanEditObject(group.UUID, remote_client.AgentId)) { foreach (IScriptModule module in modules) { //Disable the entire object foreach (ISceneChildEntity part in group.ChildrenEntities()) { foreach (TaskInventoryItem item in part.Inventory.GetInventoryItems()) { if (item.InvType == (int) InventoryType.LSL) { module.SuspendScript(item.ItemID); } } } } } } } } #endregion #endregion } }
1
0.964352
1
0.964352
game-dev
MEDIA
0.549838
game-dev
0.93595
1
0.93595