text
stringlengths
33
161k
plugins { application `maven-publish` id("com.github.johnrengelman.shadow") version "8.1.1" kotlin("jvm") version("1.9.21") } val darkanVersion: String = "1.9.0" val ktVer: String = "1.9.21" application { group = "rs.darkan" version = darkanVersion mainClass.set("com.rs.Launcher") } java { toolchain.languageVersion = JavaLanguageVersion.of(21) } repositories { mavenLocal() mavenCentral() maven("https://gitlab.com/api/v4/projects/42379000/packages/maven") } dependencies { implementation("rs.darkan:core:1.6.8") implementation("org.jetbrains.kotlin:kotlin-stdlib:$ktVer") implementation("org.jetbrains.kotlin:kotlin-stdlib-common:$ktVer") implementation("org.jetbrains.kotlin:kotlin-scripting-common:$ktVer") implementation("org.jetbrains.kotlin:kotlin-scripting-jvm:$ktVer") implementation("org.jetbrains.kotlin:kotlin-scripting-jvm-host:$ktVer") implementation("org.jetbrains.kotlin:kotlin-main-kts:$ktVer") implementation("org.jetbrains.kotlin:kotlin-script-runtime:$ktVer") implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.0-RC2") implementation("org.openjdk.jmh:jmh-core:1.37") implementation("com.google.code.gson:gson:2.10.1") implementation("com.google.guava:guava:33.0.0-jre") implementation("org.mongodb:mongodb-driver-sync:4.11.1") implementation("org.mongodb:mongodb-driver-core:4.11.1") implementation("io.netty:netty-all:4.1.104.Final") implementation("io.undertow:undertow-core:2.3.10.Final") implementation("it.unimi.dsi:fastutil:8.5.12") implementation("com.trivago:fastutil-concurrent-wrapper:0.2.2") // TODO: Deprecated. Upstream dead. Replace with unirest implementation("com.squareup.okhttp3:okhttp:4.12.0") } tasks.withType<ShadowJar> { isZip64 = true mergeServiceFiles() } publishing { val ciProjectId: String? = System.getenv("CI_PROJECT_ID") val ciJobToken: String? = System.getenv("CI_JOB_TOKEN") val ciPipelineId: String? = System.getenv("CI_PIPELINE_ID") if (ciProjectId == null || ciJobToken == null || ciPipelineId == null) { println("Failed to get project id, job token or pipeline id.") return@publishing } publications.create<MavenPublication>("library") { version = "${darkanVersion}-${ciPipelineId}" artifact("build/libs/world-server-${darkanVersion}-all.jar") } repositories.maven { name = "GitLab" url = uri("https://gitlab.com/api/v4/projects/${ciProjectId}/packages/maven") credentials(HttpHeaderCredentials::class) { name = "Job-Token" value = ciJobToken } authentication.create("header", HttpHeaderAuthentication::class) } }
rootProject.name = "world-server"
/* * OpenRS Cache Library * Copyright (c) 2011 Graham and `Discardedx2 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.kfricilone.vyre.asm.script; /** * Created by Kyle Fricilone on May 10, 2018. */ public enum CS2InstructionType { PUSH_CONSTANT_INT, PUSH_VAR, POP_VAR, PUSH_VARBIT, POP_VARBIT, PUSH_CONSTANT_STRING, BRANCH, BRANCH_NOT, BRANCH_EQUALS, BRANCH_LESS_THAN, BRANCH_GREATER_THAN, BRANCH_LESS_THAN_OR_EQUALS, BRANCH_GREATER_THAN_OR_EQUALS, PUSH_INT_LOCAL, POP_INT_LOCAL, PUSH_STRING_LOCAL, POP_STRING_LOCAL, JOIN_STRING, POP_INT_DISCARD, POP_STRING_DISCARD, GOSUB_WITH_PARAMS, DEFINE_ARRAY, PUSH_ARRAY_INT, POP_ARRAY_INT, SWITCH, PUSH_LONG_CONSTANT, POP_LONG_DISCARD, PUSH_LONG_LOCAL, POP_LONG_LOCAL, LONG_BRANCH_NOT, LONG_BRANCH_EQUALS, LONG_BRANCH_LESS_THAN, LONG_BRANCH_GREATER_THAN, LONG_BRANCH_LESS_THAN_OR_EQUALS, LONG_BRANCH_GREATER_THAN_OR_EQUALS, PUSH_ARRAY_INT_LEAVE_INDEX_ON_STACK, PUSH_ARRAY_INT_AND_INDEX, POP_ARRAY_INT_LEAVE_VALUE_ON_STACK, BRANCH_IF_TRUE, BRANCH_IF_FALSE, CC_CREATE, CC_DELETE, CC_DELETEALL, CC_INVALIDATE, IF_SENDTOFRONT, IF_SENDTOBACK, CC_SENDTOFRONT, CC_SENDTOBACK, IF_RESUME_PAUSEBUTTON, CC_RESUME_PAUSEBUTTON, BASEIDKIT, BASECOLOUR, BASEMATERIAL, SETGENDER, SETOBJ, CC_SETPOSITION, CC_SETSIZE, CC_SETHIDE, CC_SETASPECT, CC_SETNOCLICKTHROUGH, CC_SETSCROLLPOS, CC_SETCOLOUR, CC_SETFILL, CC_SETTRANS, CC_SETLINEWID, CC_SETGRAPHIC, CC_SET2DANGLE, CC_SETTILING, CC_SETMODEL, CC_SETMODELANGLE, CC_SETMODELANIM, CC_SETMODELORTHOG, CC_SETMODELTINT, CC_SETMODELLIGHTING, CC_RESETMODELLIGHTING, CC_SETTEXT, CC_SETTEXTFONT, CC_SETTEXTALIGN, CC_SETTEXTSHADOW, CC_SETTEXTANTIMACRO, CC_SETOUTLINE, CC_SETGRAPHICSHADOW, CC_SETVFLIP, CC_SETHFLIP, CC_SETSCROLLSIZE, CC_SETALPHA, CC_SETMODELZOOM, CC_SETLINEDIRECTION, CC_SETMODELORIGIN, CC_SETMAXLINES, CC_SETPARAM_INT, CC_SETPARAM_STRING, CC_SETRECOL, CC_SETRETEX, CC_SETFONTMONO, CC_SETPARAM, CC_SETCLICKMASK, CC_SETOBJECT, CC_SETNPCHEAD, CC_SETPLAYERHEAD_SELF, CC_SETNPCMODEL, CC_SETPLAYERMODEL, CC_SETOBJECT_NONUM, CC_SETLINKFRIEND, CC_SETLINKFRIENDCHAT, CC_SETLINKPLAYERGROUP, CC_SETLINKACTIVECLANCHANNEL, CC_RESETLINKPLAYER, CC_SETOBJECT_WEARCOL, CC_SETOBJECT_WEARCOL_NONUM, CC_SETPLAYERMODEL_SELF, CC_SETOBJECT_ALWAYSNUM, CC_SETOBJECT_WEARCOL_ALWAYSNUM, CC_SETOP, CC_SETDRAGGABLE, CC_SETDRAGRENDERBEHAVIOUR, CC_SETDRAGDEADZONE, CC_SETDRAGDEADTIME, CC_SETOPBASE, CC_SETTARGETVERB, CC_CLEAROPS, CC_SETTARGETCURSORS, CC_SETOPCURSOR, CC_SETPAUSETEXT, CC_SETTARGETOPCURSOR, CC_SETOPCHAR, CC_SETOPTCHAR, CC_SETOPKEY, CC_SETOPTKEY, CC_SETOPKEYRATE, CC_SETOPTKEYRATE, CC_SETOPKEYIGNOREHELD, CC_SETOPTKEYIGNOREHELD, CC_SETMOUSEOVERCURSOR, CC_SETONCLICK, CC_SETONHOLD, CC_SETONRELEASE, CC_SETONMOUSEOVER, CC_SETONMOUSELEAVE, CC_SETONDRAG, CC_SETONTARGETLEAVE, CC_SETONVARTRANSMIT, CC_SETONTIMER, CC_SETONOP, CC_SETONDRAGCOMPLETE, CC_SETONCLICKREPEAT, CC_SETONMOUSEREPEAT, CC_SETONINVTRANSMIT, CC_SETONSTATTRANSMIT, CC_SETONTARGETENTER, CC_SETONSCROLLWHEEL, CC_SETONCHATTRANSMIT, CC_SETONKEY, CC_SETONGAMEPADBUTTON, CC_SETONGAMEPADBUTTONHELD, CC_SETONGAMEPADAXIS, CC_SETONGAMEPADTRIGGER, CC_SETONFRIENDTRANSMIT, CC_SETONCLANTRANSMIT, CC_SETONMISCTRANSMIT, CC_SETONDIALOGABORT, CC_SETONSUBCHANGE, CC_SETONSTOCKTRANSMIT, CC_SETONCAMFINISHED, CC_SETONRESIZE, CC_SETONVARCTRANSMIT, CC_SETONVARCSTRTRANSMIT, CC_SETONOPT, CC_SETONCLANSETTINGSTRANSMIT, CC_SETONCLANCHANNELTRANSMIT, CC_SETONVARCLANTRANSMIT, CC_SETONPLAYERGROUPTRANSMIT, CC_SETONPLAYERGROUPVARPTRANSMIT, CC_SETONCAMERAUPDATETRANSMIT, CC_CLEARSCRIPTHOOKS, CC_CALLONRESIZE, IF_SETPOSITION, IF_SETSIZE, IF_SETHIDE, IF_SETASPECT, IF_SETNOCLICKTHROUGH, IF_SETSCROLLPOS, IF_SETCOLOUR, IF_SETFILL, IF_SETTRANS, IF_SETLINEWID, IF_SETGRAPHIC, IF_SET2DANGLE, IF_SETTILING, IF_SETMODEL, IF_SETMODELANGLE, IF_SETMODELANIM, IF_SETMODELORTHOG, IF_SETMODELTINT, IF_SETMODELLIGHTING, IF_RESETMODELLIGHTING, IF_SETTEXT, IF_SETTEXTFONT, IF_SETTEXTALIGN, IF_SETTEXTSHADOW, IF_SETTEXTANTIMACRO, IF_SETOUTLINE, IF_SETGRAPHICSHADOW, IF_SETVFLIP, IF_SETHFLIP, IF_SETSCROLLSIZE, IF_SETALPHA, IF_SETMODELZOOM, IF_SETLINEDIRECTION, IF_SETMODELORIGIN, IF_SETMAXLINES, IF_SETPARAM_INT, IF_SETPARAM_STRING, IF_SETRECOL, IF_SETRETEX, IF_SETFONTMONO, IF_SETCLICKMASK, IF_SETOBJECT, IF_SETNPCHEAD, IF_SETPLAYERHEAD_SELF, IF_SETNPCMODEL, IF_SETPLAYERMODEL, IF_SETOBJECT_NONUM, IF_SETLINKFRIEND, IF_SETLINKFRIENDCHAT, IF_SETLINKPLAYERGROUP, IF_SETLINKACTIVECLANCHANNEL, IF_RESETLINKPLAYER, IF_SETOBJECT_WEARCOL, IF_SETOBJECT_WEARCOL_NONUM, IF_SETPLAYERMODEL_SELF, IF_SETOBJECT_ALWAYSNUM, IF_SETOBJECT_WEARCOL_ALWAYSNUM, IF_SETOP, IF_SETDRAGGABLE, IF_SETDRAGRENDERBEHAVIOUR, IF_SETDRAGDEADZONE, IF_SETDRAGDEADTIME, IF_SETOPBASE, IF_SETTARGETVERB, IF_CLEAROPS, IF_SETTARGETCURSORS, IF_SETOPCURSOR, IF_SETPAUSETEXT, IF_SETTARGETOPCURSOR, IF_SETOPCHAR, IF_SETOPTCHAR, IF_SETOPKEY, IF_SETOPTKEY, IF_SETOPKEYRATE, IF_SETOPTKEYRATE, IF_SETOPKEYIGNOREHELD, IF_SETOPTKEYIGNOREHELD, IF_SETMOUSEOVERCURSOR, IF_SETONCLICK, IF_SETONHOLD, IF_SETONRELEASE, IF_SETONMOUSEOVER, IF_SETONMOUSELEAVE, IF_SETONDRAG, IF_SETONTARGETLEAVE, IF_SETONVARTRANSMIT, IF_SETONTIMER, IF_SETONOP, IF_SETONDRAGCOMPLETE, IF_SETONCLICKREPEAT, IF_SETONMOUSEREPEAT, IF_SETONINVTRANSMIT, IF_SETONSTATTRANSMIT, IF_SETONTARGETENTER, IF_SETONSCROLLWHEEL, IF_SETONCHATTRANSMIT, IF_SETONKEY, IF_SETONGAMEPADBUTTON, IF_SETONGAMEPADBUTTONHELD, IF_SETONGAMEPADAXIS, IF_SETONGAMEPADTRIGGER, IF_SETONFRIENDTRANSMIT, IF_SETONCLANTRANSMIT, IF_SETONMISCTRANSMIT, IF_SETONDIALOGABORT, IF_SETONSUBCHANGE, IF_SETONSTOCKTRANSMIT, IF_SETONCAMFINISHED, IF_SETONRESIZE, IF_SETONVARCTRANSMIT, IF_SETONVARCSTRTRANSMIT, IF_SETONOPT, IF_SETONCLANSETTINGSTRANSMIT, IF_SETONCLANCHANNELTRANSMIT, IF_SETONVARCLANTRANSMIT, IF_SETONPLAYERGROUPTRANSMIT, IF_SETONPLAYERGROUPVARPTRANSMIT, IF_SETONCAMERAUPDATETRANSMIT, IF_CLEARSCRIPTHOOKS, IF_CALLONRESIZE, IF_NPC_SETCUSTOMBODYMODEL, CC_NPC_SETCUSTOMBODYMODEL, IF_NPC_SETCUSTOMHEADMODEL, CC_NPC_SETCUSTOMHEADMODEL, IF_NPC_SETCUSTOMRECOL, CC_NPC_SETCUSTOMRECOL, IF_NPC_SETCUSTOMRETEX, CC_NPC_SETCUSTOMRETEX, MES, RETURN, IF_CLOSE, RESUME_COUNTDIALOG, RESUME_NAMEDIALOG, RESUME_STRINGDIALOG, ABORT_DIALOG, OPPLAYER, RESUME_OBJDIALOG, IF_DRAGPICKUP, CC_DRAGPICKUP, IF_OPENSUBCLIENT, IF_CLOSESUBCLIENT, OPPLAYERT, MES_TYPED, SETUP_MESSAGEBOX, RESUME_HSLDIALOG, RESUME_CLANFORUMQFCDIALOG, SOUND_SYNTH, SOUND_SONG, SOUND_JINGLE, SOUND_SYNTH_VOLUME, SOUND_SONG_VOLUME, SOUND_JINGLE_VOLUME, SOUND_VORBIS_VOLUME, SOUND_SPEECH_VOLUME, SOUND_SYNTH_RATE, SOUND_VORBIS_RATE, EMAIL_VALIDATION_SUBMIT_CODE, EMAIL_VALIDATION_CHANGE_ADDRESS, EMAIL_VALIDATION_ADD_NEW_ADDRESS, FRIEND_SETRANK, FRIEND_SETNOTES, FRIEND_ADD, FRIEND_DEL, IGNORE_ADD, IGNORE_DEL, IGNORE_SETNOTES, FC_KICKUSER, FC_JOINCHAT, FC_LEAVECHAT, IGNORE_ADD_TEMP, AFFINEDCLANSETTINGS_ADDBANNED_FROMCHANNEL, AFFINEDCLANSETTINGS_SETMUTED_FROMCHANNEL, ACTIVECLANCHANNEL_KICKUSER, OC_FINDRESTART, CHAT_SETFILTER, CHAT_SENDABUSEREPORT, CHAT_SETMODE, CHAT_SENDPUBLIC, CHAT_SENDPRIVATE, ACTIVECHATPHRASE_PREPARE, ACTIVECHATPHRASE_SEND, ACTIVECHATPHRASE_SENDPRIVATE, ACTIVECHATPHRASE_SETDYNAMICINT, ACTIVECHATPHRASE_SETDYNAMICOBJ, CHATPHRASE_FINDRESTART, WORLDMAP_3DVIEW_ENABLE, WORLDMAP_3DVIEW_DISABLE, WORLDMAP_3DVIEW_SETLODDISTANCE, WORLDMAP_SETCATEGORYPRIORITY, WORLDMAP_3DVIEW_SETTEXTFONT, WORLDMAP_DISABLETEXTSIZE, WORLDMAP_DISABLETYPE, WORLDMAP_3DVIEW_SETLIGHTING, WORLDMAP_SETZOOM, WORLDMAP_SETMAP, WORLDMAP_JUMPTOSOURCECOORD, WORLDMAP_JUMPTODISPLAYCOORD, WORLDMAP_SETMAP_COORD, WORLDMAP_FLASHELEMENT, WORLDMAP_SETMAP_COORD_OVERRIDE, WORLDMAP_DISABLEELEMENTS, WORLDMAP_FLASHELEMENTCATEGORY, WORLDMAP_DISABLEELEMENTCATEGORY, WORLDMAP_DISABLEELEMENT, WORLDMAP_CLOSEMAP, FULLSCREEN_EXIT, SETWINDOWMODE, SETDEFAULTWINDOWMODE, OPENURL, URLENCODE, SPLINE_NEW, SPLINE_ADDPOINT, QUIT, OPENURL_NOLOGIN, WRITECONSOLE, FORMATMINIMENU, DEFAULTMINIMENU, SETDEFAULTCURSORS, SETHARDCODEDOPCURSORS, DOCHEAT, NOTIFY_ACCOUNTCREATED, NOTIFY_ACCOUNTCREATESTARTED, SETSUBMENUMINLENGTH, OPENURL_SHIM, CAM_MOVETO, CAM_LOOKAT, CAM_MOVEALONG, CAM_RESET, CAM_FORCEANGLE, CAM_INC_X, CAM_DEC_X, CAM_INC_Y, CAM_DEC_Y, CAM_SETFOLLOWHEIGHT, CAM_FOLLOWCOORD, CAM_SMOOTHRESET, CAM_REMOVEROOF, CAM2_SETLOOKATMODE, CAM2_SETPOSITIONMODE, CAM2_SETLOOKATACCELERATION, CAM2_SETPOSITIONACCELERATION, CAM2_SETLOOKATMAXSPEED, CAM2_SETPOSITIONMAXSPEED, CAM2_SETDEPTHPLANES, CAM2_SETFIELDOFVIEW, CAM2_SETLOOKATPOINT_POINT, CAM2_SETPOSITIONPOINT_POINT, CAM2_GETPOSITIONPOINT_POINT, CAM2_SETLOOKATENTITY_PLAYER, CAM2_SETLOOKATENTITY_NPC, CAM2_SETPOSITIONENTITY_PLAYER, CAM2_SETPOSITIONENTITY_NPC, CAM2_SETFIELDOFVIEWSCREEN, CAM2_SETPOSITIONSPLINE_SPLINE, CAM2_SETLOOKATSPLINE_SPLINE, CAM2_REMOVEEFFECT, CAM2_REMOVEALLEFFECTS, CAM2_SETLOOKATACCELERATION_AXIS, CAM2_SETPOSITIONACCELERATION_AXIS, CAM2_SETLOOKATMAXSPEED_AXIS, CAM2_SETPOSITIONMAXSPEED_AXIS, CAM2_SETCOLLISIONMODE, CAM2_SETPOSITIONPOINTCOLLISION, CAM2_UPDATEEFFECT_ZTILT, CAM2_SETTRAILDISTANCE, CAM2_SETLINEARMOVEMENTMODE, CAM2_SETSPRINGPROPERTIES, CAM2_SETLOOKATANGULARINTERPOLATION, CAM2_SETPOSITIONANGULARINTERPOLATION, CAM2_SETLOOKATSPRINGPROPERTIES, CAM2_SETPOSITIONSPRINGPROPERTIES, CAM2_ENABLE, CAM2_SETSNAPDISTANCES, CAM2_RESETSNAPDISTANCES, LOGIN_REQUEST, CAM2_SETLOOKATORIENTATION_VECTOR, CAM2_SETLOOKATORIENTATION_XROTATION, CAM2_SETLOOKATORIENTATION_YROTATION, CAM2_SETLOOKATORIENTATION_XMOVEMENT, CAM2_SETLOOKATORIENTATION_ZMOVEMENT, CAM2_SETLOOKATORIENTATION_MAXDISTANCECLAMPING, LOGIN_CONTINUE, LOGIN_RESETREPLY, RESEND_UID_PASSPORT_REQUEST, CREATE_AVAILABLEREQUEST, CREATE_NAME_AVAILABLEREQUEST, CREATE_SUGGEST_NAME_REQUEST, CREATE_CREATEREQUEST, CREATE_CONNECTREQUEST, CREATE_STEP_REACHED, LOBBY_ENTERGAME, LOBBY_ENTERLOBBY, LOBBY_LEAVELOBBY, CREATE_SETUNDER13, LOGIN_CANCEL, LOGIN_REQUEST_SOCIAL_NETWORK, LOBBY_ENTERLOBBY_SOCIAL_NETWORK, DETAIL_BRIGHTNESS, DETAIL_REMOVEROOFS_OPTION, DETAIL_GROUNDDECOR_ON, DETAIL_IDLEANIMS_MANY, DETAIL_FLICKERING_ON, DETAIL_SPOTSHADOWS_ON, DETAIL_HARDSHADOWS, DETAIL_SHADOWQUALITY, DETAIL_LIGHTDETAIL_HIGH, DETAIL_WATERDETAIL_HIGH, DETAIL_FOG_ON, DETAIL_ANTIALIASING, DETAIL_ANTIALIASING_QUALITY, DETAIL_STEREO, DETAIL_SOUNDVOL, DETAIL_MUSICVOL, DETAIL_BGSOUNDVOL, DETAIL_REMOVEROOFS_OPTION_OVERRIDE, DETAIL_PARTICLES, DETAIL_ANTIALIASING_DEFAULT, DETAIL_BUILDAREA, DETAIL_BLOOM, DETAIL_CUSTOMCURSORS, DETAIL_IDLEANIMS, DETAIL_GROUNDBLENDING, DETAIL_TOOLKIT, DETAIL_TOOLKIT_DEFAULT, DETAIL_CPUUSAGE, DETAIL_TEXTURING, DETAIL_MAXSCREENSIZE, DETAIL_SPEECHVOL, DETAIL_LOGINVOL, DETAIL_LOADINGSCREENTYPE, DETAIL_DRAWDISTANCE, DETAIL_SKYDETAIL, DETAIL_ANIMDETAIL, DETAIL_DISKCACHESIZE, VIEWPORT_SETFOV, VIEWPORT_SETZOOM, VIEWPORT_CLAMPFOV, WORLDLIST_SORT, WORLDLIST_AUTOWORLD, WORLDLIST_PINGWORLDS, IF_DEBUG_BUTTON1, IF_DEBUG_BUTTON2, IF_DEBUG_BUTTON3, IF_DEBUG_BUTTON4, IF_DEBUG_BUTTON5, IF_DEBUG_BUTTON6, IF_DEBUG_BUTTON7, IF_DEBUG_BUTTON8, IF_DEBUG_BUTTON9, IF_DEBUG_BUTTON10, IF_DEBUG_TARGET, IF_TRIGGEROP, CC_TRIGGEROP, FORCE_INTERFACE_DRAG, CANCEL_INTERFACE_DRAG, TARGETMODE_ACTIVE, TARGETMODE_CANCEL, AUTOSETUP_SETHIGH, AUTOSETUP_SETMEDIUM, AUTOSETUP_SETLOW, AUTOSETUP_SETMIN, AUTOSETUP_SETCUSTOM, AUTOSETUP_BLACKFLAGLAST, VIDEO_ADVERT_FORCE_REMOVE, VIDEO_ADVERT_ALLOW_SKIP, BUG_REPORT, ARRAY_SORT, CC_FIND, IF_FIND, CC_GETX, CC_GETY, CC_GETWIDTH, CC_GETHEIGHT, CC_GETHIDE, CC_GETLAYER, CC_GETPARENTLAYER, CC_GETCOLOUR, CC_GETSCROLLX, CC_GETSCROLLY, CC_GETTEXT, CC_GETSCROLLWIDTH, CC_GETSCROLLHEIGHT, CC_GETMODELZOOM, CC_GETMODELANGLE_X, CC_GETMODELANGLE_Z, CC_GETMODELANGLE_Y, CC_GETTRANS, CC_GETMODELXOF, CC_GETMODELYOF, CC_GETGRAPHIC, CC_PARAM, CC_GET2DANGLE, CC_GETMODEL, CC_GETFONTGRAPHIC, CC_GETGRAPHICDIMENSIONS, CC_GETFONTMETRICS, CC_GETINVOBJECT, CC_GETINVCOUNT, CC_GETID, CC_GETTARGETMASK, CC_GETOP, CC_GETOPBASE, CC_GETCHARINDEXATPOS, CC_GETCHARPOSATINDEX, IF_GETX, IF_GETY, IF_GETWIDTH, IF_GETHEIGHT, IF_GETHIDE, IF_GETLAYER, IF_GETPARENTLAYER, IF_GETCOLOUR, IF_GETSCROLLX, IF_GETSCROLLY, IF_GETTEXT, IF_GETSCROLLWIDTH, IF_GETSCROLLHEIGHT, IF_GETMODELZOOM, IF_GETMODELANGLE_X, IF_GETMODELANGLE_Z, IF_GETMODELANGLE_Y, IF_GETTRANS, IF_GETMODELXOF, IF_GETMODELYOF, IF_GETGRAPHIC, IF_GET2DANGLE, IF_GETMODEL, IF_GETFONTGRAPHIC, IF_GETGRAPHICDIMENSIONS, IF_GETFONTMETRICS, IF_GETINVOBJECT, IF_GETINVCOUNT, IF_HASSUB, IF_GETNEXTSUBID, IF_HASSUBMODAL, IF_HASSUBOVERLAY, IF_GETTARGETMASK, IF_GETOP, IF_GETOPBASE, IF_GETCHARINDEXATPOS, IF_GETCHARPOSATINDEX, CLIENTCLOCK, INV_GETOBJ, INV_GETNUM, INV_TOTAL, INV_TOTALCAT, INV_SIZE, INV_STOCKBASE, INV_GETVAR, STAT, STAT_BASE, STAT_VISIBLE_XP, STAT_BASE_ACTUAL, STAT_VISIBLE_XP_ACTUAL, FACING_FINE, COORD, COORDX, COORDY, COORDZ, COORD_FINE, COORDX_FINE, COORDY_FINE, COORDZ_FINE, COORDLEVEL_FINE, MOVECOORD_FINE, COORD_GRIDTOFINE, COORD_FINETOGRID, MAP_MEMBERS, MAP_PRELOAD, MAP_LOADEDPERCENT, INVOTHER_GETOBJ, INVOTHER_GETNUM, INVOTHER_TOTAL, INVOTHER_GETVAR, STAFFMODLEVEL, REBOOTTIMER, MAP_WORLD, RUNENERGY_VISIBLE, RUNWEIGHT_VISIBLE, PLAYERMOD, PLAYERMODLEVEL, PLAYERMEMBER, COMLEVEL_ACTIVE, GENDER, MAP_QUICKCHAT, INV_FREESPACE, INV_TOTALPARAM, INV_TOTALPARAM_STACK, MAP_LANG, MOVECOORD, AFFILIATE, PROFILE_CPU, PLAYERDEMO, APPLET_HASFOCUS, FROMBILLING, GET_MOUSEX, GET_MOUSEY, GET_ACTIVE_MINIMENU_ENTRY, GET_SECOND_MINIMENU_ENTRY, GET_MINIMENU_LENGTH, NPC_FIND_ACTIVE_MINIMENU_ENTRY, PLAYER_FIND_ACTIVE_MINIMENU_ENTRY, GET_CURRENTCURSOR, GET_SELFYANGLE, MAP_ISOWNER, GET_MOUSEBUTTONS, SELF_PLAYER_UID, GET_MINIMENU_TARGET, ENUM_STRING, ENUM, ENUM_HASOUTPUT, ENUM_HASOUTPUT_STRING, ENUM_GETOUTPUTCOUNT, ENUM_GETREVERSECOUNT, ENUM_GETREVERSECOUNT_STRING, ENUM_GETREVERSEINDEX, ENUM_GETREVERSEINDEX_STRING, FRIEND_COUNT, FRIEND_GETNAME, FRIEND_GETWORLD, FRIEND_GETRANK, FRIEND_GETNOTES, FRIEND_GETWORLDFLAGS, FRIEND_TEST, FRIEND_GETWORLDNAME, FC_GETCHATDISPLAYNAME, FC_GETCHATCOUNT, FC_GETCHATUSERNAME, FC_GETCHATUSERWORLD, FC_GETCHATUSERRANK, FC_GETCHATMINKICK, FC_GETCHATRANK, IGNORE_COUNT, IGNORE_GETNAME, IGNORE_GETNOTES, IGNORE_TEST, FC_ISSELF, FC_GETCHATOWNERNAME, FC_GETCHATUSERWORLDNAME, FRIEND_PLATFORM, FRIEND_GETSLOTFROMNAME, IGNORE_GETSLOTFROMNAME, PLAYERCOUNTRY, IGNORE_IS_TEMP, FC_GETCHATUSERNAME_UNFILTERED, IGNORE_GETNAME_UNFILTERED, FRIEND_IS_REFERRER, FRIEND_IS_REFERRED, ACTIVECLANSETTINGS_FIND_LISTENED, ACTIVECLANSETTINGS_FIND_AFFINED, ACTIVECLANSETTINGS_GETCLANNAME, ACTIVECLANSETTINGS_GETALLOWUNAFFINED, ACTIVECLANSETTINGS_GETRANKTALK, ACTIVECLANSETTINGS_GETRANKKICK, ACTIVECLANSETTINGS_GETRANKLOOTSHARE, ACTIVECLANSETTINGS_GETCOINSHARE, ACTIVECLANSETTINGS_GETAFFINEDCOUNT, ACTIVECLANSETTINGS_GETAFFINEDDISPLAYNAME, ACTIVECLANSETTINGS_GETAFFINEDRANK, ACTIVECLANSETTINGS_GETAFFINEDMUTED, ACTIVECLANSETTINGS_GETBANNEDCOUNT, ACTIVECLANSETTINGS_GETBANNEDDISPLAYNAME, ACTIVECLANSETTINGS_GETAFFINEDEXTRAINFO, ACTIVECLANSETTINGS_GETCURRENTOWNER_SLOT, ACTIVECLANSETTINGS_GETREPLACEMENTOWNER_SLOT, ACTIVECLANSETTINGS_GETAFFINEDSLOT, ACTIVECLANSETTINGS_GETSORTEDAFFINEDSLOT, ACTIVECLANSETTINGS_GETAFFINEDJOINRUNEDAY, ACTIVECLANCHANNEL_FIND_LISTENED, ACTIVECLANCHANNEL_FIND_AFFINED, ACTIVECLANCHANNEL_GETCLANNAME, ACTIVECLANCHANNEL_GETRANKKICK, ACTIVECLANCHANNEL_GETRANKTALK, ACTIVECLANCHANNEL_GETUSERCOUNT, ACTIVECLANCHANNEL_GETUSERDISPLAYNAME, ACTIVECLANCHANNEL_GETUSERRANK, ACTIVECLANCHANNEL_GETUSERWORLD, ACTIVECLANCHANNEL_GETUSERSLOT, ACTIVECLANCHANNEL_GETSORTEDUSERSLOT, CLANPROFILE_FIND, STOCKMARKET_GETOFFERTYPE, STOCKMARKET_GETOFFERITEM, STOCKMARKET_GETOFFERPRICE, STOCKMARKET_GETOFFERCOUNT, STOCKMARKET_GETOFFERCOMPLETEDCOUNT, STOCKMARKET_GETOFFERCOMPLETEDGOLD, STOCKMARKET_ISOFFEREMPTY, STOCKMARKET_ISOFFERSTABLE, STOCKMARKET_ISOFFERFINISHED, STOCKMARKET_ISOFFERADDING, ADD, SUB, MULTIPLY, DIVIDE, RANDOM, RANDOMINC, INTERPOLATE, ADDPERCENT, SETBIT, CLEARBIT, TESTBIT, MODULO, POW, INVPOW, AND, OR, MIN, MAX, SCALE, RANDOM_SOUND_PITCH, HSVTORGB, NOT, APPEND_NUM, APPEND, APPEND_SIGNNUM, GET_COL_TAG, LOWERCASE, FROMDATE, TEXT_GENDER, TOSTRING, COMPARE, PARAHEIGHT, PARAWIDTH, PARALINE, TEXT_SWITCH, ESCAPE, APPEND_CHAR, CHAR_ISPRINTABLE, CHAR_ISALPHANUMERIC, CHAR_ISALPHA, CHAR_ISNUMERIC, STRING_LENGTH, SUBSTRING, REMOVETAGS, STRING_INDEXOF_CHAR, STRING_INDEXOF_STRING, CHAR_TOLOWERCASE, CHAR_TOUPPERCASE, TOSTRING_LOCALISED, STRINGWIDTH, STRING_DISTANCE, FORMAT_DATETIME_FROM_MINUTES, CLANFORUMQFC_TOSTRING, OC_NAME, OC_OP, OC_IOP, OC_COST, OC_STACKABLE, OC_CATEGORY, OC_HASVAROBJ, OC_CERT, OC_UNCERT, OC_SHARD, OC_UNSHARD, OC_SHARDCOUNT, OC_WEARPOS, OC_WEARPOS2, OC_WEARPOS3, OC_MEMBERS, OC_PARAM, OC_ICURSOR, OC_MULTISTACKSIZE, OC_FIND, OC_FINDNEXT, OC_MINIMENU_COLOUR_OVERRIDDEN, OC_MINIMENU_COLOUR, NPC_PARAM, OBJECT_PARAM, STRUCT_PARAM, SEQ_PARAM, SEQLENGTH, BAS_GETANIM_READY, CHAT_GETFILTER_PUBLIC, CHAT_GETHISTORY_BYTYPEANDLINE, CHAT_GETHISTORY_BYUID, CHAT_GETFILTER_PRIVATE, CHAT_PLAYERNAME, CHAT_GETFILTER_TRADE, CHAT_GETHISTORYLENGTH, CHAT_GETNEXTUID, CHAT_GETPREVUID, CHAT_PLAYERNAME_UNFILTERED, CHATCAT_GETDESC, CHATCAT_GETSUBCATCOUNT, CHATCAT_GETSUBCAT, CHATCAT_GETPHRASECOUNT, CHATCAT_GETPHRASE, CHATPHRASE_GETTEXT, CHATPHRASE_GETAUTORESPONSECOUNT, CHATPHRASE_GETAUTORESPONSE, CHATCAT_GETSUBCATSHORTCUT, CHATCAT_GETPHRASESHORTCUT, CHATCAT_FINDSUBCATBYSHORTCUT, CHATCAT_FINDPHRASEBYSHORTCUT, CHATPHRASE_GETDYNAMICCOMMANDCOUNT, CHATPHRASE_GETDYNAMICCOMMAND, CHATPHRASE_GETDYNAMICCOMMANDPARAM_ENUM, CHATPHRASE_FIND, CHATPHRASE_FINDNEXT, KEYHELD_ALT, KEYHELD_CTRL, KEYHELD_SHIFT, WORLDMAP_3DVIEW_ACTIVE, WORLDMAP_3DVIEW_GETCOORDFINE, WORLDMAP_3DVIEW_GETLODDISTANCE, WORLDMAP_GETCATEGORYPRIORITY, WORLDMAP_3DVIEW_GETTEXTFONT, WORLDMAP_3DVIEW_GETSCREENPOSITION, WORLDMAP_GETDISABLETEXTSIZE, WORLDMAP_GETDISABLETYPE, WORLDMAP_GETZOOM, WORLDMAP_GETMAP, WORLDMAP_GETMAPNAME, WORLDMAP_GETSIZE, WORLDMAP_GETDISPLAYPOSITION, WORLDMAP_GETCONFIGORIGIN, WORLDMAP_GETCONFIGSIZE, WORLDMAP_GETCONFIGBOUNDS, WORLDMAP_LISTELEMENT_START, WORLDMAP_LISTELEMENT_NEXT, WORLDMAP_COORDINMAP, WORLDMAP_GETCONFIGZOOM, WORLDMAP_ISLOADED, WORLDMAP_GETSOURCEPOSITION, WORLDMAP_GETDISPLAYCOORD, WORLDMAP_GETSOURCECOORD, WORLDMAP_GETDISABLEELEMENTS, WORLDMAP_GETDISABLEELEMENTCATEGORY, WORLDMAP_GETDISABLEELEMENT, WORLDMAP_GETCURRENTMAP, WORLDMAP_FINDNEARESTELEMENT, FULLSCREEN_ENTER, FULLSCREEN_MODECOUNT, FULLSCREEN_GETMODE, FULLSCREEN_LASTMODE, GETWINDOWMODE, GETDEFAULTWINDOWMODE, SPLINE_LENGTH, LASTLOGIN, MINIMENUOPEN, GETCLIPBOARD, HAS_HTML5, HAS_NXT, CLIENTTYPE, IS_GAMESCREEN_STATE, CAM_GETANGLE_XA, CAM_GETANGLE_YA, CAM_GETFOLLOWHEIGHT, CAM2_GETCONTROLMODE, CAM2_GETLOOKATMODE, CAM2_GETPOSITIONMODE, CAM2_GETPOSITIONENTITY_ANGLEOFFSETS, CAM2_ADDEFFECT_SHAKE, CAM2_GETPOSITIONENTITY_LOOKATANGLEOFFSETS, CAM2_GETPOSITIONENTITY_LOOKATANGLE, CAM2_GETPOSITIONENTITY_LOOKATDISTANCE, CAM2_ADDEFFECT_ZTILT, CAM2_ISENABLED, CAM2_LEGACYCAM_READY, CAM_MODEISFOLLOWPLAYER, LOGIN_REPLY, LOGIN_HOPTIME, LOGIN_BAN_DURATION, CREATE_REPLY, CREATE_EMAIL_VALIDATE_REPLY, CREATE_NAME_VALIDATE_REPLY, CREATE_SUGGEST_NAME_REPLY, CREATE_CONNECT_REPLY, LOGIN_DISALLOWRESULT, LOBBY_ENTERGAMEREPLY, LOBBY_ENTERLOBBYREPLY, USERFLOWFLAGS, AUTOMATEDTESTFLAGS, CREATE_UNDER13, LOGIN_LAST_TRANSFER_REPLY, LOGIN_INPROGRESS, LOGIN_QUEUE_POSITION, LOGIN_DISALLOWTRIGGER, CREATE_GET_EMAIL, LOGIN_ACCOUNTAPPEAL, DETAILGET_BRIGHTNESS, DETAILGET_REMOVEROOFS_OPTION, DETAILGET_GROUNDDECOR_ON, DETAILGET_IDLEANIMS_MANY, DETAILGET_FLICKERING_ON, DETAILGET_SPOTSHADOWS_ON, DETAILGET_HARDSHADOWS, DETAILGET_SHADOWQUALITY, DETAILGET_LIGHTDETAIL_HIGH, DETAILGET_WATERDETAIL_HIGH, DETAILGET_FOG_ON, DETAILGET_ANTIALIASING, DETAILGET_ANTIALIASING_QUALITY, DETAILGET_STEREO, DETAILGET_SOUNDVOL, DETAILGET_MUSICVOL, DETAILGET_BGSOUNDVOL, DETAILGET_PARTICLES, DETAILGET_ANTIALIASING_DEFAULT, DETAILGET_BUILDAREA, DETAILGET_BLOOM, DETAILGET_CUSTOMCURSORS, DETAILGET_IDLEANIMS, DETAILGET_GROUNDBLENDING, DETAILGET_TOOLKIT, DETAILGET_TOOLKIT_DEFAULT, DETAILGET_CPUUSAGE, DETAILGET_TEXTURING, DETAILGET_PERFORMANCE_METRIC, DETAILGET_MAXSCREENSIZE, DETAILGET_SPEECHVOL, DETAILGET_LOGINVOL, DETAILGET_SAFEMODE, DETAILGET_LOADINGSCREENTYPE, DETAILGET_ORTHOGRAPHIC, DETAILGET_CANCHOOSESAFEMODE, DETAILGET_CHOSESAFEMODE, DETAILGET_SKYDETAIL, DETAILGET_DRAWDISTANCE, DETAILGET_MAXDISKCACHESIZE, DETAILGET_MINDISKCACHESIZE, DETAILGET_RECOMMENDEDDISKCACHESIZE, DETAILGET_DISKCACHESIZE, DETAILGET_ANIMDETAIL, VIEWPORT_GETEFFECTIVESIZE, VIEWPORT_GETZOOM, VIEWPORT_GETFOV, DATE_MINUTES, DATE_RUNEDAY, DATE_RUNEDAY_FROMDATE, DATE_YEAR, DATE_ISLEAPYEAR, DATE_RUNEDAY_TODATE, DATE_MINUTES_FROMRUNEDAY, WORLDLIST_FETCH, WORLDLIST_START, WORLDLIST_NEXT, WORLDLIST_SWITCH, WORLDLIST_SPECIFIC, WORLDLIST_SPECIFIC_THISWORLD, IF_GETTOP, IF_DEBUG_GETOPENIFCOUNT, IF_DEBUG_GETOPENIFID, IF_DEBUG_GETNAME, IF_DEBUG_GETCOMCOUNT, IF_DEBUG_GETCOMNAME, IF_DEBUG_GETSERVERTRIGGERS, OPCOUNT, MEC_TEXT, MEC_SPRITE, MEC_TEXTSIZE, MEC_CATEGORY, MEC_PARAM, USERDETAIL_QUICKCHAT, USERDETAIL_LOBBY_MEMBERSHIP, USERDETAIL_LOBBY_RECOVERYDAY, USERDETAIL_LOBBY_UNREADMESSAGES, USERDETAIL_LOBBY_LASTLOGINDAY, USERDETAIL_LOBBY_LASTLOGINADDRESS, USERDETAIL_LOBBY_EMAILSTATUS, USERDETAIL_LOBBY_CCEXPIRY, USERDETAIL_LOBBY_GRACEEXPIRY, USERDETAIL_LOBBY_DOBREQUESTED, USERDETAIL_DOB, USERDETAIL_LOBBY_MEMBERSSTATS, USERDETAIL_LOBBY_PLAYAGE, USERDETAIL_LOBBY_JCOINS_BALANCE, USERDETAIL_LOBBY_LOYALTY_BALANCE, AUTOSETUP_DOSETUP, AUTOSETUP_GETLEVEL, VIDEO_ADVERT_PLAY, VIDEO_ADVERT_HAS_FINISHED, GET_ENTITY_SAY, GET_DISPLAYNAME_WITHEXTRAS, GET_NPC_NAME, GET_NPC_VISLEVEL, GET_ENTITY_SCREEN_POSITION, IF_GET_GAMESCREEN, IF_SET_GAMESCREEN_ENABLED, GET_ENTITY_OVERLAY_HEIGHT, GET_NPC_STAT, IS_NPC_ACTIVE, IS_NPC_VISIBLE, IS_TARGETED_ENTITY, NPC_TYPE, GET_LOC_SCREEN_POSITION, GET_OBJ_SCREEN_POSITION, GET_LOC_OVERLAY_HEIGHT, GET_OBJ_OVERLAY_HEIGHT, GET_LOC_BOUNDING_BOX, GET_OBJ_BOUNDING_BOX, GET_ENTITY_BOUNDING_BOX, QUEST_GETNAME, QUEST_GETSORTNAME, QUEST_TYPE, QUEST_GETDIFFICULTY, QUEST_GETMEMBERS, QUEST_POINTS, QUEST_QUESTREQ_COUNT, QUEST_QUESTREQ, QUEST_QUESTREQ_MET, QUEST_POINTSREQ, QUEST_POINTSREQ_MET, QUEST_STATREQ_COUNT, QUEST_STATREQ_STAT, QUEST_STATREQ_LEVEL, QUEST_STATREQ_MET, QUEST_VARPREQ_COUNT, QUEST_VARPREQ_DESC, QUEST_VARPREQ_MET, QUEST_VARBITREQ_COUNT, QUEST_VARBITREQ_DESC, QUEST_VARBITREQ_MET, QUEST_ALLREQMET, QUEST_STARTED, QUEST_FINISHED, QUEST_PARAM, MAP_BUILD_COMPLETE, SOUND_SONG_STOP, SOUND_GROUP_START, SOUND_GROUP_STOP, SOUND_VORBIS_VOLUME_RATE_GROUP, SOUND_MIXBUSS_ADD, SOUND_MIXBUSS_SETLEVEL, SOUND_DISTANCEFOCUSFILTER_SETPARAMS, PRELOAD_PERCENT, SHADER_PRELOAD_ALLOW, SHADER_PRELOAD_PERCENT, SHADER_PRELOAD_THROTTLE, CAN_RUN_JAVA_CLIENT, FPS_STATS, RUNJAVASCRIPT, WORLDMAP_JUMPTOSOURCECOORD_INSTANT, WORLDMAP_JUMPTODISPLAYCOORD_INSTANT, WORLDMAP_SETFLASHLOOPS, WORLDMAP_SETFLASHLOOPS_DEFAULT, WORLDMAP_SETFLASHTICS, WORLDMAP_SETFLASHTICS_DEFAULT, WORLDMAP_PERPETUALFLASH, WORLDMAP_STOPCURRENTFLASHES, PLAYER_GROUP_FIND, PLAYER_GROUP_MEMBER_COUNT, PLAYER_GROUP_MEMBER_GET_SAME_WORLD_VAR, PLAYER_GROUP_MEMBER_GET_RANK, PLAYER_GROUP_MEMBER_GET_TEAM, PLAYER_GROUP_MEMBER_GET_LAST_SEEN_NODE_ID, PLAYER_GROUP_MEMBER_GET_STATUS, PLAYER_GROUP_MEMBER_IS_ONLINE, PLAYER_GROUP_MEMBER_IS_MEMBER, PLAYER_GROUP_MEMBER_GET_DISPLAYNAME, PLAYER_GROUP_MEMBER_GET_JOIN_XP, PLAYER_GROUP_MEMBER_IS_OWNER, PLAYER_GROUP_BANNED_COUNT, PLAYER_GROUP_BANNED_GET_DISPLAYNAME, PLAYER_GROUP_GET_DISPLAYNAME, PLAYER_GROUP_GET_MAX_SIZE, PLAYER_GROUP_GET_CREATE_MINS_SINCE_EPOCH, PLAYER_GROUP_GET_CREATE_SECONDS_TO_NOW, PLAYER_GROUP_IS_MEMBERS_ONLY, PLAYER_GROUP_GET_OVERALL_STATUS, PLAYER_GROUP_GET_OWNER_SLOT, TTV_LOGIN, TTV_LOGIN_GETSTATE, TTV_LOGOUT, TTV_LIBRARY_GETSTATE, TTV_LIBRARY_REQUEST, TTV_STREAM_GETSTATE, TTV_STREAM_START, TTV_STREAM_STOP, TTV_STREAM_SETTITLE, TTV_STREAM_GETVIEWERS, TTV_STREAM_GETQUALITY, TTV_STREAM_SETSMOOTHRESIZE, TTV_CHAT_GETSTATE, TTV_CHAT_SENDMESSAGE, TTV_WEBCAM_GETSTATE, TTV_WEBCAM_SUPPORTED, TTV_WEBCAM_GETDEVICE_COUNT, TTV_WEBCAM_GETDEVICE_BYINDEX, TTV_WEBCAM_GETDEVICE_BYUNIQUENAME, TTV_WEBCAM_GETCAP_COUNT, TTV_WEBCAM_GETCAP_BYINDEX, TTV_WEBCAM_GETCAP_BYUNIQUEID, TTV_WEBCAM_START, TTV_WEBCAM_STOP, TTV_WEBCAM_FLIP, TTV_LIVESTREAMS_UPDATE, TTV_LIVESTREAMS_GETSTREAM_START, TTV_LIVESTREAMS_GETSTREAM_NEXT, TTV_SETDEBUGOUPUT, TTV_HASPREREQUISITES, OS_ISMAC, OS_ISWINDOWS, OS_ISLINUX, OS_PHYSICALMEMORYSIZE, GETGRIDCOORDRELATIVETOCAMERA, MOVESCRIPTED, TELEMETRY_GET_GROUP_COUNT, TELEMETRY_GET_GROUP_INDEX, TELEMETRY_GET_GROUP_ID, TELEMETRY_GET_ROW_COUNT, TELEMETRY_GET_ROW_INDEX, TELEMETRY_GET_ROW_ID, TELEMETRY_IS_ROW_PINNED, TELEMETRY_GET_COLUMN_COUNT, TELEMETRY_GET_COLUMN_INDEX, TELEMETRY_GET_COLUMN_ID, TELEMETRY_GET_GRID_VALUE, TELEMETRY_IS_GRID_PROCESSOR_SET, EMOJI_ADD, EMOJI_REMOVE, EMOJI_REMOVEALL, EMOJI_SUBSTITUTE, EMOJI_ENABLE_AUTO_CHATLINE, DB_FIND, DB_FIND_WITH_COUNT, DB_FINDNEXT, DB_GETFIELD, DB_GETFIELDCOUNT, DETAILCANMOD_GROUNDDECOR, DETAILCANMOD_SPOTSHADOWS, DETAILCANMOD_HARDSHADOWS, DETAILCANMOD_SHADOWQUALITY, DETAILCANMOD_WATERDETAIL, DETAILCANMOD_ANTIALIASING, DETAILCANMOD_ANTIALIASING_QUALITY, DETAILCANMOD_PARTICLES, DETAILCANMOD_BUILDAREA, DETAILCANMOD_BLOOM, DETAILCANMOD_GROUNDBLENDING, DETAILCANMOD_TEXTURING, DETAILCANMOD_MAXSCREENSIZE, DETAILCANMOD_FOG, DETAILCANMOD_ORTHOGRAPHIC, DETAILCANMOD_TOOLKIT_DEFAULT, DETAILCANMOD_SKYDETAIL, DETAILCANMOD_ANIMDETAIL, DETAILCANSET_GROUNDDECOR, DETAILCANSET_SPOTSHADOWS, DETAILCANSET_HARDSHADOWS, DETAILCANSET_SHADOWQUALITY, DETAILCANSET_WATERDETAIL, DETAILCANSET_ANTIALIASING, DETAILCANSET_ANTIALIASING_QUALITY, DETAILCANSET_PARTICLES, DETAILCANSET_BUILDAREA, DETAILCANSET_BLOOM, DETAILCANSET_GROUNDBLENDING, DETAILCANSET_TEXTURING, DETAILCANSET_MAXSCREENSIZE, DETAILCANSET_FOG, DETAILCANSET_ORTHOGRAPHIC, DETAILCANSET_TOOLKIT_DEFAULT, DETAILCANSET_SKYDETAIL, DETAILCANSET_ANIMDETAIL, DETAIL_SHADOWS, DETAIL_LIGHTINGQUALITY, DETAIL_ANTIALIASINGMODE, DETAIL_AMBIENTOCCLUSION, DETAIL_REFLECTIONS, DETAIL_VSYNC, DETAILGET_SHADOWS, DETAILGET_LIGHTINGQUALITY, DETAILGET_ANTIALIASINGMODE, DETAILGET_AMBIENTOCCLUSION, DETAILGET_REFLECTIONS, DETAILGET_VSYNC, DETAILCANMOD_SHADOWS, DETAILCANMOD_LIGHTINGQUALITY, DETAILCANMOD_ANTIALIASINGMODE, DETAILCANMOD_AMBIENTOCCLUSION, DETAILCANMOD_REFLECTIONS, DETAILCANMOD_VSYNC, DETAILCANSET_SHADOWS, DETAILCANSET_LIGHTINGQUALITY, DETAILCANSET_ANTIALIASINGMODE, DETAILCANSET_AMBIENTOCCLUSION, DETAILCANSET_REFLECTIONS, DETAILCANSET_VSYNC, AUTOSETUP_SETULTRA; public String getFunction() { return "_" + name().toLowerCase(); } }
onNpcClick("Man", options = arrayOf("Talk-to")) { e -> e.player.startConversation { npc(e.npc.id, HAPPY_TALKING, "Hello there, adventurer! What brings you to our town?") options { //Conditional options example if (e.player.inventory.containsItem(1050, 1)) option("Ask about the town") { npc(e.npc.id, HAPPY_TALKING, "This town is known for its ancient history and beautiful landscapes.") player(HAPPY_TALKING, "That sounds fascinating!") npc(e.npc.id, HAPPY_TALKING, "Feel free to explore and enjoy your stay!") } option("Ask about quests") { npc(e.npc.id, HAPPY_TALKING, "Oh, there are many adventures to be had here!") player(HAPPY_TALKING, "Any specific recommendations?") npc(e.npc.id, HAPPY_TALKING, "You should visit the old wizard on the hill for a magical quest.") } option("Say goodbye") { player(HAPPY_TALKING, "Thanks for your time. I must be going now.") npc(e.npc.id, HAPPY_TALKING, "Safe travels, adventurer!") } } } }
val messages = arrayOf( Pair(HAPPY_TALKING, "I'm fine!"), Pair(CALM_TALK, "I think we need a new king. The one we've got isn't good."), Pair(CALM_TALK, "Not too bad. But I'm quite worried about the goblin population these days."), Pair(CONFUSED, "Who are you?.."), Pair(HAPPY_TALKING, "Hello."), Pair(NERVOUS, "I've heard there are many fearsome creatures that dwell underground..."), Pair(WORRIED, "I'm a little worried. I've heard there are people killing citizens at random.") ) onNpcClick("Man", "Woman", options = arrayOf("Talk-to")) { e -> val (chathead, text) = messages.random() e.player.startConversation { player(HAPPY_TALKING, "Hello, how's it going?") npc(e.npc.id, chathead, text) } }
package com.rs; public final class Launcher { public static void main(String[] args) throws Exception { Logger.setupFormat(); Logger.setLevel(Level.FINE); //FINER for traces JsonFileManager.setGSON(new GsonBuilder() .registerTypeAdapter(Controller.class, new ControllerAdapter()) .registerTypeAdapter(Date.class, new DateAdapter()) .registerTypeAdapter(PacketEncoder.class, new PacketEncoderAdapter()) .registerTypeAdapter(Packet.class, new PacketAdapter()) .registerTypeAdapterFactory(new RecordTypeAdapterFactory()) .disableHtmlEscaping() .setPrettyPrinting() .create()); Settings.loadConfig(); if (!Settings.getConfig().isDebug()) Logger.setLevel(Level.WARNING); long currentTime = System.currentTimeMillis(); Cache.init(Settings.getConfig().getCachePath()); MapXTEAs.loadKeys(); WorldDB DB = new WorldDB(); DB.init(); GameDecoder.loadPacketDecoders(); AsyncTaskExecutor.initExecutors(); PluginManager.loadPlugins(); PluginManager.executeStartupHooks(); try { ServerChannelHandler.init(Settings.getConfig().getWorldInfo().port(), BaseWorldDecoder.class); } catch (Throwable e) { Logger.handle(Launcher.class, "main", e); Logger.error(Launcher.class, "main", "Failed to initialize server channel handler. Shutting down..."); System.exit(1); return; } WorldThread.init(); Logger.info(Launcher.class, "main", "Server launched in " + (System.currentTimeMillis() - currentTime) + " ms..."); Logger.info(Launcher.class, "main", "Server is listening at " + InetAddress.getLocalHost().getHostAddress() + ":" + Settings.getConfig().getWorldInfo().port() + "..."); Logger.info(Launcher.class, "main", "Player will be directed to "+Settings.getConfig().getWorldInfo()+"..."); Logger.info(Launcher.class, "main", "Registering world with lobby server..."); Logger.info(Launcher.class, "main", Settings.getConfig().getWorldInfo()); new WorldAPI().start(); LobbyCommunicator.post(Boolean.class, Settings.getConfig().getWorldInfo(), "addworld", success -> { if (success) Logger.info(Launcher.class, "main", "Registered world with lobby server..."); else Logger.warn(Launcher.class, "main", "Failed to register world with lobby server... You can still login locally but social features will not work properly."); }); addCleanMemoryTask(); // Runtime.getRuntime().addShutdownHook(new Thread() { // @Override // public void run() { // try { // for (Player player : World.getPlayers()) { // if (player == null || !player.hasStarted()) // continue; // try { // player.getPackets().sendLogout(player, true); // player.realFinish(); // } catch(Throwable e) { // // } // } // PartyRoom.save(); // Launcher.shutdown(); // } catch (Throwable e) { // Logger.handle(this, e); // } // } // }); } private static void addCleanMemoryTask() { AsyncTaskExecutor.schedule(() -> { try { cleanMemory(WorldUtil.getMemUsedPerc() > Settings.HIGH_MEM_USE_THRESHOLD); } catch (Throwable e) { Logger.handle(Launcher.class, "addCleanMemoryTask", e); } }, 0, Ticks.fromMinutes(10)); //}, 0, Ticks.fromSeconds(10)); } public static void saveFilesSync() { for (Player player : World.getPlayers()) { if (player == null || !player.hasStarted() || player.hasFinished()) continue; WorldDB.getPlayers().saveSync(player); } WorldPersistentData.save(); } public static void saveFilesAsync() { for (Player player : World.getPlayers()) { if (player == null || !player.hasStarted() || player.hasFinished()) continue; WorldDB.getPlayers().save(player); } WorldPersistentData.save(); } public static void cleanMemory(boolean force) { if (force) { ItemDefinitions.clearItemsDefinitions(); NPCDefinitions.clearNPCDefinitions(); ObjectDefinitions.clearObjectDefinitions(); ChunkManager.clearUnusedMemory(); Logger.debug(Launcher.class, "cleanMemory", "Force cleaning cached data."); } for (Index index : Cache.STORE.getIndices()) index.resetCachedFiles(); System.gc(); System.gc(); } public static void shutdown() { try { closeServices(); } finally { System.exit(0); } } public static void closeServices() { ServerChannelHandler.shutdown(); AsyncTaskExecutor.shutdown(); } private Launcher() { } public static void executeCommand(String cmd) { executeCommand(null, cmd); } public static void executeCommand(Player player, String cmd) { AsyncTaskExecutor.execute(() -> { try { String line; ProcessBuilder builder = new ProcessBuilder(cmd.split(" ")); Process proc = builder.start(); BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream())); while ((line = in.readLine()) != null) { if (player != null) player.getPackets().sendDevConsoleMessage(line); Logger.debug(Launcher.class, "executeCommand", line); } proc.waitFor(); in.close(); } catch (IOException | InterruptedException e) { if (player != null) player.getPackets().sendDevConsoleMessage("Error: " + e.getMessage()); Logger.handle(Launcher.class, "executeCommand", e); } }); } }
package com.rs; public final class Settings { private static Settings SETTINGS; private static final Settings DEFAULTS = new Settings(); public static Settings getConfig() { if (SETTINGS == null) loadConfig(); return SETTINGS; } private String serverName; private String ownerName; private String cachePath; private boolean debug = false; private boolean enableJFR = false; private final boolean allowHighMemUseOptimizations; private String mongoUrl; private int mongoPort; private String mongoUser; private String mongoPass; private String mongoDbName; private String lobbyIp; private String lobbyApiKey; private WorldInfo worldInfo; private String loginMessage; private Tile playerStartTile; private Tile playerRespawnTile; private int xpRate; private double dropModifier; private Item[] startItems; private String staffWebhookUrl; public Settings() { serverName = "Darkan"; ownerName = "trent"; cachePath = "../cache/"; debug = false; enableJFR = false; allowHighMemUseOptimizations = false; lobbyIp = "dev.darkan.org"; mongoUrl = "localhost"; mongoPort = 27017; mongoUser = ""; mongoPass = ""; mongoDbName = "darkan-server"; lobbyApiKey = "TEST_API_KEY"; worldInfo = new WorldInfo(3, "127.0.0.1", 43595, "My Test World", 1, false, true, true, false, false); loginMessage = ""; playerStartTile = Tile.of(2889, 3528, 0); playerRespawnTile = Tile.of(2887, 3535, 0); xpRate = 1; dropModifier = 1.0; startItems = new Item[] { new Item(1351, 1), new Item(590, 1), new Item(303, 1), new Item(315, 1), new Item(1925, 1), new Item(1931, 1), new Item(2309, 1), new Item(1265, 1), new Item(1205, 1), new Item(1277, 1), new Item(1171, 1), new Item(841, 1), new Item(882, 25), new Item(556, 25), new Item(558, 15), new Item(555, 6), new Item(557, 4), new Item(559, 2), }; staffWebhookUrl = null; } public static final long WORLD_CYCLE_NS = 600000000L; public static final long WORLD_CYCLE_MS = WORLD_CYCLE_NS / 1000000L; public static final int AIR_GUITAR_MUSICS_COUNT = 150; public static final int PLAYERS_LIMIT = 2000; public static final int LOCAL_PLAYERS_LIMIT = 250; public static final int NPCS_LIMIT = 64000; public static final int LOCAL_NPCS_LIMIT = 250; public static final double HIGH_MEM_USE_THRESHOLD = 85.0; public static ArrayList<String> COMMIT_HISTORY = new ArrayList<>(); public static void loadConfig() { Logger.info(Settings.class, "loadConfig", "Loading config..."); try { File rootConfigFile = new File("./worldConfig.json"); File dataConfigFile = new File("./data/worldConfig.json"); if (rootConfigFile.exists()) SETTINGS = JsonFileManager.loadJsonFile(rootConfigFile, Settings.class); else if (dataConfigFile.exists()) SETTINGS = JsonFileManager.loadJsonFile(dataConfigFile, Settings.class); else SETTINGS = new Settings(); for (Field f : SETTINGS.getClass().getDeclaredFields()) if (f.get(SETTINGS) == null) f.set(SETTINGS, f.get(DEFAULTS)); JsonFileManager.saveJsonFile(SETTINGS, dataConfigFile); if (rootConfigFile.exists()) rootConfigFile.delete(); } catch (JsonIOException | IOException | IllegalArgumentException | IllegalAccessException e1) { e1.printStackTrace(); System.exit(5); } try { String line; ProcessBuilder builder = new ProcessBuilder("git", "log", "-n", "1"); Process proc = builder.start(); BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream())); boolean markMsg = false; while ((line = in.readLine()) != null) { if (line.isEmpty()) continue; line = line.replace("commit ", "Hash: "); if (markMsg) { line = "Message: " + line.trim(); markMsg = false; } if (line.contains("Date: ")) markMsg = true; COMMIT_HISTORY.add(line); } proc.waitFor(); in.close(); Logger.info(Settings.class, "loadConfig", "Commit history loaded: " + COMMIT_HISTORY); } catch (JsonIOException | IOException | InterruptedException e) { Logger.handle(Settings.class, "loadConfig", e); } Globals.DEBUG = getConfig().debug; Logger.info(Settings.class, "loadConfig", "Loaded lobby IP: " + getConfig().lobbyIp); } public static void saveConfig() throws IOException { JsonFileManager.saveJsonFile(SETTINGS, new File("./worldConfig.json")); } public String getServerName() { return serverName; } public String getOwnerName() { return ownerName; } public boolean isDebug() { return debug; } public boolean isEnableJFR() { return enableJFR; } public boolean isAllowHighMemUseOptimizations() { return allowHighMemUseOptimizations; } public String getLoginMessage() { return loginMessage; } public void setLoginMessage(String loginMessage) { this.loginMessage = loginMessage; } public Tile getPlayerStartTile() { return Tile.of(playerStartTile != null ? playerStartTile : DEFAULTS.playerStartTile); } public Tile getPlayerRespawnTile() { return Tile.of(playerRespawnTile != null ? playerRespawnTile : DEFAULTS.playerRespawnTile); } public int getXpRate() { return xpRate; } public double getDropModifier() { return dropModifier; } public String getCachePath() { return cachePath != null ? cachePath : DEFAULTS.cachePath; } public static boolean isOwner(String string) { return string.equalsIgnoreCase(SETTINGS.getOwnerName()); } public Item[] getStartItems() { return startItems != null ? startItems : DEFAULTS.startItems; } public WorldInfo getWorldInfo() { return worldInfo != null ? worldInfo : DEFAULTS.worldInfo; } public String getLobbyIp() { return lobbyIp; } public String getLobbyApiKey() { return lobbyApiKey; } public String getMongoDBName() { return mongoDbName; } public String getMongoDb() { String db = "mongodb://"; if (mongoUser != null && !mongoUser.isEmpty()) db += mongoUser + ":" + new PercentEscaper("", false).escape(mongoPass) + "@"; db += mongoUrl; if (mongoPort > 0) db += ":" + mongoPort; db += "/"+mongoDbName+"?retryWrites=true&w=majority"; return db; } public String getStaffWebhookUrl() { return staffWebhookUrl; } public void setJFR(boolean b) { enableJFR = b; } }
package com.rs.db; public class WorldDB extends DBConnection { private static final PlayerManager PLAYERS = new PlayerManager(); private static final HighscoresManager HIGHSCORES = new HighscoresManager(); private static final GEManager GE = new GEManager(); private static final LogManager LOGS = new LogManager(); public WorldDB() { super(Settings.getConfig().getMongoDb(), Settings.getConfig().getMongoDBName()); Logger.info(WorldDB.class, "constructor()", "Connecting to MongoDB and initializing databases..."); addItemManager(PLAYERS); addItemManager(HIGHSCORES); addItemManager(GE); addItemManager(LOGS); } public static PlayerManager getPlayers() { return PLAYERS; } public static HighscoresManager getHighscores() { return HIGHSCORES; } public static GEManager getGE() { return GE; } public static LogManager getLogs() { return LOGS; } }
package com.rs.db.collection; public class GEManager extends DBItemManager { public GEManager() { super("grandexchange"); } @Override public void initCollection() { getDocs().createIndex(Indexes.text("owner")); getDocs().createIndex(Indexes.compoundIndex(Indexes.ascending("itemId"), Indexes.ascending("completedAmount"))); getDocs().createIndex(Indexes.compoundIndex(Indexes.ascending("itemId"), Indexes.ascending("state"))); getDocs().createIndex(Indexes.compoundIndex(Indexes.ascending("itemId"), Indexes.ascending("price"))); getDocs().createIndex(Indexes.compoundIndex(Indexes.ascending("itemId"), Indexes.ascending("selling"))); } public void get(String username, Consumer<List<Offer>> func) { execute(() -> func.accept(getSync(username))); } public void save(Offer offer) { save(offer, null); } public void save(Offer offer, Runnable done) { execute(() -> { saveSync(offer); if (done != null) done.run(); }); } public void saveSync(Offer offers) { getDocs().findOneAndReplace(Filters.and(Filters.eq("owner", offers.getOwner()), Filters.eq("box", offers.getBox())), Document.parse(JsonFileManager.toJson(offers)), new FindOneAndReplaceOptions().upsert(true)); } public List<Offer> getSync(String username) { FindIterable<Document> offerDocs = getDocs().find(Filters.eq("owner", username)); if (offerDocs == null) return null; try { List<Offer> offers = new ArrayList<>(6); for (Document d : offerDocs) { Offer offer = JsonFileManager.fromJSONString(JsonFileManager.toJson(d), Offer.class); offers.add(offer); } return offers; } catch (JsonIOException | IOException e) { Logger.handle(GEManager.class, "getSync", e); return null; } } public void remove(String username, int box, Runnable done) { execute(() -> { removeSync(username, box); if (done != null) done.run(); }); } public void removeSync(String username, int box) { getDocs().findOneAndDelete(Filters.and(Filters.eq("owner", username), Filters.eq("box", box))); } public List<Offer> getBestOffersSync(Offer other) { if (other.getState() == State.FINISHED) return null; List<Offer> result = new ArrayList<>(); FindIterable<Document> docs = getDocs().find(Filters.and(Filters.eq("state", State.STABLE.toString()), Filters.eq("itemId", other.getItemId()), Filters.eq("selling", !other.isSelling()), other.isSelling() ? Filters.gte("price", other.getPrice()) : Filters.lte("price", other.getPrice()))).sort(Sorts.ascending("price")); for (Document doc : docs) try { Offer offer = JsonFileManager.fromJSONString(JsonFileManager.toJson(doc), Offer.class); result.add(offer); } catch (JsonIOException | IOException e) { Logger.handleNoRecord(GEManager.class, "getBestOffersSync", "Error converting document: " + result, e); } return result; } public void getBestOffer(int itemId, boolean sell, Consumer<Offer> func) { execute(() -> { FindIterable<Document> docs = getDocs().find(Filters.and(Filters.eq("state", State.STABLE.toString()), Filters.eq("itemId", itemId), Filters.eq("selling", !sell))).sort(sell ? Sorts.ascending("price") : Sorts.descending("price")); try { func.accept(JsonFileManager.fromJSONString(JsonFileManager.toJson(docs.first()), Offer.class)); } catch (JsonIOException | IOException e) { func.accept(null); } }); } public void getAllOffersOfType(boolean selling, Consumer<List<Offer>> func) { execute(() -> { List<Offer> result = new ArrayList<>(); FindIterable<Document> docs = getDocs().find(Filters.and(Filters.eq("state", State.STABLE.toString()), Filters.eq("selling", selling))); for (Document doc : docs) try { Offer offer = JsonFileManager.fromJSONString(JsonFileManager.toJson(doc), Offer.class); result.add(offer); } catch (JsonIOException | IOException e) { Logger.handleNoRecord(GEManager.class, "getAllOffersOfType", "Error converting document: " + result, e); } func.accept(result); }); } }
package com.rs.db.collection; public class HighscoresManager extends DBItemManager { public HighscoresManager() { super("highscores"); } @Override public void initCollection() { getDocs().createIndex(Indexes.compoundIndex(Indexes.text("displayName"), Indexes.text("username"))); getDocs().createIndex(Indexes.descending("totalLevel", "totalXp")); } public void save(Player player) { save(player, null); } public void save(Player player, Runnable done) { execute(() -> { saveSync(player); if (done != null) done.run(); }); } public void saveSync(Player player) { if (player.hasRights(Rights.OWNER) || player.hasRights(Rights.DEVELOPER) || player.hasRights(Rights.ADMIN) || player.getSkills().getTotalXp() < 50000) return; try { getDocs().findOneAndReplace(eq("username", player.getUsername()), Document.parse(JsonFileManager.toJson(new Highscore(player))), new FindOneAndReplaceOptions().upsert(true)); } catch (Exception e) { Logger.handle(HighscoresManager.class, "saveSync", e); } } public void getPlayerAtPosition(int rank, Consumer<Highscore> top) { execute(() -> { try { top.accept(JsonFileManager.fromJSONString(getDocs().find().sort(Sorts.descending("totalLevel", "totalXp")).skip(rank).limit(1).first().toJson(), Highscore.class)); } catch(Throwable e) { top.accept(null); } }); } }
package com.rs.db.collection; public class PlayerManager extends DBItemManager { public PlayerManager() { super("players"); } @Override public void initCollection() { getDocs().createIndex(Indexes.text("username")); } public void getByUsername(String username, Consumer<Player> func) { execute(() -> func.accept(getSyncUsername(username))); } public void save(Player player) { save(player, null); } public void save(Player account, Runnable done) { execute(() -> { saveSync(account); if (done != null) done.run(); }); } public void saveSync(Player account) { try { getDocs().findOneAndReplace(eq("username", account.getUsername()), Document.parse(JsonFileManager.toJson(account)), new FindOneAndReplaceOptions().upsert(true)); } catch(Throwable e) { Logger.handle(PlayerManager.class, "saveSync", "Error saving player: " + account.getUsername(), e); } } public Player getSyncUsername(String username) { Player loggedIn = World.getPlayerByUsername(username); if (loggedIn != null) return loggedIn; Document accDoc = getDocs().find(eq("username", username)).first(); if (accDoc == null) return null; try { return JsonFileManager.fromJSONString(JsonFileManager.toJson(accDoc), Player.class); } catch (JsonIOException | IOException e) { Logger.handle(PlayerManager.class, "getSyncUsername", e); return null; } } public boolean usernameExists(String username) { return getSyncUsername(username) == null; } }
package com.rs.db.collection.logs; public class CommandLog { private final String uuid; private final String player; private final String command; public CommandLog(String player, String command) { this.player = player; this.command = command; this.uuid = UUID.randomUUID().toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CommandLog that = (CommandLog) o; return Objects.equals(uuid, that.uuid) && Objects.equals(player, that.player) && Objects.equals(command, that.command); } @Override public int hashCode() { return Objects.hash(uuid, player, command); } }
package com.rs.db.collection.logs; public class GELog { private final String uuid; private final String from; private final String to; private final String item; private final int itemId; private final int amount; private final int price; public GELog(Offer offer1, Offer offer2, int amount, int price) { Offer sellOffer = offer1.getOfferType() == GE.OfferType.SELL ? offer1 : offer2; Offer buyOffer = offer2.getOfferType() == GE.OfferType.BUY ? offer2 : offer1; to = buyOffer.getOwner(); item = ItemDefinitions.getDefs(sellOffer.getItemId()).name; itemId = sellOffer.getItemId(); this.amount = amount; this.price = price; this.uuid = UUID.randomUUID().toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GELog geLog = (GELog) o; return itemId == geLog.itemId && amount == geLog.amount && price == geLog.price && Objects.equals(uuid, geLog.uuid) && Objects.equals(from, geLog.from) && Objects.equals(to, geLog.to) && Objects.equals(item, geLog.item); } @Override public int hashCode() { return Objects.hash(from, to, item, itemId, amount, price, uuid); } }
package com.rs.db.collection.logs; public class GraveLog { private final String uuid; private final String player; private final Tile tile; private final List<Item> items; public GraveLog(String player, GraveStone grave) { this.player = player; this.tile = grave.getTile(); items = new ArrayList<>(); for (GroundItem item : grave.getItems()) if (item != null) items.add(new Item(item)); this.uuid = UUID.randomUUID().toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GraveLog graveLog = (GraveLog) o; return Objects.equals(uuid, graveLog.uuid) && Objects.equals(player, graveLog.player) && Objects.equals(tile, graveLog.tile) && Objects.equals(items, graveLog.items); } @Override public int hashCode() { return Objects.hash(uuid, player, tile, items); } }
package com.rs.db.collection.logs; public class LogEntry { public enum LogType { ERROR, GE, PICKUP, GRAVE, COMMAND, REPORT, TRADE } private final Date date; private final LogType type; private final long hash; private final Object data; public LogEntry(LogType type, long hash, Object data) { this.date = new Date(); this.type = type; this.hash = hash; this.data = data; } public Date getDate() { return date; } public LogType getType() { return type; } public long getHash() { return hash; } public Object getData() { return data; } }
package com.rs.db.collection.logs; public class LogManager extends DBItemManager { public LogManager() { super("logs"); } @Override public void initCollection() { getDocs().createIndex(Indexes.text("type")); getDocs().createIndex(Indexes.descending("hash")); getDocs().createIndex(Indexes.ascending("date"), new IndexOptions().expireAfter(180L, TimeUnit.DAYS)); } public void save(LogEntry entry) { save(entry, null); } public void save(LogEntry entry, Runnable done) { execute(() -> { saveSync(entry); if (done != null) done.run(); }); } public void saveSync(LogEntry entry) { try { getDocs().findOneAndReplace(eq("hash", entry.getHash()), Document.parse(JsonFileManager.toJson(entry)), new FindOneAndReplaceOptions().upsert(true)); } catch(Throwable e) { e.printStackTrace(); } } public void logGE(Offer offer, Offer other, int num, int price) { GELog log = new GELog(offer, other, num, price); save(new LogEntry(LogEntry.LogType.GE, log.hashCode(), log)); } public void logTrade(Player player1, Trade p1Trade, Player p2, Trade p2Trade) { List<Item> p1Items = new ArrayList<>(); List<Item> p2Items = new ArrayList<>(); for (Item item : p1Trade.getItems().array()) if (item != null) p1Items.add(item); for (Item item : p2Trade.getItems().array()) if (item != null) p2Items.add(item); if (p1Items.size() > 0 || p2Items.size() > 0) { TradeLog log = new TradeLog(player1, p1Items, p2, p2Items); save(new LogEntry(LogEntry.LogType.TRADE, log.hashCode(), log)); } } public void logPickup(Player player, GroundItem item) { PickupLog log = new PickupLog(player, item); save(new LogEntry(LogEntry.LogType.PICKUP, log.hashCode(), log)); } public void logGrave(String player, GraveStone grave) { GraveLog log = new GraveLog(player, grave); save(new LogEntry(LogEntry.LogType.GRAVE, log.hashCode(), log)); } public void logReport(Player reporter, Player reported, ReportsManager.Rule rule) { if (reporter == null || reported == null) return; ReportLog log = new ReportLog(reporter, reported, rule); save(new LogEntry(LogEntry.LogType.REPORT, log.hashCode(), log)); } public void logCommand(String username, String commandStr) { CommandLog log = new CommandLog(username, commandStr); save(new LogEntry(LogEntry.LogType.COMMAND, log.hashCode(), log)); } }
package com.rs.db.collection.logs; public class PickupLog { private final String uuid; private final String player; private final String itemName; private final Item item; private final Tile tile; private final String owner; public PickupLog(Player player, GroundItem item) { this.player = player.getUsername(); this.tile = item.getTile(); this.item = new Item(item); this.itemName = item.getName(); this.owner = item.getCreatorUsername(); this.uuid = UUID.randomUUID().toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PickupLog pickupLog = (PickupLog) o; return Objects.equals(uuid, pickupLog.uuid) && Objects.equals(player, pickupLog.player) && Objects.equals(itemName, pickupLog.itemName) && Objects.equals(item, pickupLog.item) && Objects.equals(tile, pickupLog.tile) && Objects.equals(owner, pickupLog.owner); } @Override public int hashCode() { return Objects.hash(uuid, player, itemName, item, tile, owner); } }
package com.rs.db.collection.logs; public class ReportLog { private Object relevantData; public ReportLog(Player reporter, Player reported, Rule rule) { String player = reported.getUsername(); String reporter1 = reporter.getUsername(); } //TODO finish //TODO create hashCode and equals }
package com.rs.db.collection.logs; public class TradeLog { private final String uuid; private final String player1; private final List<Item> p1Items; private final String player2; private final List<Item> p2Items; public TradeLog(Player p1, List<Item> p1Items, Player p2, List<Item> p2Items) { this.player1 = p1.getUsername(); this.p1Items = p1Items; this.player2 = p2.getUsername(); this.p2Items = p2Items; this.uuid = UUID.randomUUID().toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TradeLog tradeLog = (TradeLog) o; return Objects.equals(uuid, tradeLog.uuid) && Objects.equals(player1, tradeLog.player1) && Objects.equals(p1Items, tradeLog.p1Items) && Objects.equals(player2, tradeLog.player2) && Objects.equals(p2Items, tradeLog.p2Items); } @Override public int hashCode() { int result = Objects.hash(uuid, player1, player2, p1Items, p2Items); return result; } }
package com.rs.db.model; public class Highscore { private final String username; private final String displayName; private final boolean ironman; private final int totalLevel; private final long totalXp; private final int[] xp; public Highscore(Player player) { if (player.getDisplayName() == null) throw new RuntimeException("No display name found for player: " + player.getUsername()); username = player.getUsername(); displayName = player.getDisplayName(); ironman = player.isIronMan(); totalLevel = player.getSkills().getTotalLevel(); totalXp = player.getSkills().getTotalXp(); xp = player.getSkills().getXpInt(); } public boolean isIronman() { return ironman; } public int getTotalLevel() { return totalLevel; } public long getTotalXp() { return totalXp; } public int[] getXp() { return xp; } public String getUsername() { return username; } public String getDisplayName() { return displayName; } }
package com.rs.engine; @PluginEventHandler public class Shop { private static final int MAIN_STOCK_ITEMS_KEY = 0; private static final int MAX_SHOP_ITEMS = 40; private String name; private ShopItem[] mainStock; private int[] defaultQuantity; private ShopItem[] generalStock; private boolean buyOnly; private int currency; private final transient CopyOnWriteArrayList<Player> viewingPlayers; public Shop(String name, int money, ShopItem[] shopItems, boolean isGeneralStore, boolean buyOnly) { viewingPlayers = new CopyOnWriteArrayList<>(); this.name = name; currency = money; mainStock = shopItems; defaultQuantity = new int[shopItems.length]; for (int i = 0; i < defaultQuantity.length; i++) defaultQuantity[i] = shopItems[i].getItem().getAmount(); if (isGeneralStore && shopItems.length < MAX_SHOP_ITEMS) generalStock = new ShopItem[MAX_SHOP_ITEMS - shopItems.length]; this.buyOnly = buyOnly; for (ShopItem item : mainStock) { if (item == null) continue; item.init(); } } public static ButtonClickHandler handleInterfaces = new ButtonClickHandler(new Object[] { 449, 1265, 1266, 621 }, e -> { if (e.getInterfaceId() == 449) { if (e.getComponentId() == 1) { Shop shop = e.getPlayer().getTempAttribs().getO("Shop"); if (shop == null) return; shop.sendInventory(e.getPlayer()); } else if (e.getComponentId() == 21) { Shop shop = e.getPlayer().getTempAttribs().getO("Shop"); if (shop == null) return; int slot = e.getPlayer().getTempAttribs().getI("ShopSelectedSlot"); if (slot == -1) return; if (e.getPacket() == ClientPacket.IF_OP1) shop.buy(e.getPlayer(), slot, 1); else if (e.getPacket() == ClientPacket.IF_OP2) shop.buy(e.getPlayer(), slot, 5); else if (e.getPacket() == ClientPacket.IF_OP3) shop.buy(e.getPlayer(), slot, 10); else if (e.getPacket() == ClientPacket.IF_OP4) shop.buy(e.getPlayer(), slot, 50); shop.sendCustomPrices(e.getPlayer()); } } else if (e.getInterfaceId() == 1265) { Shop shop = e.getPlayer().getTempAttribs().getO("Shop"); if (shop == null) return; int slot = e.getPlayer().getTempAttribs().getI("ShopSelectedSlot"); boolean isBuying = e.getPlayer().getTempAttribs().getB("shop_buying"); if (e.getComponentId() == 20) { e.getPlayer().getTempAttribs().setI("ShopSelectedSlot", e.getSlotId()); if (e.getPacket() == ClientPacket.IF_OP1) shop.sendInfo(e.getPlayer(), e.getSlotId(), isBuying); else if (e.getPacket() == ClientPacket.IF_OP2) shop.handleShop(e.getPlayer(), e.getSlotId(), 1); else if (e.getPacket() == ClientPacket.IF_OP3) shop.handleShop(e.getPlayer(), e.getSlotId(), 5); else if (e.getPacket() == ClientPacket.IF_OP4) shop.handleShop(e.getPlayer(), e.getSlotId(), 10); else if (e.getPacket() == ClientPacket.IF_OP5) shop.handleShop(e.getPlayer(), e.getSlotId(), 50); else if (e.getPacket() == ClientPacket.IF_OP6) shop.handleShop(e.getPlayer(), e.getSlotId(), 500); else if (e.getPacket() == ClientPacket.IF_OP7) e.getPlayer().sendOptionDialogue("Really buy out the shop? This could be absurdly expensive.", ops -> { ops.add("Yes, I am sure.", () -> shop.handleShop(e.getPlayer(), e.getSlotId(), Integer.MAX_VALUE)); ops.add("Nevermind."); }); else if (e.getPacket() == ClientPacket.IF_OP10) shop.sendExamine(e.getPlayer(), e.getSlotId()); } else if (e.getComponentId() == 201) { if (slot == -1) return; if (isBuying) shop.buy(e.getPlayer(), slot, e.getPlayer().getTempAttribs().getI("shopAmt", 0)); else { shop.sell(e.getPlayer(), slot, e.getPlayer().getTempAttribs().getI("shopAmt", 0)); e.getPlayer().getVars().setVar(2563, 0); e.getPlayer().getVars().setVar(2565, 1); // this is to update the tab. } } else if (e.getComponentId() == 208) { e.getPlayer().getTempAttribs().setI("shopAmt", Utils.clampI(e.getPlayer().getTempAttribs().getI("shopAmt", 0) + 5, 1, 5000)); e.getPlayer().getPackets().setIFText(1265, 67, String.valueOf(e.getPlayer().getTempAttribs().getI("shopAmt", 0))); } else if (e.getComponentId() == 15) { e.getPlayer().getTempAttribs().setI("shopAmt", Utils.clampI(e.getPlayer().getTempAttribs().getI("shopAmt", 0) + 1, 1, 5000)); e.getPlayer().getPackets().setIFText(1265, 67, String.valueOf(e.getPlayer().getTempAttribs().getI("shopAmt", 0))); } else if (e.getComponentId() == 214) { e.getPlayer().getTempAttribs().setI("shopAmt", Utils.clampI(e.getPlayer().getTempAttribs().getI("shopAmt", 0) - 1, 1, 5000)); e.getPlayer().getPackets().setIFText(1265, 67, String.valueOf(e.getPlayer().getTempAttribs().getI("shopAmt", 0))); } else if (e.getComponentId() == 217) { e.getPlayer().getTempAttribs().setI("shopAmt", Utils.clampI(e.getPlayer().getTempAttribs().getI("shopAmt", 0) - 5, 1, 5000)); e.getPlayer().getPackets().setIFText(1265, 67, String.valueOf(e.getPlayer().getTempAttribs().getI("shopAmt", 0))); } else if (e.getComponentId() == 220) { e.getPlayer().getTempAttribs().setI("shopAmt", 1); e.getPlayer().getPackets().setIFText(1265, 67, String.valueOf(e.getPlayer().getTempAttribs().getI("shopAmt", 0))); } else if (e.getComponentId() == 211) { if ((slot == -1) || (shop.getMainStock() == null) || (slot > shop.getMainStock().length - 1) || (shop.getMainStock()[slot] == null)) return; if (e.getPlayer().getInventory().getItems().array()[slot] == null) return; e.getPlayer().getTempAttribs().setI("shopAmt", Utils.clampI(isBuying ? shop.getMainStock()[slot].getItem().getAmount() : e.getPlayer().getInventory().getItems().array()[slot].getAmount(), 1, 5000)); e.getPlayer().getPackets().setIFText(1265, 67, String.valueOf(e.getPlayer().getTempAttribs().getI("shopAmt", 0))); } else if (e.getComponentId() == 29) { e.getPlayer().getVars().setVar(2561, 93); e.getPlayer().getTempAttribs().removeB("shop_buying"); e.getPlayer().getTempAttribs().setI("shopAmt", 1); } else if (e.getComponentId() == 28) { e.getPlayer().getTempAttribs().setB("shop_buying", true); e.getPlayer().getTempAttribs().setI("shopAmt", 1); e.getPlayer().getPackets().setIFText(1265, 67, String.valueOf(e.getPlayer().getTempAttribs().getI("shopAmt", 0))); } shop.sendCustomPrices(e.getPlayer()); } else if (e.getInterfaceId() == 1266) { if (e.getComponentId() == 0) if (e.getPacket() == ClientPacket.IF_OP6) e.getPlayer().getInventory().sendExamine(e.getSlotId()); else { Shop shop = e.getPlayer().getTempAttribs().getO("Shop"); if (shop == null) return; e.getPlayer().getVars().setVar(2563, e.getSlotId()); if (e.getPacket() == ClientPacket.IF_OP1) shop.sendValue(e.getPlayer(), e.getSlotId()); else if (e.getPacket() == ClientPacket.IF_OP2) shop.sell(e.getPlayer(), e.getSlotId(), 1); else if (e.getPacket() == ClientPacket.IF_OP3) shop.sell(e.getPlayer(), e.getSlotId(), 5); else if (e.getPacket() == ClientPacket.IF_OP4) shop.sell(e.getPlayer(), e.getSlotId(), 10); else if (e.getPacket() == ClientPacket.IF_OP5) shop.sell(e.getPlayer(), e.getSlotId(), 50); } } else if (e.getInterfaceId() == 621) if (e.getComponentId() == 0) if (e.getPacket() == ClientPacket.IF_OP6) e.getPlayer().getInventory().sendExamine(e.getSlotId()); else { Shop shop = e.getPlayer().getTempAttribs().getO("Shop"); if (shop == null) return; if (e.getPacket() == ClientPacket.IF_OP1) shop.sendValue(e.getPlayer(), e.getSlotId()); else if (e.getPacket() == ClientPacket.IF_OP2) shop.sell(e.getPlayer(), e.getSlotId(), 1); else if (e.getPacket() == ClientPacket.IF_OP3) shop.sell(e.getPlayer(), e.getSlotId(), 5); else if (e.getPacket() == ClientPacket.IF_OP4) shop.sell(e.getPlayer(), e.getSlotId(), 10); else if (e.getPacket() == ClientPacket.IF_OP5) shop.sell(e.getPlayer(), e.getSlotId(), 50); } }); public boolean isGeneralStore() { return generalStock != null; } public void addPlayer(final Player player) { viewingPlayers.add(player); player.getTempAttribs().setO("Shop", this); player.setCloseInterfacesEvent(() -> { viewingPlayers.remove(player); player.getTempAttribs().removeO("Shop"); }); player.getVars().setVar(118, MAIN_STOCK_ITEMS_KEY); player.getVars().setVar(1496, -1); player.getVars().setVar(532, currency); player.getVars().setVar(2561, -1); player.getVars().setVar(2562, -1); player.getVars().setVar(2563, -1); //player.getVars().setVar(2565, 1); //changes to sell tab player.getVars().syncVarsToClient(); sendStore(player); player.getInterfaceManager().sendInterface(1265); player.getPackets().sendVarc(1876, -1); player.getPackets().setIFEvents(new IFEvents(1265, 20, 0, getStoreSize() * 6).enableRightClickOptions(0,1,2,3,4,5,9)); player.getPackets().setIFEvents(new IFEvents(1265, 26, 0, getStoreSize() * 6) .enableUseOptions(UseFlag.ICOMPONENT) .enableRightClickOptions(0,2,3) .setDepth(4) .enableDrag() .enableDepthFlagIgnoring() .enableUseTargetability()); player.getPackets().setIFText(1265, 85, name); if (isGeneralStore()) player.getPackets().setIFHidden(1265, 52, false); sendInventory(player); player.getTempAttribs().setB("shop_buying", true); WorldTasks.delay(1, () -> sendCustomPrices(player)); } public void sendCustomPrices(Player player) { if (!player.getTempAttribs().getB("shop_buying")) return; for (int i = 0;i < mainStock.length;i++) { if (mainStock[i] == null) continue; //player.getPackets().setIFSprite(1265, 24, i, 592); if (mainStock[i].getCustomPrice() > 0) player.getPackets().setIFText(1265, 23, i, Utils.kmify(mainStock[i].getCustomPrice())); } } public void sendInventory(Player player) { player.getInterfaceManager().sendInventoryInterface(1266); player.getPackets().sendItems(93, player.getInventory().getItems()); player.getPackets().setIFRightClickOps(1266, 0, 0, 27, 0, 1, 2, 3, 4, 5); player.getPackets().sendInterSetItemsOptionsScript(1266, 0, 93, 4, 7, "Value", "Sell 1", "Sell 5", "Sell 10", "Sell 50", "Examine"); } // cid 67 public void buy(Player player, int slotId, int quantity) { if (slotId >= mainStock.length && player.isIronMan()) { player.sendMessage("You can't buy something another player has sold as an ironman!"); return; } if (slotId >= getStoreSize()) return; ShopItem item = slotId >= mainStock.length ? generalStock[slotId - mainStock.length] : mainStock[slotId]; if (item == null) return; if (item.getItem().getAmount() == 0) { player.sendMessage("There is no stock of that item at the moment."); return; } int price = getBuyPrice(item); int amountCoins = currency == 995 ? player.getInventory().getCoinsAsInt() : player.getInventory().getItems().getNumberOf(currency); int maxQuantity = amountCoins / price; int buyQ = Math.min(item.getItem().getAmount(), quantity); boolean enoughCoins = maxQuantity >= buyQ; if (!enoughCoins) { player.sendMessage("You don't have enough " + ItemDefinitions.getDefs(currency).name.toLowerCase() + "."); buyQ = maxQuantity; } else if (quantity > buyQ) player.sendMessage("The shop has run out of stock."); if (item.getItem().getDefinitions().isStackable()) { if (player.getInventory().getFreeSlots() < 1) { player.sendMessage("Not enough space in your inventory."); return; } } else { int freeSlots = player.getInventory().getFreeSlots(); if (buyQ > freeSlots) { buyQ = freeSlots; player.sendMessage("Not enough space in your inventory."); } } if (buyQ != 0) { int totalPrice = price * buyQ; if (currency == 995) player.getInventory().removeCoins(totalPrice); else player.getInventory().deleteItem(currency, totalPrice); if (item.getItem().getId() == 36 && buyQ == 5) player.getInventory().addItem(24170, 1); else player.getInventory().addItem(item.getItem().getId(), buyQ); item.getItem().setAmount(item.getItem().getAmount() - buyQ); if (item.getItem().getAmount() <= 0 && slotId >= mainStock.length) generalStock[slotId - mainStock.length] = null; refreshShop(); sendInventory(player); } } public void restoreItems() { boolean needRefresh = false; for (ShopItem element : mainStock) { if (element == null) continue; if (element.tickRestock()) needRefresh = true; } if (generalStock != null) for (int i = 0; i < generalStock.length; i++) { if (generalStock[i] == null) continue; if (generalStock[i].tickRestock()) needRefresh = true; if (generalStock[i].getItem().getAmount() <= 0) generalStock[i] = null; } if (needRefresh) { refreshShop(); for (Player player : viewingPlayers) WorldTasks.delay(0, () -> sendCustomPrices(player)); } } private boolean addItem(int itemId, int quantity) { for (ShopItem item : mainStock) if (item.getItem().getId() == itemId) { item.getItem().setAmount(item.getItem().getAmount() + quantity); refreshShop(); return true; } if (generalStock != null) { for (ShopItem item : generalStock) { if (item == null) continue; if (item.getItem().getId() == itemId) { item.getItem().setAmount(item.getItem().getAmount() + quantity); refreshShop(); return true; } } for (int i = 0; i < generalStock.length; i++) if (generalStock[i] == null) { generalStock[i] = new ShopItem(itemId, quantity); generalStock[i].setCap(-1); refreshShop(); return true; } } return false; } public void sell(Player player, int slotId, int quantity) { if (buyOnly) { player.sendMessage("You cannot sell items to this shop."); return; } if (player.getInventory().getItemsContainerSize() < slotId) return; Item item = player.getInventory().getItem(slotId); if (item == null) return; int originalId = item.getId(); if (item.getDefinitions().isNoted()) item = new Item(item.getDefinitions().getCertId(), item.getAmount()); if (item.getDefinitions().isDestroyItem() || !ItemConstants.isTradeable(item) || item.getId() == currency) { player.sendMessage("You can't sell this item."); return; } int dq = getDefaultQuantity(item.getId()); if (dq == -1 && generalStock == null) { player.sendMessage("You can't sell this item to this shop."); return; } int numberOff = player.getInventory().getItems().getNumberOf(originalId); if (quantity > numberOff) quantity = numberOff; if (!addItem(item.getId(), quantity)) { player.sendMessage("Shop is currently full."); return; } if ((player.getInventory().getNumberOf(currency) + (getSellPrice(item)*quantity)) < 0 || (player.getInventory().getNumberOf(currency)+(getSellPrice(item)*quantity)) > Integer.MAX_VALUE) player.sendMessage("Looks like we need an eco reset.."); else { player.getInventory().deleteItem(originalId, quantity); if (currency == 995) player.getInventory().addCoins(getSellPrice(item) * quantity); else player.getInventory().addItem(currency, getSellPrice(item) * quantity); } } public void sendValue(Player player, int slotId) { if (player.getInventory().getItemsContainerSize() < slotId) return; Item item = player.getInventory().getItem(slotId); if (item == null) return; if (item.getDefinitions().isNoted()) item = new Item(item.getDefinitions().getCertId(), item.getAmount()); if (item.getDefinitions().isNoted() || !ItemConstants.isTradeable(item) || item.getId() == currency) { player.sendMessage("You can't sell this item."); return; } int dq = getDefaultQuantity(item.getId()); if (dq == -1 && generalStock == null) { player.sendMessage("You can't sell this item to this shop."); return; } player.sendMessage(item.getDefinitions().getName() + ": shop will buy for: " + getSellPrice(item) + " " + ItemDefinitions.getDefs(currency).getName().toLowerCase() + ". Right-click the item to sell."); } public int getDefaultQuantity(int itemId) { for (int i = 0; i < mainStock.length; i++) if (mainStock[i].getItem().getId() == itemId) return defaultQuantity[i]; return -1; } public void sendInfo(Player player, int slotId, boolean isBuying) { if (slotId >= getStoreSize()) return; if (isBuying) { ShopItem item = slotId >= mainStock.length ? generalStock[slotId - mainStock.length] : mainStock[slotId]; if (item == null) return; int price = getBuyPrice(item); player.sendMessage(item.getItem().getDefinitions().getName() + ": shop will " + (isBuying ? "sell" : "buy") + " for " + price + " " + ItemDefinitions.getDefs(currency).getName().toLowerCase() + "."); } else { Item[] stock = player.getInventory().getItems().array(); if (slotId >= stock.length) return; Item item = stock[slotId]; if (item == null) return; int price = getSellPrice(item); player.sendMessage(item.getDefinitions().getName() + ": shop will " + (isBuying ? "sell" : "buy") + " for " + price + " " + ItemDefinitions.getDefs(currency).getName().toLowerCase() + "."); } } public int getSellPrice(Item item) { int price = item.getDefinitions().getSellPrice(); if (price == 0) price = 1; if (currency == 6529) { EnumDefinitions defs = EnumDefinitions.getEnum(732); if (defs.getIntValue(item.getId()) != -1) return defs.getIntValue(item.getId()); } else if (currency == 995) { EnumDefinitions defs = EnumDefinitions.getEnum(1441); if (defs.getIntValue(item.getId()) != -1) return defs.getIntValue(item.getId()); } return price; } public int getBuyPrice(ShopItem item) { if (item.getCustomPrice() > 0) return item.getCustomPrice(); int price = item.getItem().getDefinitions().getValue(); if (price == 0) price = 1; if (currency == 6529) { EnumDefinitions defs = EnumDefinitions.getEnum(731); if (defs.getIntValue(item.getItem().getId()) != -1) return defs.getIntValue(item.getItem().getId()); return (int) (price * 3.0 / 2.0); } if (currency == 995) { EnumDefinitions defs = EnumDefinitions.getEnum(733); if (defs.getIntValue(item.getItem().getId()) != -1) return defs.getIntValue(item.getItem().getId()); } return price; } public void sendExamine(Player player, int slotId) { if (slotId >= getStoreSize()) return; ShopItem item = slotId >= mainStock.length ? generalStock[slotId - mainStock.length] : mainStock[slotId]; if (item == null) return; player.sendMessage(ItemConfig.get(item.getItem().getId()).getExamine(item.getItem())); } public void refreshShop() { for (Player player : viewingPlayers) { sendStore(player); player.getPackets().setIFEvents(new IFEvents(620, 25, 0, getStoreSize() * 6).enableRightClickOptions(0,1,2,3,4,5,9)); sendCustomPrices(player); } } public int getStoreSize() { return mainStock.length + (generalStock != null ? generalStock.length : 0); } public void sendStore(Player player) { Item[] stock = new Item[mainStock.length + (generalStock != null ? generalStock.length : 0)]; for (int i = 0;i < stock.length;i++) if (i >= mainStock.length) { ShopItem item = generalStock[i - mainStock.length]; if (item == null) continue; stock[i] = item.getItem(); } else { ShopItem item = mainStock[i]; if (item == null) continue; stock[i] = item.getItem(); } player.getPackets().sendItems(MAIN_STOCK_ITEMS_KEY, stock); } // public void sendSellStore(Player player, Item[] inventory) { // Item[] stock = new Item[inventory.length + (generalStock != null ? generalStock.length : 0)]; // System.arraycopy(inventory, 0, stock, 0, inventory.length); // if (generalStock != null) // System.arraycopy(generalStock, 0, stock, inventory.length, generalStock.length); // player.getPackets().sendItems(MAIN_STOCK_ITEMS_KEY, stock); // } /** * Checks if the player is buying an item or selling it. * * @param player * The player * @param slotId * The slot id * @param amount * The amount */ public void handleShop(Player player, int slotId, int amount) { if (player.getTempAttribs().getB("shop_buying")) buy(player, slotId, amount); else sell(player, slotId, amount); } public ShopItem[] getMainStock() { return mainStock; } public boolean isBuyOnly() { return buyOnly; } }
package com.rs.engine.book; @PluginEventHandler public abstract class Book { private static final int INTERFACE = 960; private static final int[] LEFT_COMPONENTS = { 49, 56, 61, 62, 54, 63, 55, 51, 60, 58, 53, 50, 57, 59, 52 }; private static final int[] RIGHT_COMPONENTS = { 33, 39, 36, 44, 37, 46, 40, 42, 34, 35, 38, 43, 47, 45, 41 }; private Player player; private int page; private final String title; private final BookPage[] pages; public Book(String title, BookPage... pages) { this.title = title; this.pages = pages; } public Book(String title, String text) { this.title = title; this.pages = buildPages(text); } public static ButtonClickHandler handleInter = new ButtonClickHandler(INTERFACE, e -> { if (e.getPlayer().getTempAttribs().getO("currBook") == null) return; Book book = e.getPlayer().getTempAttribs().getO("currBook"); if (e.getComponentId() == 72) book.prevPage(); if (e.getComponentId() == 73) book.nextPage(); }); public void open(Player player) { this.player = player; this.player.getTempAttribs().setO("currBook", this); this.player.setCloseInterfacesEvent(() -> this.player.getTempAttribs().removeO("currBook")); player.getPackets().setIFText(INTERFACE, 69, title); page = 0; update(); } public void update() { player.getInterfaceManager().sendInterface(INTERFACE); if (page == 0) { player.getPackets().setIFHidden(INTERFACE, 72, true); player.getPackets().setIFText(INTERFACE, 70, ""); } else { player.getPackets().setIFHidden(INTERFACE, 72, false); player.getPackets().setIFText(INTERFACE, 70, "Prev"); } if (page >= pages.length-1) { player.getPackets().setIFHidden(INTERFACE, 73, true); player.getPackets().setIFText(INTERFACE, 71, ""); } else { player.getPackets().setIFHidden(INTERFACE, 73, false); player.getPackets().setIFText(INTERFACE, 71, "Next"); } for (int line = 0;line < LEFT_COMPONENTS.length;line++) { player.getPackets().setIFText(INTERFACE, LEFT_COMPONENTS[line], pages[page].getLeftLine(line) == null ? "" : pages[page].getLeftLine(line)); player.getPackets().setIFText(INTERFACE, RIGHT_COMPONENTS[line], pages[page].getRightLine(line) == null ? "" : pages[page].getRightLine(line)); } } private BookPage[] buildPages(String text) { List<BookPage> pages = new ArrayList<>(); String[] lines = Utils.splitTextIntoLines(text, 497, IComponentDefinitions.getInterfaceComponent(INTERFACE, RIGHT_COMPONENTS[0]).baseWidth); int i = 0; while (i < lines.length) { String[] leftPageLines = new String[LEFT_COMPONENTS.length]; String[] rightPageLines = new String[RIGHT_COMPONENTS.length]; for (int j = 0; j < LEFT_COMPONENTS.length; j++) { if (i < lines.length) { leftPageLines[j] = lines[i]; i++; } else { break; } } for (int k = 0; k < RIGHT_COMPONENTS.length; k++) { if (i < lines.length) { rightPageLines[k] = lines[i]; i++; } else { break; } } pages.add(new BookPage(leftPageLines, rightPageLines)); } return pages.toArray(BookPage[]::new); } public void nextPage() { if (page >= pages.length-1) return; page++; update(); } public void prevPage() { if (page <= 0) return; page--; update(); } }
package com.rs.engine.book; public class BookPage { private final String[] left; private final String[] right; public BookPage(String[] left, String[] right) { if (left.length > 15 || right.length > 15) throw new RuntimeException("Cannot create book page with longer than 15 lines of text."); this.left = left; this.right = right; } public String getLeftLine(int line) { return line >= left.length ? "" : left[line]; } public String getRightLine(int line) { return line >= right.length ? "" : right[line]; } }
package com.rs.engine.command; public class Command { private final String usage; private final String description; private final CommandExecution execution; public Command(String usage, String description, CommandExecution execution) { this.description = description; this.execution = execution; this.usage = usage; } public void execute(Player player, String[] args) { execution.run(player, args); } public String getDescription() { return description; } public String getUsage() { return usage; } }
package com.rs.engine.command; public interface CommandExecution { void run(Player p, String[] args); }
package com.rs.engine.command; public final class Commands { private static final Map<Rights, Map<String , Command>> COMMANDS = new HashMap<>(); private static final Map<Rights, Set<Command>> UNIQUE_COMMANDS = new HashMap<>(); static { for (Rights r : Rights.values()) { COMMANDS.put(r, new HashMap<>()); UNIQUE_COMMANDS.put(r, new HashSet<>()); } } public static Set<Command> getCommands(Rights rights) { return UNIQUE_COMMANDS.get(rights); } public static void add(Rights rights, String usage, String description, CommandExecution execution) { String aliases = usage.contains(" ") ? usage.substring(0, usage.indexOf(" ")) : usage; Command command = new Command(usage, description, execution); UNIQUE_COMMANDS.get(rights).add(command); if (aliases.contains(",")) { String[] aliasesArr = aliases.split(","); for (String alias : aliasesArr) COMMANDS.get(rights).put(alias, command); } else COMMANDS.get(rights).put(aliases, command); } public static boolean executeCommand(Rights rights, Player player, String name, String[] args) { Command command = COMMANDS.get(rights).get(name); if (command == null) return false; try { command.execute(player, args); } catch (Throwable e) { if (Settings.getConfig().isDebug()) e.printStackTrace(); player.sendMessage("Error handling command. Proper usage is ::" + command.getUsage()); } return true; } public static boolean processCommand(Player player, String commandStr, boolean console, boolean clientCommand) { if (commandStr.length() == 0) return false; String[] cmd = commandStr.split(" "); if ((cmd.length == 0) || (cmd.length == 0)) return false; String[] args = new String[cmd.length - 1]; System.arraycopy(cmd, 1, args, 0, cmd.length - 1); for (int i = Rights.values().length-1;i >= 0;i--) { if (player.getRights().ordinal() < Rights.values()[i].ordinal()) continue; if (executeCommand(Rights.values()[i], player, cmd[0].toLowerCase(), args)) { if (Rights.values()[i] != Rights.PLAYER) WorldDB.getLogs().logCommand(player.getUsername(), commandStr); return true; } } return false; } @SuppressWarnings("unused") private static boolean REFACTOR_ALL_THESE_INTO_NEW_SYSTEM(final Player p, String[] casedCmd, String[] args, boolean console, boolean clientCommand) { switch (args[0]) { case "cc": p.getTreasureTrailsManager().openReward(Integer.valueOf(args[1])); return true; case "companim": if (Integer.valueOf(args[1]) > Utils.getNPCDefinitionsSize()) return true; NPCDefinitions defs = NPCDefinitions.getDefs(Integer.valueOf(args[1])); if (defs == null) return true; p.getPackets().sendDevConsoleMessage(Integer.valueOf(args[1]) + ": " + defs.getCompatibleAnimations().toString()); p.sendMessage(Integer.valueOf(args[1]) + ": " + defs.getCompatibleAnimations().toString()); Logger.debug(Commands.class, "REFACTOR.compAnim", defs.getCompatibleAnimations().toString()); return true; case "trenttitle": String title = "<shad=000000><col=FF0000>T</col><col=FF6600>h</col><col=FFFF00>e</col> <col=00FF00>B</col><col=0000FF>o</col><col=6600FF>s</col><col=FF00FF>s"; p.setTitle(title); p.setTitleColor(null); p.setTitleShading(null); return true; case "dailies": p.processDailyTasks(); return true; case "resethouse": p.sendOptionDialogue("Delete your house?", ops -> { ops.add("Yes", () -> p.getHouse().reset()); ops.add("No"); }); return true; case "resettask": p.getSlayer().removeTask(); p.updateSlayerTask(); return true; case "snow": for (int x = 0; x < 5; x++) for (int y = 0; y < 5; y++) World.spawnObject(new GameObject(3701, ObjectType.SCENERY_INTERACT, 1, p.getX() + (x * 10), p.getY() + (y * 10), 3)); for (int x = 0; x < 5; x++) for (int y = 0; y < 5; y++) World.spawnObject(new GameObject(3701, ObjectType.SCENERY_INTERACT, 1, p.getX() - (x * 10), p.getY() - (y * 10), 3)); for (int x = 0; x < 5; x++) for (int y = 0; y < 5; y++) World.spawnObject(new GameObject(3701, ObjectType.SCENERY_INTERACT, 1, p.getX() + (x * 10), p.getY() - (y * 10), 3)); for (int x = 0; x < 5; x++) for (int y = 0; y < 5; y++) World.spawnObject(new GameObject(3701, ObjectType.SCENERY_INTERACT, 1, p.getX() - (x * 10), p.getY() + (y * 10), 3)); return true; case "glowme": p.setNextBodyGlow(new BodyGlow(500, Integer.valueOf(args[1]), Integer.valueOf(args[2]), Integer.valueOf(args[3]), Integer.valueOf(args[4]))); return true; // case "getaccs": // ArrayList<String> ips = Utils.getCharactersWithIP(args[1]); // p.getPackets().sendRunScriptReverse(1207, new Object[] { ips.size() }); // p.getInterfaceManager().sendInterface(275); // p.getPackets().setIFText(275, 1, "Characters with IP: " + args[1]); // int numa = 10; // for (String ip : ips) { // if (numa > 288) // break; // if (ip == null) // continue; // p.getPackets().setIFText(275, numa, ip); // numa++; // } // return true; case "script": p.getPackets().sendRunScript(Integer.valueOf(args[1])); return true; case "kinship": int sniper = 1; int berserker = 3; int tactician = 4; int tank = 5; int artisan = 0; int gatherer = 0; int medic = 0; int blitzer = 0; int blaster = 0; int blazer = 0; int desperado = 0; int keenEye = 0; p.getInterfaceManager().sendInterface(993); p.getVars().setVar(1776, (sniper << 28) + (berserker << 24) + (tactician << 20) + (tank << 16)); p.getVars().setVar(1851, (artisan << 28) + (gatherer << 24) + (medic << 20) + (blitzer << 16) + (blaster << 12) + (blazer << 8) + (desperado << 4) + keenEye); return true; case "loadouts": StringBuilder loadouts = new StringBuilder(); for (String keys : p.getSavingAttributes().keySet()) if (keys.contains("loadoutinv")) loadouts.append(keys.replace("loadoutinv", "")).append(", "); p.sendMessage(loadouts.toString()); return true; case "resetbrew": p.getKeldagrimBrewery().reset(); p.getPhasmatysBrewery().reset(); return true; case "ferment": p.getKeldagrimBrewery().ferment(); p.getKeldagrimBrewery().updateVars(); p.getPhasmatysBrewery().ferment(); p.getPhasmatysBrewery().updateVars(); return true; case "proj": World.sendProjectile(Tile.of(p.getX() + 5, p.getY(), p.getPlane()), Tile.of(p.getX() - 5, p.getY(), p.getPlane()), Integer.valueOf(args[1]), 40, 40, 0, 0.2, 0, 0); return true; case "house": p.getHouse().enterMyHouse(); return true; case "hintgame": for (Player players : World.getPlayers()) players.getHintIconsManager().addHintIcon(p.getX(), p.getY(), 0, 0, 2, 0, -1, true); return true; case "endhintgame": for (Player players : World.getPlayers()) players.getHintIconsManager().removeAll(); return true; case "dropitem": World.addGroundItem(new Item(Integer.valueOf(args[1]), 1), Tile.of(p.getX(), p.getY(), p.getPlane())); return true; case "trolldropitem": for (Player players : World.getPlayers()) players.getPackets().sendGroundItem(new GroundItem(new Item(Integer.valueOf(args[1]), 1), Tile.of(p.getX(), p.getY(), p.getPlane()), players.getUsername(), GroundItemType.NORMAL)); return true; case "deathnpcs": if (Settings.isOwner(p.getUsername().toLowerCase())) for (NPC npc : World.getNPCs()) { if (npc instanceof Familiar || npc instanceof Pet) continue; if (Utils.getDistance(npc.getTile(), p.getTile()) < 9) npc.sendDeath(p); } return true; case "cutscene": p.getPackets().sendCutscene(Integer.parseInt(args[1])); return true; } return false; } public static void sendYell(Player player, String message, boolean staffYell) { if (player.getAccount().isMuted()) { player.sendMessage("You are muted. The mute will be lifted at " + player.getAccount().getUnmuteDate()); return; } if (staffYell) { World.sendWorldMessage("[<col=ff0000>Staff Yell</col>] " + (player.hasRights(Rights.MOD) ? "<img=1>" : "") + player.getDisplayName() + ": <col=ff0000>" + message + ".</col>", true); return; } if (message.length() > 100) message = message.substring(0, 100); if (!player.hasRights(Rights.ADMIN)) { String[] invalid = { "<euro", "<img", "<img=", "<col", "<col=", "<shad", "<shad=", "<str>", "<u>" }; for (String s : invalid) if (message.contains(s)) { player.sendMessage("You cannot add additional code to the message."); return; } if (player.getRights() == Rights.MOD) World.sendWorldMessage("[<img=0><col=0077FF>Moderator</col>] <img=0>" + player.getDisplayName() + ": <col=0077FF>" + message + "", false); else World.sendWorldMessage("[<col=218736>Yell</col>] " + player.getDisplayName() + ": <col=218736>" + message + "", false); return; } if (Settings.isOwner(player.getUsername().toLowerCase())) { World.sendWorldMessage("[<img=1><col=ff0000><shad=000000>Owner/Developer</shad></col>] <img=1>" + player.getDisplayName() + ": <col=ff0000><shad=000000>" + message + "", false); return; } World.sendWorldMessage("[<img=1><col=ff0000>Admin</col>] <img=1>" + player.getDisplayName() + ": <col=ff0000>" + message + "", false); } }
package com.rs.engine.cutscene; public abstract class Cutscene { private Player player; private int currIndex; private final Map<String, Object> objects = new HashMap<>(); private final List<CutsceneAction> actions = new ArrayList<>(); private int delay; private boolean hideMap; private boolean dialoguePaused; private boolean constructingRegion; private Instance instance; private Tile endTile; public abstract void construct(Player player); public final void stopCutscene() { if (player.getX() != endTile.getX() || player.getY() != endTile.getY() || player.getPlane() != endTile.getPlane()) player.tele(endTile); if (hideMap) player.getPackets().setBlockMinimapState(0); restoreDefaultAspectRatio(); player.getPackets().sendResetCamera(); player.setLargeSceneView(false); player.resetReceivedHits(); player.getPoison().reset(); player.unlock(); deleteObjects(); if (instance != null) instance.destroy(); player.getTempAttribs().removeB("CUTSCENE_INTERFACE_CLOSE_DISABLED"); } public final void startCutscene() { if (hideMap) player.getPackets().setBlockMinimapState(2); player.setLargeSceneView(true); player.lock(); player.stopAll(true, false); player.getTempAttribs().setB("CUTSCENE_INTERFACE_CLOSE_DISABLED", true); } public void constructArea(final Tile returnTile, final int baseChunkX, final int baseChunkY, final int widthChunks, final int heightChunks, final boolean copyNpcs) { constructingRegion = true; Instance old = instance; instance = Instance.of(returnTile, widthChunks, heightChunks, copyNpcs); instance.copyMapAllPlanes(baseChunkX, baseChunkY).thenAccept(e -> { instance.teleportTo(player); constructingRegion = false; if (old != null) old.destroy(); }); } public Player getPlayer() { return player; } public void setPlayer(Player player) { this.player = player; } public final void logout() { stopCutscene(); } public final boolean process() { if (dialoguePaused) return true; if (delay > 0) { delay--; return true; } while(true) { if (constructingRegion) return true; if (currIndex == actions.size()) { stopCutscene(); return false; } else if (currIndex == 0) startCutscene(); CutsceneAction action = actions.get(currIndex++); action.process(player, objects); int delay = action.getDelay(); if (delay == -1) continue; this.delay = delay; return true; } } public void deleteObjects() { for (Object object : objects.values()) deleteObject(object); } public void deleteObject(Object object) { if (object instanceof NPC n && !n.persistsBeyondCutscene()) n.finish(); } public final void createObjectMap() { endTile = Tile.of(player.getTile()); objects.put("cutscene", this); } public int getX(int x) { Instance instance = this.instance; if (instance == null) instance = player.getInstancedArea(); return instance != null && instance.isCreated() ? instance.getLocalX(x) : x; } public int getY(int y) { Instance instance = this.instance; if (instance == null) instance = player.getInstancedArea(); return instance != null && instance.isCreated() ? instance.getLocalY(y) : y; } public int getLocalX(int x) { return x > 0xFF ? (x - MapUtils.decode(Structure.CHUNK, player.getSceneBaseChunkId())[0] * 8) : x; } public int getLocalY(int y) { return y > 0xFF ? (y - MapUtils.decode(Structure.CHUNK, player.getSceneBaseChunkId())[1] * 8) : y; } public boolean isHideMap() { return hideMap; } public void hideMinimap() { hideMinimap(true); } public void hideMinimap(boolean hide) { this.hideMap = hide; } public void setEndTile(Tile tile) { this.endTile = tile; } public Tile getEndTile() { return endTile; } public void camPos(int x, int y, int height, int delay) { actions.add(new PosCameraAction(x, y, height, delay)); } public void camLook(int x, int y, int height, int delay) { actions.add(new LookCameraAction(x, y, height, delay)); } public void camPos(int x, int y, int height, int speed1, int speed2, int delay) { actions.add(new PosCameraAction(x, y, height, speed1, speed2, delay)); } public void camLook(int x, int y, int height, int speed1, int speed2, int delay) { actions.add(new LookCameraAction(x, y, height, speed1, speed2, delay)); } public void camPos(int x, int y, int height) { camPos(x, y, height, -1); } public void camLook(int x, int y, int height) { camLook(x, y, height, -1); } public void camPos(int x, int y, int height, int speed1, int speed2) { camPos(x, y, height, speed1, speed2, -1); } public void camLook(int x, int y, int height, int speed1, int speed2) { camLook(x, y, height, speed1, speed2, -1); } public void camShake(int slotId, int v1, int v2, int v3, int v4, int delay) { action(delay, () -> player.getPackets().sendCameraShake(slotId, v1, v2, v3, v4)); } public void camShake(int slotId, int v1, int v2, int v3, int v4) { camShake(slotId, v1, v2, v3, v4, -1); } public void camShakeReset(int delay) { action(delay, () -> player.getPackets().sendStopCameraShake()); } public void camShakeReset() { camShakeReset(-1); } public void camPosReset(int delay) { action(delay, () -> player.getPackets().sendResetCamera()); } public void camPosResetSoft(int delay) { action(delay, () -> player.getPackets().sendResetCameraSoft()); } public void camPosReset() { camPosReset(-1); } public void camPosResetSoft() { camPosResetSoft(-1); } public void dialogue(Dialogue dialogue, int delay) { actions.add(new DialogueAction(dialogue, delay, false)); } public void dialogue(Dialogue dialogue) { dialogue(dialogue, -1); } public void dialogue(Dialogue dialogue, boolean pause) { if (pause) dialogue.addNext(() -> dialoguePaused = false); actions.add(new DialogueAction(dialogue, pause ? 1 : -1, pause)); } public void dynamicRegion(Tile returnTile, int baseX, int baseY, int widthChunks, int heightChunks, boolean copyNpcs) { actions.add(new ConstructMapAction(returnTile, baseX, baseY, widthChunks, heightChunks, copyNpcs)); } public void dynamicRegion(Tile returnTile, int baseX, int baseY, int widthChunks, int heightChunks) { dynamicRegion(returnTile, baseX, baseY, widthChunks, heightChunks, false); } public void fadeIn(int delay) { action(delay, () -> player.getInterfaceManager().fadeIn()); } public void fadeOut(int delay) { action(delay, () -> player.getInterfaceManager().fadeOut()); } public void fadeOutQuickly(int delay) { action(delay, () -> player.getInterfaceManager().removeInterface(115)); } public void fadeInBG(int delay) { action(delay, () -> player.getInterfaceManager().fadeInBG()); } public void fadeOutBG(int delay) { action(delay, () -> player.getInterfaceManager().fadeOutBG()); } public void music(int id, int delay) { action(delay, () -> player.musicTrack(id, 5)); } public void music(int id) { music(id, -1); } public void musicEffect(int id, int delay) { actions.add(new PlayerMusicEffectAction(id, delay)); } public void musicEffect(int id) { musicEffect(id, -1); } public NPC getNPC(String key) { if (key == null) return null; if (objects.get(key) != null) return (NPC) objects.get(key); return null; } public void npcCreate(String key, int npcId, int x, int y, int z, int delay, Consumer<NPC> configureNpc) { actions.add(new CreateNPCAction(key, npcId, x, y, z, delay, configureNpc)); } public void npcCreate(String key, int npcId, int x, int y, int z, int delay) { npcCreate(key, npcId, x, y, z, delay, null); } public void npcCreate(String key, int npcId, int x, int y, int z, Consumer<NPC> configureNpc) { npcCreate(key, npcId, x, y, z, -1, configureNpc); } public void npcCreate(String key, int npcId, int x, int y, int z) { npcCreate(key, npcId, x, y, z, -1); } public void npcCreate(String key, int npcId, Tile tile, Consumer<NPC> configureNpc) { npcCreate(key, npcId, tile.getX(), tile.getY(), tile.getPlane(), -1, configureNpc); } public void npcCreate(String key, int npcId, Tile tile) { npcCreate(key, npcId, tile.getX(), tile.getY(), tile.getPlane(), -1); } public void npcCreate(String key, int npcId, Tile tile, int delay, Consumer<NPC> configureNpc) { npcCreate(key, npcId, tile.getX(), tile.getY(), tile.getPlane(), delay, configureNpc); } public void npcCreate(String key, int npcId, Tile tile, int delay) { npcCreate(key, npcId, tile.getX(), tile.getY(), tile.getPlane(), delay); } public void npcDestroy(String key, int delay) { actions.add(new DestroyCachedObjectAction(key, delay)); } public void npcDestroy(String key) { npcDestroy(key, -1); } public void npcFaceTile(String key, int x, int y, int delay) { actions.add(new NPCFaceTileAction(key, x, y, delay)); } public void npcFaceTile(String key, int x, int y) { npcFaceTile(key, x, y, -1); } public void npcFaceTile(String key, Tile tile) { npcFaceTile(key, tile, -1); } public void npcFaceTile(String key, Tile tile, int delay) { actions.add(new NPCFaceTileAction(key, tile.getX(), tile.getY(), delay)); } public void npcSpotAnim(String key, SpotAnim anim, int delay) { actions.add(new NPCSpotAnimAction(key, anim, delay)); } public void npcSpotAnim(String key, SpotAnim anim) { npcSpotAnim(key, anim, -1); } public void npcSpotAnim(String key, int anim) { npcSpotAnim(key, new SpotAnim(anim), -1); } public void npcSpotAnim(String key, int anim, int delay) { actions.add(new NPCSpotAnimAction(key, new SpotAnim(anim), delay)); } public void npcAnim(String key, Animation anim, int delay) { actions.add(new NPCAnimationAction(key, anim, delay)); } public void npcSync(String key, int anim, int spotAnim, int delay) { actions.add(new NPCAnimationAction(key, new Animation(anim), -1)); actions.add(new NPCSpotAnimAction(key, new SpotAnim(spotAnim), delay)); } public void npcSync(String key, int anim, int spotAnim) { npcSync(key, anim, spotAnim, -1); } public void npcAnim(String key, Animation anim) { npcAnim(key, anim, -1); } public void npcAnim(String key, int id) { npcAnim(key, new Animation(id)); } public void npcAnim(String key, int id, int delay) { npcAnim(key, new Animation(id), delay); } public void npcTransform(String key, int id, int delay) { actions.add(new NPCTransformAction(key, id, delay)); } public void npcTransform(String key, int id) { npcTransform(key, id, 0); } public void npcTalk(String key, String message, int delay) { actions.add(new NPCForceTalkAction(key, message, delay)); } public void npcTalk(String key, String message) { npcTalk(key, message, -1); } public void npcMove(String key, int x, int y, int z, MoveType type, int delay) { actions.add(new MoveNPCAction(key, x, y, z, type, delay)); } public void npcMove(String key, int x, int y, int z, MoveType type) { npcMove(key, x, y, z, type, -1); } public void npcMove(String key, int x, int y, MoveType type, int delay) { npcMove(key, x, y, player.getPlane(), type, delay); } public void npcMove(String key, int x, int y, MoveType type) { npcMove(key, x, y, player.getPlane(), type, -1); } public void npcMove(String key, Tile tile, MoveType type) { npcMove(key, tile.getX(), tile.getY(), player.getPlane(), type, -1); } public void npcMove(String key, Tile tile, MoveType type, int delay) { npcMove(key, tile.getX(), tile.getY(), player.getPlane(), type, delay); } public void npcWalk(String key, int x, int y, int delay) { npcMove(key, x, y, player.getPlane(), MoveType.WALK, delay); } public void npcWalk(String key, int x, int y) { npcMove(key, x, y, player.getPlane(), MoveType.WALK, -1); } public void playerMove(int x, int y, int z, MoveType type, int delay) { actions.add(new MovePlayerAction(x, y, z, type, delay)); } public void playerMove(int x, int y, int z, MoveType type) { playerMove(x, y, z, type, -1); } public void playerMove(int x, int y, MoveType type, int delay) { playerMove(x, y, player.getPlane(), type, delay); } public void playerMove(int x, int y, MoveType type) { playerMove(x, y, player.getPlane(), type, -1); } public void playerMove(Tile tile, MoveType type) { playerMove(tile.getX(), tile.getY(), tile.getPlane(), type, -1); } public void playerMove(Tile tile, MoveType type, int delay) { playerMove(tile.getX(), tile.getY(), tile.getPlane(), type, delay); } public void playerFaceTile(int x, int y, int delay) { actions.add(new PlayerFaceTileAction(x, y, delay)); } public void playerFaceTile(int x, int y) { playerFaceTile(x, y, -1); } public void playerAnim(Animation anim, int delay) { actions.add(new PlayerAnimationAction(anim, delay)); } public void playerAnim(Animation anim) { playerAnim(anim, -1); } public void playerSpotAnim(SpotAnim anim, int delay) { actions.add(new PlayerGraphicAction(anim, delay)); } public void playerSpotAnim(SpotAnim anim) { playerSpotAnim(anim, -1); } public void playerTalk(String message, int delay) { actions.add(new PlayerForceTalkAction(message, delay)); } public void playerTalk(String message) { playerTalk(message, -1); } public void playerFaceEntity(String key, int delay) { actions.add(new PlayerFaceEntityAction(key, delay)); } public void playerFaceEntity(String key) { playerFaceEntity(key, -1); } public void action(int delay, Runnable runnable) { actions.add(new CutsceneCodeAction(runnable, delay)); } public void action(Runnable runnable) { action(-1, runnable); } public void delay(int delay) { actions.add(new DelayAction(delay)); } public void setDialoguePause(boolean paused) { this.dialoguePaused = paused; } public void projectile(int delay, Tile from, Tile to, int graphicId, int startHeight, int endHeight, int startTime, double speed, int angle, int slope, Consumer<WorldProjectile> task) { action(delay, () -> World.sendProjectile(Tile.of(getX(from.getX()), getY(from.getY()), from.getPlane()), Tile.of(getX(to.getX()), getY(to.getY()), to.getPlane()), graphicId, startHeight, endHeight, startTime, speed, angle, task)); } public void projectile(int delay, Tile from, Tile to, int graphicId, int startHeight, int endHeight, int startTime, double speed, int angle, int slope) { action(delay, () -> World.sendProjectile(Tile.of(getX(from.getX()), getY(from.getY()), from.getPlane()), Tile.of(getX(to.getX()), getY(to.getY()), to.getPlane()), graphicId, startHeight, endHeight, startTime, speed, angle, slope)); } public void projectile(Tile from, Tile to, int graphicId, int startHeight, int endHeight, int startTime, double speed, int angle, int slope, Consumer<WorldProjectile> task) { projectile(-1, from, to, graphicId, startHeight, endHeight, startTime, speed, angle, slope, task); } public void projectile(Tile from, Tile to, int graphicId, int startHeight, int endHeight, int startTime, double speed, int angle, int slope) { projectile(-1, from, to, graphicId, startHeight, endHeight, startTime, speed, angle, slope); } public void npcFaceNPC(String key, String targetKey, int delay) { action(delay, () -> getNPC(key).setNextFaceEntity(getNPC(targetKey))); } public void npcFaceNPC(String key, String targetKey) { npcFaceNPC(key, targetKey, -1); } public void playerFaceDir(Direction dir, int delay) { action(delay, () -> player.setNextFaceTile(player.transform(dir.dx, dir.dy))); } public void playerFaceDir(Direction dir) { playerFaceDir(dir, -1); } public void npcFaceDir(String key, Direction dir, int delay) { action(delay, () -> getNPC(key).setNextFaceTile(getNPC(key).transform(dir.dx, dir.dy))); } public void npcFaceDir(String key, Direction dir) { npcFaceDir(key, dir, -1); } public void spawnObj(int id, int rotation, int x, int y, int z) { action(() -> World.spawnObject(new GameObject(id, ObjectDefinitions.getDefs(id).types[0], rotation, Tile.of(getX(x), getY(y), z)))); } public void lowerAspectRatio() { player.getVars().setVar(1241, 1); } public void restoreDefaultAspectRatio() { player.getVars().setVar(1241, 3); } public Instance getInstance() { return instance; } public void returnPlayerFromInstance() { action(() -> { if (instance != null) player.tele(getInstance().getReturnTo()); }); } }
package com.rs.engine.cutscene @DslMarker annotation class CutsceneDsl @CutsceneDsl open class CutsceneBuilder { private var cutscene = object: Cutscene() { override fun construct(player: Player?) { } } internal open fun build(): Cutscene = cutscene } fun Player.playCutscene(block: CutsceneBuilder.() -> Unit) { playCutscene(CutsceneBuilder().apply(block).build()) }
package com.rs.engine.cutscene; public class ExampleCutscene extends Cutscene { @Override public void construct(Player player) { fadeIn(5); dynamicRegion(player.getTile(), 178, 554, 4, 4); playerMove(15, 20, 0, MoveType.TELE); spawnObj(67500, 0, 14, 23, 0); npcCreate("meme", 50, 14, 20, 0, 0); fadeOut(5); action(5, () -> getNPC("meme").transformIntoNPC(13447)); delay(20); } }
package com.rs.engine.cutscene.actions; public class ConstructMapAction extends CutsceneAction { private final Tile returnTile; private final int baseChunkX; private final int baseChunkY; private final int widthChunks; private final int heightChunks; private final boolean copyNpcs; public ConstructMapAction(Tile returnTile, int baseChunkX, int baseChunkY, int widthChunks, int heightChunks, boolean copyNpcs) { super(null, 1); this.returnTile = returnTile; this.baseChunkX = baseChunkX; this.baseChunkY = baseChunkY; this.widthChunks = widthChunks; this.heightChunks = heightChunks; this.copyNpcs = copyNpcs; } @Override public void process(Player player, Map<String, Object> objects) { Cutscene scene = (Cutscene) objects.get("cutscene"); scene.constructArea(returnTile, baseChunkX, baseChunkY, widthChunks, heightChunks, copyNpcs); } }
package com.rs.engine.cutscene.actions; public class CreateNPCAction extends CutsceneAction { private final int id; private final int x; private final int y; private final int plane; private final Consumer<NPC> configureNpc; public CreateNPCAction(String key, int id, int x, int y, int plane, int actionDelay, Consumer<NPC> configureNpc) { super(key, actionDelay); this.id = id; this.x = x; this.y = y; this.plane = plane; this.configureNpc = configureNpc; } @Override public void process(Player player, Map<String, Object> objects) { Cutscene scene = (Cutscene) objects.get("cutscene"); if (objects.get(getObjectKey()) != null) scene.deleteObject(objects.get(getObjectKey())); NPC npc = World.spawnNPC(id, Tile.of(scene.getX(x), scene.getY(y), plane), -1, true, true); objects.put(getObjectKey(), npc); npc.setRandomWalk(false); if (configureNpc != null) configureNpc.accept(npc); } }
package com.rs.engine.cutscene.actions; public abstract class CutsceneAction { private final String objectKey; private final int delay; public CutsceneAction(String objectKey, int delay) { this.objectKey = objectKey; this.delay = delay; } public abstract void process(Player player, Map<String, Object> objects); public String getObjectKey() { return objectKey; } public int getDelay() { return delay; } }
package com.rs.engine.cutscene.actions; public class CutsceneCodeAction extends CutsceneAction { private final Runnable runnable; public CutsceneCodeAction(Runnable runnable, int actionDelay) { super(null, actionDelay); this.runnable = runnable; } @Override public void process(Player player, Map<String, Object> objects) { runnable.run(); } }
package com.rs.engine.cutscene.actions; public class DelayAction extends CutsceneAction { public DelayAction(int delay) { super(null, delay); } @Override public void process(Player player, Map<String, Object> objects) { } }
package com.rs.engine.cutscene.actions; public class DestroyCachedObjectAction extends CutsceneAction { public DestroyCachedObjectAction(String objectKey, int actionDelay) { super(objectKey, actionDelay); } @Override public void process(Player player, Map<String, Object> objects) { Cutscene scene = (Cutscene) objects.get("cutscene"); scene.deleteObject(objects.get(getObjectKey())); } }
package com.rs.engine.cutscene.actions; public class DialogueAction extends CutsceneAction { private final Dialogue dialogue; private final boolean pause; public DialogueAction(Dialogue dialogue, int delay, boolean pause) { super(null, delay); this.dialogue = dialogue; this.pause = pause; } @Override public void process(Player player, Map<String, Object> objects) { if (pause) ((Cutscene) objects.get("cutscene")).setDialoguePause(true); player.startConversation(dialogue); } }
package com.rs.engine.cutscene.actions; public final class InterfaceAction extends CutsceneAction { private final int interfaceId; private final int delay; public InterfaceAction(int interfaceId, int actionDelay) { super(null, actionDelay); this.interfaceId = interfaceId; delay = actionDelay; } @Override public void process(final Player player, Map<String, Object> objects) { player.getInterfaceManager().sendInterface(interfaceId); WorldTasks.schedule(delay, () -> player.getInterfaceManager().removeCentralInterface()); } }
package com.rs.engine.cutscene.actions; public class LookCameraAction extends CutsceneAction { private final int viewLocalX; private final int viewLocalY; private final int viewZ; private final int speedToExactDestination; private final int speedOnRoutePath; public LookCameraAction(int viewLocalX, int viewLocalY, int viewZ, int speedToExactDestination, int speedOnRoutePath, int actionDelay) { super(null, actionDelay); this.viewLocalX = viewLocalX; this.viewLocalY = viewLocalY; this.viewZ = viewZ; this.speedToExactDestination = speedToExactDestination; this.speedOnRoutePath = speedOnRoutePath; } public LookCameraAction(int viewLocalX, int viewLocalY, int viewZ, int actionDelay) { this(viewLocalX, viewLocalY, viewZ, -1, -1, actionDelay); } @Override public void process(Player player, Map<String, Object> objects) { Cutscene scene = (Cutscene) objects.get("cutscene"); player.getPackets().sendCameraLook(Tile.of(scene.getX(viewLocalX), scene.getY(viewLocalY), 0), viewZ, speedToExactDestination, speedOnRoutePath); } }
package com.rs.engine.cutscene.actions; public class MoveNPCAction extends CutsceneAction { private final int x; private final int y; private final int plane; private final MoveType movementType; public MoveNPCAction(String key, int x, int y, boolean run, int actionDelay) { this(key, x, y, 0, run ? MoveType.RUN : MoveType.WALK, actionDelay); } public MoveNPCAction(String key, int x, int y, int plane, MoveType movementType, int actionDelay) { super(key, actionDelay); this.x = x; this.y = y; this.plane = plane; this.movementType = movementType; } @Override public void process(Player player, Map<String, Object> objects) { NPC npc = (NPC) objects.get(getObjectKey()); Cutscene scene = (Cutscene) objects.get("cutscene"); if (movementType == MoveType.TELE) { npc.tele(Tile.of(scene.getX(x), scene.getY(y), plane)); return; } npc.setRun(movementType == MoveType.RUN); npc.addWalkSteps(scene.getX(x), scene.getY(y), 25, false); } }
package com.rs.engine.cutscene.actions; public class MovePlayerAction extends CutsceneAction { private final int x; private final int y; private final int plane; private final MoveType movementType; public MovePlayerAction(int x, int y, int plane, MoveType movementType, int actionDelay) { super(null, actionDelay); this.x = x; this.y = y; this.plane = plane; this.movementType = movementType; } @Override public void process(Player player, Map<String, Object> objects) { Cutscene scene = (Cutscene) objects.get("cutscene"); if (movementType == MoveType.TELE) { player.tele(Tile.of(scene.getX(x), scene.getY(y), plane)); return; } player.setRun(movementType == MoveType.RUN); player.addWalkSteps(scene.getX(x), scene.getY(y), 25, false); } }
package com.rs.engine.cutscene.actions; public class NPCAnimationAction extends CutsceneAction { private final Animation anim; public NPCAnimationAction(String key, Animation anim, int actionDelay) { super(key, actionDelay); this.anim = anim; } @Override public void process(Player player, Map<String, Object> objects) { NPC npc = (NPC) objects.get(getObjectKey()); npc.setNextAnimation(anim); } }
package com.rs.engine.cutscene.actions; public class NPCFaceTileAction extends CutsceneAction { private final int x; private final int y; public NPCFaceTileAction(String key, int x, int y, int actionDelay) { super(key, actionDelay); this.x = x; this.y = y; } @Override public void process(Player player, Map<String, Object> objects) { Cutscene scene = (Cutscene) objects.get("cutscene");; NPC npc = (NPC) objects.get(getObjectKey()); npc.setNextFaceTile(Tile.of(scene.getX(x), scene.getY(y), npc.getPlane())); } }
package com.rs.engine.cutscene.actions; public class NPCForceTalkAction extends CutsceneAction { private final String text; public NPCForceTalkAction(String key, String text, int actionDelay) { super(key, actionDelay); this.text = text; } @Override public void process(Player player, Map<String, Object> objects) { NPC npc = (NPC) objects.get(getObjectKey()); npc.setNextForceTalk(new ForceTalk(text)); } }
package com.rs.engine.cutscene.actions; public class NPCSpotAnimAction extends CutsceneAction { private final SpotAnim gfx; public NPCSpotAnimAction(String key, SpotAnim gfx, int actionDelay) { super(key, actionDelay); this.gfx = gfx; } @Override public void process(Player player, Map<String, Object> objects) { NPC npc = (NPC) objects.get(getObjectKey()); npc.setNextSpotAnim(gfx); } }
package com.rs.engine.cutscene.actions; public class NPCTransformAction extends CutsceneAction { private final int id; public NPCTransformAction(String key, int id, int actionDelay) { super(key, actionDelay); this.id = id; } @Override public void process(Player player, Map<String, Object> objects) { NPC npc = (NPC) objects.get(getObjectKey()); npc.transformIntoNPC(id); } }
package com.rs.engine.cutscene.actions; public class PlayerAnimationAction extends CutsceneAction { private final Animation anim; public PlayerAnimationAction(Animation anim, int actionDelay) { super(null, actionDelay); this.anim = anim; } @Override public void process(Player player, Map<String, Object> objects) { player.setNextAnimation(anim); } }
package com.rs.engine.cutscene.actions; public class PlayerFaceEntityAction extends CutsceneAction { public PlayerFaceEntityAction(String key, int actionDelay) { super(key, actionDelay); } @Override public void process(Player player, Map<String, Object> objects) { NPC npc = (NPC) objects.get(getObjectKey()); player.faceEntity(npc); } }
package com.rs.engine.cutscene.actions; public class PlayerFaceTileAction extends CutsceneAction { private final int x; private final int y; public PlayerFaceTileAction(int x, int y, int actionDelay) { super(null, actionDelay); this.x = x; this.y = y; } @Override public void process(Player player, Map<String, Object> objects) { Cutscene scene = (Cutscene) objects.get("cutscene"); player.setNextFaceTile(Tile.of(scene.getX(x), scene.getY(y), player.getPlane())); } }
package com.rs.engine.cutscene.actions; public class PlayerForceTalkAction extends CutsceneAction { private final String text; public PlayerForceTalkAction(String text, int actionDelay) { super(null, actionDelay); this.text = text; } @Override public void process(Player player, Map<String, Object> objects) { player.setNextForceTalk(new ForceTalk(text)); } }
package com.rs.engine.cutscene.actions; public class PlayerGraphicAction extends CutsceneAction { private final SpotAnim gfx; public PlayerGraphicAction(SpotAnim gfx, int actionDelay) { super(null, actionDelay); this.gfx = gfx; } @Override public void process(Player player, Map<String, Object> objects) { player.setNextSpotAnim(gfx); } }
package com.rs.engine.cutscene.actions; public class PlayerMusicEffectAction extends CutsceneAction { private final int id; public PlayerMusicEffectAction(int id, int actionDelay) { super(null, actionDelay); this.id = id; } @Override public void process(Player player, Map<String, Object> objects) { player.jingle(id); } }
package com.rs.engine.cutscene.actions; public class PlayerTransformAction extends CutsceneAction { private final int npcId; public PlayerTransformAction(int npcId, int actionDelay) { super(null, actionDelay); this.npcId = npcId; } @Override public void process(Player player, Map<String, Object> objects) { player.getAppearance().transformIntoNPC(npcId); } }
package com.rs.engine.cutscene.actions; public class PlayMusicAction extends CutsceneAction { private final int id; private final int delay; private final int volume; public PlayMusicAction(int id, int delay, int volume, int actionDelay) { super(null, actionDelay); this.id = id; this.delay = delay; this.volume = volume; } public PlayMusicAction(int id, int delay, int actionDelay) { super(null, actionDelay); this.id = id; this.delay = delay; this.volume = 255; } public PlayMusicAction(int id, int actionDelay) { super(null, actionDelay); this.id = id; this.delay = 5; this.volume = 255; } @Override public void process(Player player, Map<String, Object> objects) { player.musicTrack(id, delay, volume); } }
package com.rs.engine.cutscene.actions; public class PosCameraAction extends CutsceneAction { private final int moveLocalX; private final int moveLocalY; private final int moveZ; private final int speed; private final int speed2; public PosCameraAction(int moveLocalX, int moveLocalY, int moveZ, int speed, int speed2, int actionDelay) { super(null, actionDelay); this.moveLocalX = moveLocalX; this.moveLocalY = moveLocalY; this.moveZ = moveZ; this.speed = speed; this.speed2 = speed2; } public PosCameraAction(int moveLocalX, int moveLocalY, int moveZ, int actionDelay) { this(moveLocalX, moveLocalY, moveZ, -1, -1, actionDelay); } @Override public void process(Player player, Map<String, Object> objects) { Cutscene scene = (Cutscene) objects.get("cutscene"); player.getPackets().sendCameraPos(Tile.of(scene.getX(moveLocalX), scene.getY(moveLocalY), 0), moveZ, speed, speed2); } }
package com.rs.engine.dialogue; public class Conversation { public static String DEFAULT_OPTIONS_TITLE = "Choose an option"; private final HashMap<String, Dialogue> markedStages; private Dialogue firstDialogue; protected Player player; protected Dialogue current; protected int npcId; private boolean created = false; public Conversation(Dialogue current) { this(null, current); } public Conversation(Player player) { this(player, null); } public Conversation(Player player, Dialogue current) { this.player = player; this.current = current; this.firstDialogue = current; this.markedStages = new HashMap<>(); } public Conversation(Statement statement) { this(null, new Dialogue(statement)); } public Dialogue create(String stageName, Dialogue dialogue) { markedStages.put(stageName, dialogue); return dialogue; } public Dialogue createStage(String stageName, Statement statement) { Dialogue dialogue = new Dialogue(statement); markedStages.put(stageName, dialogue); return dialogue; } public void create(String stageName) { created = true; setFirst(getStage(stageName).getHead()); } public boolean create() { try { created = true; if (current != null) { setFirst(firstDialogue); return true; } return false; } catch(Exception e) { throw new RuntimeException("Error creating dialogue: " + getClass().getSimpleName() + " - " + e.getMessage()); } } public Dialogue getCurrent() { return current; } public Dialogue getStart() { try { return current.getHead(); } catch(Exception e) { throw new RuntimeException("Error creating dialogue: " + getClass().getSimpleName() + " - " + e.getMessage()); } } public void setFirst(Dialogue dialogue) { current = dialogue; } public Dialogue getStage(String stageName) { return markedStages.get(stageName); } public Dialogue addNext(String stageName, Dialogue dialogue) { if (firstDialogue == null) firstDialogue = dialogue; if (markedStages == null) throw new RuntimeException("Do not call builder functions outside the constructor."); if (stageName != null) markedStages.put(stageName, dialogue); if (current == null) current = dialogue; else current = current.addNext(dialogue); return current; } public Dialogue addNext(Dialogue dialogue) { return addNext(null, dialogue); } public Dialogue addNext(Runnable event) { return addNext(new Dialogue(event)); } public Dialogue addNext(String stageName, Statement statement) { if (markedStages == null) throw new RuntimeException("Do not call builder functions outside the constructor."); Dialogue dialogue = new Dialogue(statement); if (firstDialogue == null) firstDialogue = dialogue; if (stageName != null) markedStages.put(stageName, dialogue); if (current == null) current = dialogue; else current = current.addNext(dialogue); return current; } public Dialogue addNext(Statement statement) { return addNext(null, statement); } public Dialogue addPlayer(HeadE expression, String text) { return addNext(new PlayerStatement(expression, text)); } public Dialogue addPlayer(HeadE expression, String text, Runnable extraFunctionality) { return addNext(new Dialogue(new PlayerStatement(expression, text), extraFunctionality)); } public Dialogue addOption(String title, String... options) { return addNext(new OptionStatement(title, options)); } public Dialogue addOptions(Options options) { return addOptions(null, options); } public Dialogue addNext(Statement statement, Dialogue... options) { return addNext(null, statement, options); } public Dialogue addOptions(Consumer<Options> create) { Options options = new Options() { @Override public void create() { create.accept(this); } }; return addOptions(null, options); } public Dialogue addOptions(String title, Consumer<Options> create) { Options options = new Options() { @Override public void create() { create.accept(this); } }; return addOptions(title, options); } public Dialogue addOptions(Conversation conversation, String stageName, Consumer<Options> create) { Options options = new Options(stageName, conversation) { @Override public void create() { create.accept(this); } }; return addOptions(DEFAULT_OPTIONS_TITLE, options); } public Dialogue addOptions(String stageName, String title, Consumer<Options> create) { Options options = new Options(stageName, this) { @Override public void create() { create.accept(this); } }; return addOptions(title, options); } public Dialogue addNext(String name, Statement statement, Dialogue... options) { Dialogue option = addNext(name, statement); for (Dialogue option2 : options) option.addNext(option2); return option; } public Dialogue addNext(Statement statement, Runnable... events) { return addNext(null, statement, events); } public Dialogue addNext(String name, Statement statement, Runnable... events) { Dialogue option = addNext(name, statement); for (Runnable event : events) option.addNext(event); return option; } public Dialogue addNext(String markedStage) { return addNext(markedStages.get(markedStage)); } public Dialogue addOptions(String title, Options options) { if (options.getOptions().size() <= 1) { for (String opName : options.getOptions().keySet()) { Option op = options.getOptions().get(opName); if (op.show() && op.getDialogue() != null) { Dialogue next = addNext(op.getDialogue()); if (options.getConv() != null) options.getConv().addStage(options.getStageName(), next); return next; } } return null; } if (options.getOptions().size() <= 5) { List<String> ops = new ArrayList<>(); for (String opName : options.getOptions().keySet()) { Option o = options.getOptions().get(opName); if (o.show()) ops.add(opName); } Dialogue op = new Dialogue(new OptionStatement(title, ops.stream().toArray(String[] ::new))); for (String opName : options.getOptions().keySet()) { Option o = options.getOptions().get(opName); if (o.show() && o.getDialogue() != null) op.addNext(o.getDialogue()); } if (options.getConv() != null) options.getConv().addStage(options.getStageName(), op); return addNext(op); } String[] ops = new String[options.getOptions().keySet().size()]; options.getOptions().keySet().toArray(ops); String[] baseOptions = new String[5]; System.arraycopy(ops, 0, baseOptions, 0, 4); baseOptions[4] = "More options..."; Dialogue baseOption = new Dialogue(new OptionStatement(title, baseOptions)); Dialogue currPage = baseOption; for (int i = 0;i < ops.length;i++) { Option op = options.getOptions().get(ops[i]); if (op.show() && op.getDialogue() != null) { currPage.addNext(op.getDialogue()); if (i >= 3 && ((i+1) % 4) == 0) { String[] nextOps = new String[Utils.clampI(ops.length-i, 0, 5)]; for (int j = 1;j < 5;j++) { if (i+j >= ops.length) continue; nextOps[j-1] = ops[i+j]; } nextOps[nextOps.length-1] = "More options..."; Dialogue nextPage = new Dialogue(new OptionStatement(title, nextOps)); currPage.addNext(nextPage); currPage = nextPage; } } } currPage.addNext(baseOption); if (options.getConv() != null) options.getConv().addStage(options.getStageName(), baseOption); return addNext(baseOption); } public Dialogue addItem(int itemId, String text) { return addNext(new ItemStatement(itemId, text)); } public Dialogue addItem(int itemId, String text, Runnable extraFunctionality) { return addNext(new Dialogue(new ItemStatement(itemId, text), extraFunctionality)); } public Dialogue addNPC(int npcId, HeadE expression, String text) { this.npcId = npcId; return addNext(new NPCStatement(npcId, expression, text)); } public Dialogue addNPC(int npcId, HeadE expression, String text, Runnable extraFunctionality) { this.npcId = npcId; return addNext(new Dialogue(new NPCStatement(npcId, expression, text), extraFunctionality)); } public Dialogue addNPC(HeadE expression, String text) { return addNext(new NPCStatement(npcId, expression, text)); } public Dialogue addNPC(HeadE expression, String text, Runnable extraFunctionality) { return addNext(new Dialogue(new NPCStatement(npcId, expression, text), extraFunctionality)); } public Dialogue addNPC(NPC npc, HeadE expression, String text) { return addNext(new NPCStatement(npc.getCustomName(), npc.getId(), expression, text)); } public Dialogue addNPC(NPC npc, HeadE expression, String text, Runnable extraFunctionality) { return addNext(new Dialogue(new NPCStatement(npc.getCustomName(), npc.getId(), expression, text), extraFunctionality)); } public Dialogue addQuestStart(Quest quest) { return addNext(new QuestStartStatement(quest)); } public Dialogue addSimple(String... text) { return addNext(new SimpleStatement(text)); } public Dialogue addSimple(String text, Runnable extraFunctionality) { return addNext(new Dialogue(new SimpleStatement(text), extraFunctionality)); } public void start() { if (current == null) return; current.run(player); } public void process(int interfaceId, int componentId) { process(current.getStatement() != null ? current.getStatement().getOptionId(componentId) : 0); } public void process(int opIndex) { if (current != null) { current.close(player); if (current.getVoiceEffect() > -1) player.getPackets().resetSounds(); } current = current.getNext(opIndex); if (current == null) { player.endConversation(); return; } if (current instanceof StageSelectDialogue d) { if (d.getFunc() != null) d.getFunc().run(); if (d.getStages() != null) current = d.getStages().get(d.getStageName()); else current = d.getDirectNextReference(); } if (player.getInterfaceManager().containsChatBoxInter()) player.getInterfaceManager().closeChatBoxInterface(); current.run(player); } public void setPlayer(Player player) { this.player = player; } public void addStage(String stageName, Dialogue dialogue) { markedStages.put(stageName, dialogue); } @Override public String toString() { Set<Dialogue> visited = new HashSet<>(); StringBuilder str = new StringBuilder(); Dialogue head = current; Dialogue curr = current; while(curr != null) { visited.add(curr); str.append(curr).append("\n"); curr = curr.getNext(0); if (visited.contains(curr)) break; } curr = head; str.append(created); return str.toString(); } public boolean isCreated() { return created; } public HashMap<String, Dialogue> getStages() { return markedStages; } }
package com.rs.engine.dialogue; public class Dialogue { private Dialogue prev; private ArrayList<Dialogue> next = new ArrayList<>(); private Runnable event; private Statement statement; private int voiceEffectId = -1; private boolean started = true; public Dialogue(Statement statement, Runnable extraFunctionality) { this.statement = statement; event = extraFunctionality; } public Dialogue(Statement statement) { this(statement, () -> { }); } public Dialogue(Runnable event) { this(null, event); } public Dialogue() { this(null, () -> { }); started = false; } public Dialogue(Dialogue dialogue) { prev = dialogue.prev; next = dialogue.next; event = dialogue.event; statement = dialogue.statement; started = dialogue.started; } public void clearChildren() { started = false; event = null; statement = null; next.clear(); } public Dialogue setFunc(Runnable consumer) { event = consumer; return this; } public Runnable getFunc() { return event; } public Dialogue addGotoStage(String stageName, Map<String, Dialogue> stages) { return addNext(new StageSelectDialogue(stageName, stages)); } public Dialogue addGotoStage(String stageName, Conversation conversation) { return addNext(new StageSelectDialogue(stageName, conversation.getStages())); } public Dialogue addGotoStage(Dialogue directNextReference) { return addNext(new StageSelectDialogue(directNextReference)); } public Dialogue addStatementWithOptions(Statement statement, Dialogue... options) { Dialogue option = addNext(statement); for (Dialogue option2 : options) option.addNext(option2); return option; } public Dialogue addStatementWithActions(Statement statement, Runnable... events) { Dialogue option = addNext(statement); for (Runnable event2 : events) option.addNext(event2); return option; } public Dialogue addPlayer(HeadE expression, String text) { return addNext(new PlayerStatement(expression, text)); } public Dialogue addPlayer(HeadE expression, String text, Runnable extraFunctionality) { return addNext(new Dialogue(new PlayerStatement(expression, text), extraFunctionality)); } public Dialogue addOption(String title, String... options) { return addNext(new OptionStatement(title, options)); } public Dialogue addNPC(int npcId, HeadE expression, String text) { return addNext(new NPCStatement(npcId, expression, text)); } public Dialogue addNPC(int npcId, HeadE expression, String text, Runnable extraFunctionality) { return addNext(new Dialogue(new NPCStatement(npcId, expression, text), extraFunctionality)); } public Dialogue addNPC(NPC npc, HeadE expression, String text) { return addNext(new NPCStatement(npc.getCustomName(), npc.getId(), expression, text)); } public Dialogue addNPC(NPC npc, HeadE expression, String text, Runnable extraFunctionality) { return addNext(new Dialogue(new NPCStatement(npc.getCustomName(), npc.getId(), expression, text), extraFunctionality)); } public Dialogue addItem(int itemId, String text) { return addNext(new ItemStatement(itemId, text)); } public Dialogue addItem(int itemId, String text, Runnable extraFunctionality) { return addNext(new Dialogue(new ItemStatement(itemId, text), extraFunctionality)); } public Dialogue addSimple(String... text) { return addNext(new SimpleStatement(text)); } public Dialogue addSimple(String text, Runnable extraFunctionality) { return addNext(new Dialogue(new SimpleStatement(text), extraFunctionality)); } public Dialogue addItemToInv(Player player, Item item, String text) { return addNext(new ItemStatement(item.getId(), text)).setFunc(() -> player.getInventory().addItem(item)); } public Dialogue addQuestStart(Quest quest) { return addNext(new QuestStartStatement(quest)); } public Dialogue addMakeX(int[] itemIds, int maxAmt) { return addNext(new MakeXStatement(itemIds, maxAmt)); } public Dialogue addMakeX(int itemId, int maxAmt) { return addMakeX(new int[] { itemId }, maxAmt); } public Dialogue addMakeX(int[] itemIds) { return addMakeX(itemIds, 60); } public Dialogue addMakeX(int itemId) { return addMakeX(new int[] { itemId }, 60); } public Dialogue addOptions(Consumer<Options> create) { Options options = new Options() { @Override public void create() { create.accept(this); } }; return addOptions(null, options); } public Dialogue addOptions(Options options) { return addOptions(null, options); } public Dialogue addOptions(String title, Consumer<Options> create) { Options options = new Options() { @Override public void create() { create.accept(this); } }; return addOptions(title, options); } public Dialogue addOptions(Conversation conversation, String stageName, Consumer<Options> create) { Options options = new Options(stageName, conversation) { @Override public void create() { create.accept(this); } }; return addOptions(Conversation.DEFAULT_OPTIONS_TITLE, options); } public Dialogue addOptions(String stageName, Conversation conv, String title, Consumer<Options> create) { Options options = new Options(stageName, conv) { @Override public void create() { create.accept(this); } }; return addOptions(title, options); } public Dialogue addOptions(String title, Options options) { if (options.getOptions().size() <= 1) { for (String opName : options.getOptions().keySet()) { Option op = options.getOptions().get(opName); if (op.show() && op.getDialogue() != null) return addNext(op.getDialogue()); } if (options.getConv() != null) options.getConv().addStage(options.getStageName(), getNext(0)); } else if (options.getOptions().size() <= 5) { List<String> ops = new ArrayList<>(); for (String opName : options.getOptions().keySet()) { Option o = options.getOptions().get(opName); if (o.show()) ops.add(opName); } Dialogue op = new Dialogue(new OptionStatement(title, ops.stream().toArray(String[] ::new))); for (String opName : options.getOptions().keySet()) { Option o = options.getOptions().get(opName); if (o.show() && o.getDialogue() != null) op.addNext(o.getDialogue()); } if (options.getConv() != null) options.getConv().addStage(options.getStageName(), op); return addNext(op); } else { String[] ops = new String[options.getOptions().keySet().size()]; options.getOptions().keySet().toArray(ops); String[] baseOptions = new String[5]; System.arraycopy(ops, 0, baseOptions, 0, 4); baseOptions[4] = "More options..."; Dialogue baseOption = new Dialogue(new OptionStatement(title, baseOptions)); Dialogue currPage = baseOption; for (int i = 0;i < ops.length;i++) { Option op = options.getOptions().get(ops[i]); if (op.show() && op.getDialogue() != null) { currPage.addNext(op.getDialogue()); if (i >= 3 && ((i+1) % 4) == 0) { String[] nextOps = new String[Utils.clampI(ops.length-i, 0, 5)]; for (int j = 1;j < 5;j++) { if (i+j >= ops.length) continue; nextOps[j-1] = ops[i+j]; } nextOps[nextOps.length-1] = "More options..."; Dialogue nextPage = new Dialogue(new OptionStatement(title, nextOps)); currPage.addNext(nextPage); currPage = nextPage; } } } currPage.addNext(baseOption); if (options.getConv() != null) options.getConv().addStage(options.getStageName(), baseOption); return addNext(baseOption); } return this; } public Dialogue addNext(Statement statement) { if (!started) { this.statement = statement; started = true; return this; } Dialogue nextD = new Dialogue(statement); if (nextD.getPrev() == null) nextD.setPrev(this); next.add(nextD); return nextD; } public Dialogue addNextIf(BooleanSupplier condition, Dialogue dialogue) { if (condition.getAsBoolean()) { addNext(dialogue.getHead()); return dialogue; } return this; } public Dialogue addNextIf(BooleanSupplier condition, Runnable event) { if (condition.getAsBoolean()) return addNext(event); return this; } public Dialogue addNext(Dialogue dialogue) { if (!started) { if (dialogue instanceof StageSelectDialogue) return dialogue; statement = dialogue.statement; event = dialogue.event; next = dialogue.next; started = true; return this; } if (dialogue.getPrev() == null) dialogue.setPrev(this); else { Dialogue copy = new Dialogue(this); dialogue.setPrev(copy); } next.add(dialogue); return dialogue; } public Dialogue addNext(Runnable event) { Dialogue dialogue = new Dialogue(); dialogue.statement = null; dialogue.event = event; return addNext(dialogue); } public Dialogue addNPC(int npcId, HeadE expression, String text, String nameOverride) { return addNext(new Dialogue(new NPCStatement(nameOverride, npcId, expression, text))); } public Dialogue addNPC(int npcId, HeadE expression, String text, String nameOverride, Runnable extraFunctionality) { return addNext(new Dialogue(new NPCStatement(nameOverride, npcId, expression, text), extraFunctionality)); } public Dialogue addStop() { return addNext(new Dialogue()); } public Dialogue finish() { return getHead(); } public Dialogue getHead() { if (prev == null) return this; Set<Dialogue> visited = new HashSet<>(); Dialogue curr = this; while(curr.getPrev() != null) { if (visited.contains(curr)) break; visited.add(curr); curr = curr.getPrev(); } return curr; } public Dialogue getNext(int choice) { if (next.size() > 0 && choice < next.size()) return next.get(choice); return null; } public void run(Player player) { if (event != null) event.run(); if (statement != null) statement.send(player); if (voiceEffectId != -1) player.voiceEffect(voiceEffectId, false); } public Dialogue getPrev() { return prev; } public void setPrev(Dialogue prev) { this.prev = prev; } public Statement getStatement() { return statement; } @Override public String toString() { StringBuilder str = new StringBuilder("[Dialogue] { stmt: " + statement + " next: [ "); for (Dialogue d : next) { if (d == null) continue; str.append(d.getClass().getSimpleName()).append("(").append(d.getStatement()).append(")\n\t"); } str.append(" ] }"); return str.toString(); } public Dialogue cutPrev() { Dialogue isolated = new Dialogue(); isolated.addNext(this); isolated.prev = null; return isolated; } public Dialogue setStage(String stageName, Conversation conversation) { Dialogue copy = new Dialogue(this); copy.prev = null; conversation.addStage(stageName, copy); return this; } public void close(Player player) { if (statement != null) statement.close(player); } public int getVoiceEffect() { return voiceEffectId; } public Dialogue voiceEffect(int voiceId) { this.voiceEffectId = voiceId; return this; } }
package com.rs.engine.dialogue @DslMarker annotation class DialogueDsl @DialogueDsl open class DialogueBuilder(val stages: MutableMap<String, Dialogue> = mutableMapOf()) { private var dialogue = Dialogue() private var pendingLabel: String? = null val start = dialogue fun player(expression: HeadE, text: String, extraFunctionality: Runnable? = null) { dialogue = dialogue.addPlayer(expression, text, extraFunctionality) applyPendingLabel() } fun npc(id: Int, expression: HeadE, text: String, extraFunctionality: Runnable? = null) { dialogue = dialogue.addNPC(id, expression, text, extraFunctionality) applyPendingLabel() } fun item(itemId: Int, text: String, extraFunctionality: Runnable? = null) { dialogue = dialogue.addItem(itemId, text, extraFunctionality) applyPendingLabel() } fun simple(vararg text: String, extraFunctionality: Runnable? = null) { dialogue = if (extraFunctionality != null) { dialogue.addSimple(text.first(), extraFunctionality) } else { dialogue.addSimple(*text) } applyPendingLabel() } fun exec(extraFunctionality: Runnable) { dialogue = dialogue.addNext(extraFunctionality) applyPendingLabel() } fun addItemToInv(player: Player, item: Item, text: String) { dialogue = dialogue.addItemToInv(player, item, text) applyPendingLabel() } fun questStart(quest: Quest) { dialogue = dialogue.addQuestStart(quest) applyPendingLabel() } fun options(title: String? = null, setup: OptionsBuilder.() -> Unit) { dialogue = dialogue.addOptions(title) { options -> OptionsBuilder(stages).apply(setup).applyToOptions(options) } applyPendingLabel() } fun makeX(itemId: Int, maxAmt: Int = 60) { dialogue = dialogue.addMakeX(itemId, maxAmt) applyPendingLabel() } fun makeX(itemIds: IntArray, maxAmt: Int = 60) { dialogue = dialogue.addMakeX(itemIds, maxAmt) applyPendingLabel() } fun label(stageName: String) { pendingLabel = stageName } fun goto(stageName: String, conversation: Conversation? = null) { dialogue = if (conversation != null) dialogue.addGotoStage(stageName, conversation) else dialogue.addGotoStage(stageName, stages) } fun statementWithOptions(statement: Statement, vararg options: DialogueBuilder.() -> Unit) { val optionDialogues = options.map { DialogueBuilder(stages).apply(it).build() } dialogue = dialogue.addStatementWithOptions(statement, *optionDialogues.toTypedArray()) applyPendingLabel() } fun statementWithActions(statement: Statement, vararg events: Runnable) { dialogue = dialogue.addStatementWithActions(statement, *events) applyPendingLabel() } fun item(itemId: Int, text: String) { dialogue = dialogue.addItem(itemId, text) applyPendingLabel() } fun simple(text: String) { dialogue = dialogue.addSimple(text) applyPendingLabel() } fun npc(npc: NPC, expression: HeadE, text: String, extraFunctionality: Runnable? = null) { dialogue = dialogue.addNPC(npc, expression, text, extraFunctionality) applyPendingLabel() } fun makeX(itemId: Int) { dialogue = dialogue.addMakeX(itemId) applyPendingLabel() } fun makeX(itemIds: IntArray) { dialogue = dialogue.addMakeX(itemIds) applyPendingLabel() } fun nextIf(condition: BooleanSupplier, dialogueSetup: DialogueBuilder.() -> Unit) { val nextDialogue = DialogueBuilder(stages).apply(dialogueSetup).build() dialogue = dialogue.addNextIf(condition, nextDialogue) applyPendingLabel() } fun stop() { dialogue = dialogue.addStop() } fun setStage(stageName: String, conversation: Conversation) { dialogue = dialogue.setStage(stageName, conversation) } fun voiceEffect(voiceId: Int) { dialogue = dialogue.voiceEffect(voiceId) } private fun applyPendingLabel() { if (pendingLabel != null) { stages[pendingLabel!!] = dialogue pendingLabel = null } } internal open fun build(): Dialogue = start } @DialogueDsl class OptionsBuilder(val stages: MutableMap<String, Dialogue>) { private sealed class OptionOperation { data class BuilderOp(val name: String, val setup: OptionBuilder.() -> Unit) : OptionOperation() data class ExecOp(val name: String, val exec: Runnable) : OptionOperation() } private val operations = mutableListOf<OptionOperation>() fun op(name: String, setup: OptionBuilder.() -> Unit = {}) { operations.add(OptionOperation.BuilderOp(name, setup)) } fun opExec(name: String, exec: Runnable) { operations.add(OptionOperation.ExecOp(name, exec)) } fun applyToOptions(options: Options) { operations.forEach { operation -> when (operation) { is OptionOperation.BuilderOp -> { val builder = OptionBuilder(stages).apply(operation.setup) options.add(operation.name, builder.build()) } is OptionOperation.ExecOp -> { options.add(operation.name, operation.exec) } } } } } @DialogueDsl class OptionBuilder(stages: MutableMap<String, Dialogue>) : DialogueBuilder(stages) fun dialogue(block: DialogueBuilder.() -> Unit): Dialogue { val builder = DialogueBuilder() builder.block() return builder.build() } fun Player.startConversation(block: DialogueBuilder.() -> Unit) { startConversation(DialogueBuilder().apply(block).build()) }
package com.rs.engine.dialogue; public enum HeadE { NONE(-1), AMAZED_MILD(9742), AMAZED(9746), MORTIFIED_JAW_DROP(9750), MORTIFIED(9753), SAD_MILD_LOOK_DOWN(9757), SAD_MILD(9760), SAD_SNIFFLE(9761), SAD(9764), SAD_CRYING(9765), SAD_EXTREME(9768), UPSET(9770), UPSET_SNIFFLE(9772), SCARED(9773), WORRIED(9775), TERRIFIED(9777), FRUSTRATED(9781), VERY_FRUSTRATED(9785), ANGRY(9789), BUMPY_RIDE(9793), SLEEPING(9802), NOTHING_LISTENING(9804), CALM(9806), NO_EXPRESSION(9809), CALM_TALK(9810), CONFUSED(9811), SHAKING_HEAD(9814), SKEPTICAL_HEAD_SHAKE(9827), SKEPTICAL(9830), ROLL_EYES(9831), SKEPTICAL_THINKING(9834), DRUNK(9835), NERVOUS(9836), SECRETIVE(9838), CHUCKLE(9840), LAUGH(9841), EVIL_LAUGH(9842), CHEERFUL(9843), TALKING_ALOT(9845), CHEERFUL_EXPOSITION(9847), HAPPY_TALKING(9850), FOGGY_STORYTELLING(9851), FOGGY_STORYTELLING_2(9852), EYES_CLOSED_NERVOUS(9877), DIZZY(9878), DRUNK_ANGRY(12648), LOSING_IT_LAUGHING(12649), SAD_VERY_SNIFFLE(12650), T_CALM_TALK(12936), T_ANGRY(12940), T_VERY_SAD(12944), T_SAD(12948), T_HAPPY_TALK(12952), T_CONFUSED(12957), T_CONFUSED_DENIAL(12961), T_LAUGH(12964), T_SCARED(12968), T_ANGRY_NO(12973), T_SURPRISED(12977), CAT_CALM_TALK(9178), CAT_CHEERFUL(9179), CAT_EXPLAIN(9180), CAT_SHOOK(9181), CAT_SHOUTING(9185), CAT_SLOW_TALK(9187), CAT_CALM_TALK2(9189), CAT_SURPRISED(9190), CAT_HAPPY(9192), CAT_PURRING(9202), CAT_DISAPPOINTED(9225), CAT_CRAZY(10522), CAT_DISAPPOINTED2(11536), CAT_LAUGH(1518), CAT_SAD(6552), CAT_INTELLIGENT_CALM(6553), OLD_CHAT(590), CHILD_FRUSTRATED(7168), CHILD_DOWN(7169), CHILD_RECALLING(7170), CHILD_EVIL_LAUGH(7171), CHILD_HAPPY_TALK(7172), CHILD_CALM_TALK(7173), CHILD_LAUGH(7175), CHILD_THINKING(7176), CHILD_SAD(7177), CHILD_SCARED(7178), CHILD_SECRETIVE(7179), CHILD_AWE(7180), CHILD_ANGRY(8814), CHILD_ANGRY_HEADSHAKE(8815), CHILD_UNSURE(8824), CHILD_CRYING(9683), CHILD_GRETA_THUNBERG(9684), CHILD_TANTRUM(7181), PENG_TALK(5661), PENG_EXPLAIN(5662), PENG_HAPPY(5663), PENG_SAD(5665), SPIDER_NONE(11605), SPIDER_EXCLAIM(11606), SPIDER_CALM(11607), SPIDER_SAD(11607), //Kalphites 6243-6246 possibly //More bug faces 7630-7639 //8380-8387 //8475-8478 ; private final int emoteId; private HeadE(int emoteId) { this.emoteId = emoteId; } public int getEmoteId() { return emoteId; } }
package com.rs.engine.dialogue; public class Option { private final Dialogue dialogue; private final Supplier<Boolean> constraint; public Option(Supplier<Boolean> constraint, Dialogue dialogue) { this.constraint = constraint; this.dialogue = dialogue; } public Option(Dialogue dialogue) { this(null, dialogue); } public Dialogue getDialogue() { return dialogue; } public Supplier<Boolean> getConstraint() { return constraint; } public boolean show() { return constraint == null ? true : constraint.get(); } }
package com.rs.engine.dialogue; public abstract class Options { private final Map<String, Option> options = new LinkedHashMap<>(); //LinkedHashMap O(1) but allows ordered keys private String stageName; private Conversation conv; public Options() { create(); } public Options(String stageName, Conversation conv) { this.conv = conv; this.stageName = stageName; create(); } public abstract void create(); public void option(String name, Dialogue dialogue) { options.put(name, new Option(dialogue.getHead())); } public void option(String name, Runnable consumer) { options.put(name, new Option(new Dialogue(null, consumer))); } public void option(Supplier<Boolean> constraint, String name, Dialogue dialogue) { options.put(name, new Option(constraint, dialogue.getHead())); } public void option(String name) { options.put(name, new Option(null)); } public void add(String name, Dialogue dialogue) { options.put(name, new Option(dialogue.getHead())); } public void add(String name, Runnable consumer) { options.put(name, new Option(new Dialogue(null, consumer))); } public void add(Supplier<Boolean> constraint, String name, Dialogue dialogue) { options.put(name, new Option(constraint, dialogue.getHead())); } public Dialogue add(String name) { Dialogue dial = new Dialogue(); options.put(name, new Option(dial)); return dial; } public void empty(String name) { options.put(name, new Option(null)); } public Map<String, Option> getOptions() { return options; } public String getStageName() { return stageName; } public Conversation getConv() { return conv; } }
package com.rs.engine.dialogue.impl; public class MakeXActionD extends Dialogue { private final List<MakeXItem> options = new ArrayList<>(); public MakeXActionD addOption(MakeXItem option) { clearChildren(); options.add(option); MakeXItem[] opArr = new MakeXItem[options.size()]; options.toArray(opArr); addStatementWithOptions(new MakeXStatement(opArr, 28), opArr); return this; } public boolean isEmpty() { return options.isEmpty(); } }
package com.rs.engine.dialogue.impl; public class MakeXItem extends Dialogue { private final int itemId; public MakeXItem(Player player, Item[] materials, Item[] products, double xp, int anim, int req, int skill, int delay) { itemId = products[0].getId(); setFunc(() -> { int quantity = MakeXStatement.getQuantity(player); for (Item mat : materials) { int newQ = player.getInventory().getNumberOf(mat.getId()) / mat.getAmount(); if (newQ < quantity) quantity = newQ; } player.getActionManager().setAction(new CreateAction(new Item[][] { materials }, new Item[][] { products }, new double [] { xp }, new int[] { anim }, new int[] { req }, skill, delay, 0).setQuantity(quantity)); }); } public MakeXItem(Player player, Item material, Item product, double xp, int anim, int req, int skill, int delay) { this(player, new Item[] { material }, new Item[] { product }, xp, anim, req, skill, delay); } public int getItemId() { return itemId; } }
package com.rs.engine.dialogue.statements; public class DestroyItemStatement implements Statement { private final Item item; private final String message; public DestroyItemStatement(Item item, String message) { this.item = item; this.message = message; } @Override public void send(Player player) { player.getInterfaceManager().sendChatBoxInterface(1183); player.getPackets().setIFText(1183, 7, item.getName()); if (message != null) player.getPackets().setIFText(1183, 12, message); player.getPackets().setIFItem(1183, 13, item.getId(), 1); } @Override public int getOptionId(int componentId) { return componentId == 9 ? 0 : 1; } @Override public void close(Player player) { } }
package com.rs.engine.dialogue.statements; public class ItemStatement implements Statement { private final int itemId; private int zoom = 500; private final String[] text; public ItemStatement(int itemId, String... text) { this.itemId = itemId; this.text = text; } public ItemStatement(int itemId, int zoom, String... text) { this.itemId = itemId; this.text = text; this.zoom = zoom; } @Override public void send(Player player) { StringBuilder text = new StringBuilder(); for (String s : this.text) text.append(s).append("<br>"); player.getInterfaceManager().sendChatBoxInterface(1189); player.getPackets().sendRunScript(3449, itemId, zoom); player.getPackets().setIFText(1189, 4, text.toString()); } @Override public int getOptionId(int componentId) { return 0; } @Override public void close(Player player) { } }
package com.rs.engine.dialogue.statements; public class LampXPSelectStatement implements Statement { private final Lamp lamp; public LampXPSelectStatement(Lamp lamp) { this.lamp = lamp; } @Override public void send(Player player) { if (lamp.getId() == 12628) lamp.setXp(500); player.getTempAttribs().setO("lampInstance", lamp); player.getVars().setVar(738, 1); //has house player.getVars().setVarBit(2187, 1); player.getInterfaceManager().sendInterface(1263); player.getPackets().sendVarcString(358, "What skill would you like XP in?"); sendSelectedSkill(player); player.getPackets().sendVarc(1797, 0); player.getPackets().sendVarc(1798, lamp.getReq()); //level required to use lamp player.getPackets().sendVarc(1799, getVarCValueForLamp(lamp.getId())); for (int i = 13; i < 38; i++) player.getPackets().setIFRightClickOps(1263, i, -1, 0, 0); player.getPackets().setIFEvents(new IFEvents(1263, 39, 1, 26).enableContinueButton()); } @Override public int getOptionId(int componentId) { return switch(componentId) { case 39 -> 0; default -> 1; }; } private static void sendSelectedSkill(Player player) { if (player.getTempAttribs().getO("lampInstance") == null) return; Lamp lamp = player.getTempAttribs().getO("lampInstance"); EnumDefinitions map = EnumDefinitions.getEnum(681); if (lamp.getSelectedSkill() == map.getDefaultIntValue()) { player.getPackets().sendVarc(1796, map.getDefaultIntValue()); return; } long key = map.getKeyForValue(lamp.getSelectedSkill()); player.getPackets().sendVarc(1796, (int) key); } private int getVarCValueForLamp(int id) { return switch (id) { case 4447 ->//Shield of Arrav 23713; default -> id; }; } @Override public void close(Player player) { player.closeInterfaces(); } }
package com.rs.engine.dialogue.statements; public class LegacyItemStatement implements Statement { private final int[] itemIds; private final String title; private final String[] text; public LegacyItemStatement(int item, String title, String... text) { itemIds = new int[] { item }; this.title = title; this.text = text; } public LegacyItemStatement(int item1, int item2, String title, String... text) { itemIds = new int[] { item1, item2 }; this.title = title; this.text = text; } @Override public void send(Player player) { int interfaceId = itemIds.length > 1 ? 131 : 519; StringBuilder text = new StringBuilder(); text.append(title).append("<br>"); for (String s : this.text) text.append(s).append("<br>"); player.getInterfaceManager().sendChatBoxInterface(interfaceId); player.getPackets().setIFText(interfaceId, 1, text.toString()); player.getPackets().setIFItem(interfaceId, 0, itemIds[0], 1); if (itemIds.length > 1) player.getPackets().setIFItem(interfaceId, 2, itemIds[1], 1); } @Override public int getOptionId(int componentId) { return 0; } @Override public void close(Player player) { } }
package com.rs.engine.dialogue.statements; @PluginEventHandler public class MakeXStatement implements Statement { public enum MakeXType { MAKE, MAKE_SET, COOK, ROAST, OFFER, SELL, BAKE, CUT, DEPOSIT, MAKE_INTERVAL, TELEPORT, SELECT, MAKE_SET_INTERVAL, TAKE, RETURN, HEAT, ADD } private final MakeXType type; private int maxQuantity = -50; private final String question; private final int[] items; private final String[] options; public MakeXStatement(MakeXType type, int maxQuantity, String question, int[] items, String[] options) { this.type = type; this.maxQuantity = maxQuantity; this.question = question; this.items = items; this.options = options; } public MakeXStatement(MakeXItem[] items, int maxQuantity) { this(MakeXType.MAKE, maxQuantity, "How many would you like to make?", Arrays.stream(items).mapToInt(MakeXItem::getItemId).toArray(), null); } public MakeXStatement(MakeXType type, String question, int[] items, int maxQuantity) { this(type, maxQuantity, question, items, null); } public MakeXStatement(MakeXType type, int[] items, int maxQuantity) { this(type, maxQuantity, "How many would you like to make?", items, null); } public MakeXStatement(MakeXType type, int[] items, String[] options) { this(type, -50, "Select an item.", items, options); } public MakeXStatement(MakeXType type, int[] items) { this(type, -50, "Select an item.", items, null); } public MakeXStatement(String question, int[] items, int maxQuantity) { this(MakeXType.MAKE, maxQuantity, question, items, null); } public MakeXStatement(int[] items, int maxQuantity) { this(MakeXType.MAKE, maxQuantity, "How many would you like to make?", items, null); } public MakeXStatement(int[] items, String[] options) { this(MakeXType.SELECT, -50, "Select an item.", items, options); } public MakeXStatement(int[] items) { this(MakeXType.SELECT, -50, "Select an item.", items, null); } @Override public void send(Player player) { player.getPackets().setIFRightClickOps(916, 8, -1, 0, 0); player.getPackets().setIFText(916, 6, question); player.getPackets().sendVarc(754, type.ordinal()); for (int i = 0; i < 10; i++) { if (i >= items.length) { player.getPackets().sendVarc(i >= 6 ? (1139 + i - 6) : 755 + i, -1); continue; } player.getPackets().sendVarc(i >= 6 ? (1139 + i - 6) : 755 + i, items[i]); player.getPackets().sendVarcString(i >= 6 ? (280 + i - 6) : 132 + i, options != null ? options[i] : ItemDefinitions.getDefs(items[i]).getName()); } setMaxQuantity(player, maxQuantity); setQuantity(player, maxQuantity); player.getInterfaceManager().sendChatBoxInterface(905); player.getInterfaceManager().sendSubSpecific(true, 905, 4, 916); } public static ButtonClickHandler handleSetQuantityButtons = new ButtonClickHandler(916, e -> { if (e.getComponentId() == 10) setQuantity(e.getPlayer(), 1, true); else if (e.getComponentId() == 11) setQuantity(e.getPlayer(), 5, true); else if (e.getComponentId() == 12) setQuantity(e.getPlayer(), 10, true); else if (e.getComponentId() == 8) setQuantity(e.getPlayer(), getMaxQuantity(e.getPlayer()), true); else if (e.getComponentId() == 24) setQuantity(e.getPlayer(), getQuantity(e.getPlayer()) + 1, true); else if (e.getComponentId() == 25) setQuantity(e.getPlayer(), getQuantity(e.getPlayer()) - 1, true); }); @Override public int getOptionId(int componentId) { if (componentId < 14) return 0; if (componentId == 26) return 7; if (componentId >= 21) return componentId - 13; return componentId - 14; } public static void setMaxQuantity(Player player, int maxQuantity) { player.getVars().setVarBit(8094, maxQuantity); } public static void setQuantity(Player player, int quantity) { setQuantity(player, quantity, true); } public static void setQuantity(Player player, int quantity, boolean refresh) { int maxQuantity = getMaxQuantity(player); if (quantity > maxQuantity) quantity = maxQuantity; else if (quantity < 0) quantity = 0; if (refresh) player.getVars().setVarBit(8095, quantity); } public static int getMaxQuantity(Player player) { return player.getVars().getVarBit(8094); } public static int getQuantity(Player player) { if (player.getVars().getVarBit(8094) <= 0) return 60; return player.getVars().getVarBit(8095); } @Override public void close(Player player) { } }
package com.rs.engine.dialogue.statements; public class NPCStatement implements Statement { private final String nameOverride; private final int npcId; private final HeadE emote; private final String[] texts; public NPCStatement(String nameOverride, int npcId, HeadE emote, String... texts) { this.nameOverride = nameOverride; this.npcId = npcId; this.emote = emote; this.texts = texts; } public NPCStatement(int npcId, HeadE emote, String... texts) { this(null, npcId, emote, texts); } @Override public void send(Player player) { StringBuilder builder = new StringBuilder(); for (String text2 : texts) builder.append(" ").append(text2); String text = builder.toString(); player.getInterfaceManager().sendChatBoxInterface(1184); player.getPackets().setIFText(1184, 17, nameOverride != null ? nameOverride : NPCDefinitions.getDefs(npcId, player.getVars()).getName()); player.getPackets().setIFText(1184, 13, text); player.getPackets().setIFNPCHead(1184, 11, npcId); if (emote != null && emote.getEmoteId() != -1) player.getPackets().setIFAnimation(emote.getEmoteId(), 1184, 11); } @Override public int getOptionId(int componentId) { return 0; } @Override public void close(Player player) { } }
package com.rs.engine.dialogue.statements; public class OptionStatement implements Statement { private final String title; private final String[] options; public OptionStatement(String title, String... options) { this.title = title; if (options.length > 5) throw new InvalidParameterException("The max options length is 5."); this.options = options; } @Override public void send(Player player) { String[] optionArray = new String[5]; for (int i = 0; i < 5; i++) optionArray[i] = ""; int ptr = 0; for (String s : options) if (s != null) optionArray[ptr++] = s; player.getInterfaceManager().sendChatBoxInterface(1188); player.getPackets().setIFText(1188, 20, title != null ? title : "Select an Option"); player.getPackets().sendRunScriptReverse(5589, optionArray[4], optionArray[3], optionArray[2], optionArray[1], optionArray[0], options.length); } @Override public int getOptionId(int componentId) { return componentId == 11 ? 0 : componentId-12; } @Override public void close(Player player) { } }
package com.rs.engine.dialogue.statements; public class PlayerStatement implements Statement { private final HeadE emote; private final String[] texts; public PlayerStatement(HeadE emote, String... texts) { this.emote = emote; this.texts = texts; } @Override public void send(Player player) { StringBuilder builder = new StringBuilder(); for (String text2 : texts) builder.append(" ").append(text2); String text = builder.toString(); player.getInterfaceManager().sendChatBoxInterface(1191); player.getPackets().setIFText(1191, 8, player.getDisplayName()); player.getPackets().setIFText(1191, 17, text); player.getPackets().setIFPlayerHead(1191, 15); if (emote != null && emote.getEmoteId() != -1) player.getPackets().setIFAnimation(emote.getEmoteId(), 1191, 15); } @Override public int getOptionId(int componentId) { return 0; } @Override public void close(Player player) { } }
package com.rs.engine.dialogue.statements; public class QuestStartStatement implements Statement { private final Quest quest; public QuestStartStatement(Quest quest) { this.quest = quest; } @Override public void send(Player player) { quest.openQuestInfo(player, true); } @Override public int getOptionId(int componentId) { return switch(componentId) { case 46 -> 0; default -> 1; }; } @Override public void close(Player player) { if (player.getInterfaceManager().containsScreenInter()) player.getInterfaceManager().removeCentralInterface(); } }
package com.rs.engine.dialogue.statements; public class SimpleStatement implements Statement { private final String[] texts; public SimpleStatement(String... texts) { this.texts = texts; } @Override public void send(Player player) { StringBuilder builder = new StringBuilder(); for (int line = 0; line < texts.length; line++) builder.append(line == 0 ? "<p=" + 1 + ">" : "<br>").append(texts[line]); String text = builder.toString(); player.getInterfaceManager().sendChatBoxInterface(1186); player.getPackets().setIFText(1186, 1, text); } @Override public int getOptionId(int componentId) { return 0; } @Override public void close(Player player) { } }
package com.rs.engine.dialogue.statements; public interface Statement { void send(Player player); int getOptionId(int componentId); void close(Player player); }
package com.rs.engine.miniquest; public enum Miniquest { ENTER_THE_ABYSS("Enter the Abyss", new Quest[]{Quest.RUNE_MYSTERIES}, null, null, null), KNIGHTS_WAVE_TRAINING_GROUNDS("Knights Waves Training Grounds", new Quest[]{Quest.KINGS_RANSOM}, null, null, null), TROLL_WARZONE("Troll Warzone Tutorial", null, null, null, null), WITCHES_POTION("Witch's Potion", null, null, null, null), HUNT_FOR_SUROK("The Hunt for Surok", new Quest[]{Quest.WHAT_LIES_BELOW}, null, Map.of(Skills.MINING, 42, Skills.PRAYER, 43), null), FROM_TINY_ACORNS("From Tiny Acorns", new Quest[] { Quest.BUYERS_AND_CELLARS }, null, Map.of(Skills.THIEVING, 24), null), LOST_HER_MARBLES("Lost Her Marbles", null, new Miniquest[] { Miniquest.FROM_TINY_ACORNS }, Map.of(Skills.THIEVING, 41), null), A_GUILD_OF_OUR_OWN("A Guild of Our Own", null, new Miniquest[] { Miniquest.LOST_HER_MARBLES }, Map.of(Skills.THIEVING, 62, Skills.HERBLORE, 46, Skills.AGILITY, 40), null), BAR_CRAWL("Alfred Grimhand's Barcrawl", null, null, null, null) ; static { initializeHandlers(); } public static void initializeHandlers() { try { List<Class<?>> classes = Utils.getClassesWithAnnotation("com.rs", MiniquestHandler.class); for (Class<?> clazz : classes) { MiniquestHandler handler = clazz.getAnnotation(MiniquestHandler.class); if (handler == null || clazz.getSuperclass() != MiniquestOutline.class) continue; handler.miniquest().handler = (MiniquestOutline) clazz.getConstructor().newInstance(); } } catch (ClassNotFoundException | IOException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } } private final String name; private final Quest[] questPreReqs; private final Miniquest[] miniquestPreReqs; private final Map<Integer, Integer> skillReqs; private MiniquestOutline handler; Miniquest(String name, Quest[] questPreReqs, Miniquest[] miniquestPreReqs, Map<Integer, Integer> skillReqs, Function<Player, Boolean> canStart) { this.name = name; this.questPreReqs = questPreReqs; this.miniquestPreReqs = miniquestPreReqs; this.skillReqs = skillReqs; } public boolean isImplemented() { return handler != null; } public MiniquestOutline getHandler() { return handler; } public boolean meetsReqs(Player player) { return meetsReqs(player, null, false); } public boolean meetsReqs(Player player, String actionStr, boolean outputReqs) { boolean meetsRequirements = true; if (questPreReqs != null) { for (Quest preReq : questPreReqs) { if (!player.isQuestComplete(preReq, actionStr)) { if (outputReqs) player.sendMessage("You need to complete " + preReq.getDefs().name + " first."); meetsRequirements = false; } } } if (miniquestPreReqs != null) { for (Miniquest preReq : miniquestPreReqs) { if (!player.isMiniquestComplete(preReq, actionStr, outputReqs)) { if (outputReqs) player.sendMessage("You need to complete " + preReq.getName() + " first."); meetsRequirements = false; } } } if (skillReqs != null) { for (int skillId : skillReqs.keySet()) { if (player.getSkills().getLevelForXp(skillId) < skillReqs.get(skillId)) { if (actionStr != null) player.sendMessage("You need a " + Skills.SKILL_NAME[skillId] + " level of " + skillReqs.get(skillId) + "."); meetsRequirements = false; } } } if (!meetsRequirements && actionStr != null) if (outputReqs) player.sendMessage("You must meet the requirements for the miniquest: " + getName() + " " + actionStr); return meetsRequirements; } public String getName() { return name; } }
package com.rs.engine.miniquest; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface MiniquestHandler { Miniquest miniquest(); String startText(); String itemsText(); String combatText(); String rewardsText(); int completedStage(); }
package com.rs.engine.miniquest; @PluginEventHandler public class MiniquestManager { private transient Player player; private final Map<Miniquest, Integer> questStages; private final Map<Miniquest, GenericAttribMap> questAttribs; public MiniquestManager() { questStages = new HashMap<>(); questAttribs = new HashMap<>(); } public int getStage(Miniquest quest) { if (questStages.get(quest) == null) return 0; return questStages.get(quest); } public void setStage(Miniquest quest, int stage) { setStage(quest, stage, true); } public void setStage(Miniquest quest, int stage, boolean updateJournal) { if (!quest.isImplemented()) return; questStages.put(quest, stage); if (updateJournal) sendStage(quest); } public void complete(Miniquest quest) { if (!quest.isImplemented()) return; if (!isComplete(quest)) { setStage(quest, quest.getHandler().getCompletedStage()); clearQuestAttributes(quest); quest.getHandler().complete(player); sendStage(quest); } } public void reset(Miniquest quest) { if (!quest.isImplemented()) return; clearQuestAttributes(quest); setStage(quest, 0); } private void clearQuestAttributes(Miniquest quest) { questAttribs.remove(quest); } public GenericAttribMap getAttribs(Miniquest quest) { GenericAttribMap map = questAttribs.computeIfAbsent(quest, k -> new GenericAttribMap()); return map; } public boolean completedAll() { for (Miniquest quest : Miniquest.values()) { if (!quest.isImplemented()) continue; if (!isComplete(quest)) return false; } return true; } public boolean isComplete(Miniquest quest, String actionForUnimplemented, boolean outputReqs) { if (!quest.isImplemented()) return quest.meetsReqs(player, actionForUnimplemented, outputReqs); if (getStage(quest) == quest.getHandler().getCompletedStage()) return true; if (actionForUnimplemented != null) if (outputReqs) player.sendMessage("You must have completed " + quest.getName() + " " + actionForUnimplemented); return false; } public boolean isComplete(Miniquest quest) { return isComplete(quest, null, false); } public boolean isComplete(Miniquest quest, boolean outputReqs) { return isComplete(quest, null, outputReqs); } public void updateAllStages() { for (Miniquest quest : Miniquest.values()) sendStage(quest); } public void sendStage(Miniquest quest) { if (quest.getHandler() != null) quest.getHandler().updateStage(player); } public Player getPlayer() { return player; } public void setPlayer(Player player) { this.player = player; } }
package com.rs.engine.miniquest; public abstract class MiniquestOutline { public final Miniquest getMiniquest() { return getClass().getAnnotation(MiniquestHandler.class).miniquest(); } public final int getCompletedStage() { return getClass().getAnnotation(MiniquestHandler.class).completedStage(); } public abstract List<String> getJournalLines(Player player, int stage); public abstract void complete(Player player); public abstract void updateStage(Player player); public final String getStartLocationDescription() { return getClass().getAnnotation(MiniquestHandler.class).startText(); } public final String getRequiredItemsString() { return getClass().getAnnotation(MiniquestHandler.class).itemsText(); } public final String getCombatInformationString() { return getClass().getAnnotation(MiniquestHandler.class).combatText(); } public final String getRewardsString() { return getClass().getAnnotation(MiniquestHandler.class).rewardsText(); } public final void sendQuestCompleteInterface(Player player, int itemId) { int jingleNum = Utils.random(0, 4); if(jingleNum == 3) jingleNum = 318; else jingleNum+=152; player.jingle(jingleNum); player.getPackets().sendVarcString(359, getRewardsString()); player.getInterfaceManager().sendInterface(1244); player.getPackets().setIFItem(1244, 24, itemId, 1); player.getPackets().setIFText(1244, 25, "You have completed "+getMiniquest().getName()+"!"); } }
package com.rs.engine.pathfinder /** * @author Kris | 16/03/2022 */ @Suppress("MemberVisibilityCanBePrivate") @JvmInline public value class AbsoluteCoords(public val packedCoord: Int) { public constructor( x: Int, y: Int, z: Int, ) : this((y and 0x3FFF) or ((x and 0x3FFF) shl 14) or ((z and 0x3) shl 28)) public val x: Int get() = (packedCoord shr 14) and 0x3FFF public val y: Int get() = packedCoord and 0x3FFF public val z: Int get() = (packedCoord shr 28) and 0x3 /** * Converts these absolute coords to the zone coords in which these absolute coords are. */ public fun toZoneCoords(): ZoneCoords = ZoneCoords(x shr 3, y shr 3, z) override fun toString(): String = "AbsoluteCoords($x, $y, $z)" }
package com.rs.engine.pathfinder enum class Direction(@JvmField val id: Int, @JvmField val dx: Int, @JvmField val dy: Int) { NORTH(0, 0, 1), NORTHEAST(1, 1, 1), EAST(2, 1, 0), SOUTHEAST(3, 1, -1), SOUTH(4, 0, -1), SOUTHWEST(5, -1, -1), WEST(6, -1, 0), NORTHWEST(7, -1, 1); val angle: Int get() = Utils.getAngleTo(dx, dy) val isDiagonal: Boolean get() = dx != 0 && dy != 0 companion object { @JvmStatic fun random(): Direction { return entries[Utils.random(entries.size)] } @JvmStatic fun getById(id: Int): Direction { return when (id) { 0 -> NORTH 1 -> NORTHEAST 2 -> EAST 3 -> SOUTHEAST 4 -> SOUTH 5 -> SOUTHWEST 6 -> WEST 7 -> NORTHWEST else -> SOUTH } } @JvmStatic fun rotateClockwise(dir: Direction, rotation: Int): Direction { return getById((dir.id + rotation) and 0x7) } @JvmStatic fun fromAngle(angle: Int): Direction? { val delta = Utils.getDirection(angle) ?: return SOUTH return forDelta(delta[0].toInt(), delta[1].toInt()) } @JvmStatic fun forDelta(dx: Int, dy: Int): Direction? { if (dy >= 1 && dx >= 1) return NORTHEAST if (dy <= -1 && dx >= 1) return SOUTHEAST return if (dy <= -1 && dx <= -1) SOUTHWEST else if (dy >= 1 && dx <= -1) NORTHWEST else if (dy >= 1) NORTH else if (dx >= 1) EAST else if (dy <= -1) SOUTH else if (dx <= -1) WEST else null } @JvmStatic fun getAngleTo(dir: Direction): Int { return ((atan2(-dir.dx.toDouble(), -dir.dy.toDouble()) * 2607.5945876176133).toInt()) and 0x3fff } fun getFaceDirection(faceTile: Tile, player: Player): Direction { if (player.x < faceTile.x) return EAST if (player.x > faceTile.x) return WEST return if (player.y < faceTile.y) NORTH else if (player.y > faceTile.y) SOUTH else NORTH } @JvmStatic fun getDirectionTo(entity: Entity, target: Any): Direction? { val from = entity.middleTileAsVector val to = if (target is Entity) target.middleTileAsVector else Vec2(target as Tile) val sub = to.sub(from) sub.norm() val delta = sub.toTile() return forDelta(delta.x, delta.y) } } }
package com.rs.engine.pathfinder object DumbRouteFinder { @JvmStatic fun addDumbPathfinderSteps(entity: Entity, target: Any, collision: CollisionStrategy): Boolean { return addDumbPathfinderSteps(entity, target, 25, collision) } @JvmStatic fun addDumbPathfinderSteps(entity: Entity, target: Any, maxSize: Int, collision: CollisionStrategy): Boolean { val tiles = find(entity, target, maxSize, collision) if (tiles.size > 0) { var last = Tile.of(entity.tile) //World.sendSpotAnim(null, new SpotAnim(2000), last); for (t in tiles) { //World.sendSpotAnim(null, new SpotAnim(2000), t); entity.addWalkStep(t.x, t.y, last.x, last.y, true) last = t } return true } return false } private fun find(origin: Any, target: Any, maxSize: Int, collision: CollisionStrategy): Deque<Tile> { val originTile = WorldUtil.targetToTile(origin) val targetTile = WorldUtil.targetToTile(target) val size = if (origin is Entity) origin.size else 1 var real = Tile.of(originTile) var curr = if (origin is Entity) origin.middleTile else Tile.of(originTile) val targ = if (target is Entity) target.middleTile else Tile.of(targetTile) val positions: Deque<Tile> = ArrayDeque(maxSize) val step = StepValidator(WorldCollision.allFlags) while (true) { val from = Tile.of(curr) if (curr.x < targ.x && curr.y < targ.y) { if (step.canTravel(real.plane, real.x, real.y, 1, 1, size, 0, collision)) { real = add(positions, real.transform(1, 1)) curr = curr.transform(1, 1) } else if (step.canTravel(real.plane, real.x, real.y, 1, 0, size, 0, collision)) { real = add(positions, real.transform(1, 0)) curr = curr.transform(1, 0) } else if (step.canTravel(real.plane, real.x, real.y, 0, 1, size, 0, collision)) { real = add(positions, real.transform(0, 1)) curr = curr.transform(0, 1) } } else if (curr.x > targ.x && curr.y > targ.y) { if (step.canTravel(real.plane, real.x, real.y, -1, -1, size, 0, collision)) { real = add(positions, real.transform(-1, -1)) curr = curr.transform(-1, -1) } else if (step.canTravel(real.plane, real.x, real.y, -1, 0, size, 0, collision)) { real = add(positions, real.transform(-1, 0)) curr = curr.transform(-1, 0) } else if (step.canTravel(real.plane, real.x, real.y, 0, -1, size, 0, collision)) { real = add(positions, real.transform(0, -1)) curr = curr.transform(0, -1) } } else if (curr.x < targ.x && curr.y > targ.y) { if (step.canTravel(real.plane, real.x, real.y, 1, -1, size, 0, collision)) { real = add(positions, real.transform(1, -1)) curr = curr.transform(1, -1) } else if (step.canTravel(real.plane, real.x, real.y, 1, 0, size, 0, collision)) { real = add(positions, real.transform(1, 0)) curr = curr.transform(1, 0) } else if (step.canTravel(real.plane, real.x, real.y, 0, -1, size, 0, collision)) { real = add(positions, real.transform(0, -1)) curr = curr.transform(0, -1) } } else if (curr.x > targ.x && curr.y < targ.y) { if (step.canTravel(real.plane, real.x, real.y, -1, 1, size, 0, collision)) { real = add(positions, real.transform(-1, 1)) curr = curr.transform(-1, 1) } else if (step.canTravel(real.plane, real.x, real.y, -1, 0, size, 0, collision)) { real = add(positions, real.transform(-1, 0)) curr = curr.transform(-1, 0) } else if (step.canTravel(real.plane, real.x, real.y, 0, 1, size, 0, collision)) { real = add(positions, real.transform(0, 1)) curr = curr.transform(0, 1) } } else if (curr.x < targ.x) { if (step.canTravel(real.plane, real.x, real.y, 1, 0, size, 0, collision)) { real = add(positions, real.transform(1, 0)) curr = curr.transform(1, 0) } } else if (curr.x > targ.x) { if (step.canTravel(real.plane, real.x, real.y, -1, 0, size, 0, collision)) { real = add(positions, real.transform(-1, 0)) curr = curr.transform(-1, 0) } } else if (curr.y < targ.y) { if (step.canTravel(real.plane, real.x, real.y, 0, 1, size, 0, collision)) { real = add(positions, real.transform(0, 1)) curr = curr.transform(0, 1) } } else if (curr.y > targ.y) if (step.canTravel(real.plane, real.x, real.y, 0, -1, size, 0, collision)) { real = add(positions, real.transform(0, -1)) curr = curr.transform(0, -1) } if (curr.matches(from)) break } return positions } private fun add(positions: Deque<Tile>, att: Tile): Tile { positions.add(att) return att } }
/* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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. */ @file:Suppress("MemberVisibilityCanBePrivate", "DuplicatedCode") package com.rs.engine.pathfinder public class LineValidator( public val searchMapSize: Int = DEFAULT_SEARCH_MAP_SIZE, private val flags: Array<IntArray?>, ) { public fun hasLineOfSight( srcX: Int, srcY: Int, z: Int, destX: Int, destY: Int, srcSize: Int = 1, destWidth: Int = 0, destHeight: Int = 0 ): Boolean { val route = rayCast( srcX, srcY, z, destX, destY, srcSize, destWidth, destHeight, SIGHT_BLOCKED_WEST, SIGHT_BLOCKED_EAST, SIGHT_BLOCKED_SOUTH, SIGHT_BLOCKED_NORTH, true ) return route.success } public fun hasLineOfWalk( srcX: Int, srcY: Int, z: Int, destX: Int, destY: Int, srcSize: Int = 1, destWidth: Int = 0, destHeight: Int = 0 ): Boolean { val route = rayCast( srcX, srcY, z, destX, destY, srcSize, destWidth, destHeight, WALK_BLOCKED_WEST, WALK_BLOCKED_EAST, WALK_BLOCKED_SOUTH, WALK_BLOCKED_NORTH, false ) return route.success } private fun rayCast( srcX: Int, srcY: Int, z: Int, destX: Int, destY: Int, srcSize: Int = 1, destWidth: Int = 0, destHeight: Int = 0, flagWest: Int, flagEast: Int, flagSouth: Int, flagNorth: Int, los: Boolean, ): Route { val halfMap = searchMapSize / 2 val baseX = srcX - halfMap val baseY = srcY - halfMap val localSrcX = srcX - baseX val localSrcY = srcY - baseY val localDestX = destX - baseX val localDestY = destY - baseY val startX = coordinate(localSrcX, localDestX, srcSize) val startY = coordinate(localSrcY, localDestY, srcSize) if (los && flags.isFlagged(baseX, baseY, startX, startY, z, CollisionFlag.OBJECT)) { return FAILED_ROUTE } val endX = coordinate(localDestX, localSrcX, destWidth) val endY = coordinate(localDestY, localSrcY, destHeight) if (startX == endX && startY == endY) return SUCCESSFUL_ROUTE val deltaX = endX - startX val deltaY = endY - startY val travelEast = deltaX >= 0 val travelNorth = deltaY >= 0 var xFlags = if (travelEast) flagWest else flagEast var yFlags = if (travelNorth) flagSouth else flagNorth if (abs(deltaX) > abs(deltaY)) { val offsetX = if (travelEast) 1 else -1 val offsetY = if (travelNorth) 0 else -1 var scaledY = scaleUp(startY) + HALF_TILE + offsetY val tangent = scaleUp(deltaY) / abs(deltaX) var currX = startX while (currX != endX) { currX += offsetX val currY = scaleDown(scaledY) if (los && currX == endX && currY == endY) xFlags = xFlags and LAST_TILE_EXCLUDED_FLAGS.inv() if (flags.isFlagged(baseX, baseY, currX, currY, z, xFlags)) { return FAILED_ROUTE } scaledY += tangent val nextY = scaleDown(scaledY) if (los && currX == endX && nextY == endY) yFlags = yFlags and LAST_TILE_EXCLUDED_FLAGS.inv() if (nextY != currY && flags.isFlagged(baseX, baseY, currX, nextY, z, yFlags)) { return FAILED_ROUTE } } } else { val offsetX = if (travelEast) 0 else -1 val offsetY = if (travelNorth) 1 else -1 var scaledX = scaleUp(startX) + HALF_TILE + offsetX val tangent = scaleUp(deltaX) / abs(deltaY) var currY = startY while (currY != endY) { currY += offsetY val currX = scaleDown(scaledX) if (los && currX == endX && currY == endY) yFlags = yFlags and LAST_TILE_EXCLUDED_FLAGS.inv() if (flags.isFlagged(baseX, baseY, currX, currY, z, yFlags)) { return FAILED_ROUTE } scaledX += tangent val nextX = scaleDown(scaledX) if (los && nextX == endX && currY == endY) xFlags = xFlags and LAST_TILE_EXCLUDED_FLAGS.inv() if (nextX != currX && flags.isFlagged(baseX, baseY, nextX, currY, z, xFlags)) { return FAILED_ROUTE } } } return SUCCESSFUL_ROUTE } private fun coordinate(a: Int, b: Int, size: Int): Int { return when { a >= b -> a a + size - 1 <= b -> a + size - 1 else -> b } } private fun Array<IntArray?>.isFlagged( baseX: Int, baseY: Int, x: Int, y: Int, z: Int, flags: Int ): Boolean { return (this[baseX, baseY, x, y, z] and flags) != 0 } @Suppress("NOTHING_TO_INLINE") private inline operator fun Array<IntArray?>.get( baseX: Int, baseY: Int, localX: Int, localY: Int, z: Int ): Int { val x = baseX + localX val y = baseY + localY val zone = this[getZoneIndex(x, y, z)] ?: return -1 return zone[getIndexInZone(x, y)] } @Suppress("NOTHING_TO_INLINE") private inline operator fun IntArray.get(x: Int, y: Int): Int { val index = (y * searchMapSize) + x return this[index] } private companion object { private val FAILED_ROUTE = Route(ArrayDeque(), alternative = false, success = false) private val SUCCESSFUL_ROUTE = Route(ArrayDeque(), alternative = false, success = true) private const val LAST_TILE_EXCLUDED_FLAGS = OBJECT_PROJECTILE_BLOCKER or BLOCK_PLAYERS private const val SIGHT_BLOCKED_NORTH = OBJECT_PROJECTILE_BLOCKER .or(WALL_NORTH_PROJECTILE_BLOCKER) .or(BLOCK_PLAYERS) private const val SIGHT_BLOCKED_EAST = OBJECT_PROJECTILE_BLOCKER .or(WALL_EAST_PROJECTILE_BLOCKER) .or(BLOCK_PLAYERS) private const val SIGHT_BLOCKED_SOUTH = OBJECT_PROJECTILE_BLOCKER .or(WALL_SOUTH_PROJECTILE_BLOCKER) .or(BLOCK_PLAYERS) private const val SIGHT_BLOCKED_WEST = OBJECT_PROJECTILE_BLOCKER .or(WALL_WEST_PROJECTILE_BLOCKER) .or(BLOCK_PLAYERS) private const val WALK_BLOCKED_NORTH = CollisionFlag.WALL_NORTH .or(CollisionFlag.OBJECT) .or(CollisionFlag.FLOOR_DECORATION) .or(CollisionFlag.FLOOR) .or(BLOCK_PLAYERS) private const val WALK_BLOCKED_EAST = CollisionFlag.WALL_EAST .or(CollisionFlag.OBJECT) .or(CollisionFlag.FLOOR_DECORATION) .or(CollisionFlag.FLOOR) .or(BLOCK_PLAYERS) private const val WALK_BLOCKED_SOUTH = CollisionFlag.WALL_SOUTH .or(CollisionFlag.OBJECT) .or(CollisionFlag.FLOOR_DECORATION) .or(CollisionFlag.FLOOR) .or(BLOCK_PLAYERS) private const val WALK_BLOCKED_WEST = CollisionFlag.WALL_WEST .or(CollisionFlag.OBJECT) .or(CollisionFlag.FLOOR_DECORATION) .or(CollisionFlag.FLOOR) .or(BLOCK_PLAYERS) private const val SCALE = 16 private val HALF_TILE = scaleUp(tiles = 1) / 2 private fun scaleUp(tiles: Int) = tiles shl SCALE private fun scaleDown(tiles: Int) = tiles ushr SCALE } }
@file:Suppress("MemberVisibilityCanBePrivate") package com.rs.engine.pathfinder public data class Route( public val coords: ArrayDeque<RouteCoordinates>, public val alternative: Boolean, public val success: Boolean ) : List<RouteCoordinates> by coords { public val failed: Boolean get() = !success } @JvmInline public value class RouteCoordinates(public val packed: Int) { public val x: Int get() = packed and 0xFFFF public val y: Int get() = (packed shr 16) and 0xFFFF public constructor(x: Int, y: Int) : this( (x and 0xFFFF) or ((y and 0xFFFF) shl 16) ) public fun translate(xOffset: Int, yOffset: Int): RouteCoordinates { return RouteCoordinates( x = x + xOffset, y = y + yOffset ) } public fun translateX(offset: Int): RouteCoordinates = translate(offset, 0) public fun translateY(offset: Int): RouteCoordinates = translate(0, offset) override fun toString(): String { return "${javaClass.simpleName}{x=$x, y=$y}" } } public data class JavaRouteCoordinates(public val x: Int, public val y: Int) { public companion object { @JvmStatic fun of(coords: RouteCoordinates): JavaRouteCoordinates { return JavaRouteCoordinates(coords.x, coords.y) } @JvmStatic public fun of(coords: List<RouteCoordinates>): List<JavaRouteCoordinates> { return coords.map { of(it) } } /** * RouteCoordinates helper function to avoid memory-creation * with [JavaRouteCoordinates.of]. */ @JvmStatic public fun getX(coords: RouteCoordinates): Int { return coords.x } /** * RouteCoordinates helper function to avoid memory-creation * with [JavaRouteCoordinates.of]. */ @JvmStatic public fun getY(coords: RouteCoordinates): Int { return coords.y } /** * RouteCoordinates helper function to avoid memory-creation * with [JavaRouteCoordinates.of]. */ @JvmStatic public fun translate(coords: RouteCoordinates, xOffset: Int, yOffset: Int): RouteCoordinates { return coords.translate(xOffset, yOffset) } /** * RouteCoordinates helper function to avoid memory-creation * with [JavaRouteCoordinates.of]. */ @JvmStatic public fun translateX(coords: RouteCoordinates, offset: Int): RouteCoordinates { return coords.translateX(offset) } /** * RouteCoordinates helper function to avoid memory-creation * with [JavaRouteCoordinates.of]. */ @JvmStatic public fun translateY(coords: RouteCoordinates, offset: Int): RouteCoordinates { return coords.translateY(offset) } } }
package com.rs.engine.pathfinder class RouteEvent(private val target: Any, private val onReachedEvent: Runnable, private val onNearestEvent: (() -> Boolean)?) { constructor(target: Any, event: Runnable): this(target, event, null) //F-U java //TODO add optimized boolean for stationary targets that doesn't recalculate the path to check status each time fun processEvent(entity: Entity): Boolean { if (!simpleCheck(entity)) { cantReachThat(entity as? Player) return true } val route = routeEntityTo(entity, target) if (route.failed || route.size <= 0) { if (route.failed) cantReachThat(entity as? Player) if (route.size <= 0) { (entity as? Player)?.session?.writeToQueue(MinimapFlag()) if (route.alternative) { return onNearestEvent?.invoke() ?: run { cantReachThat(entity as? Player) return true } } onReachedEvent.run() } return true } if (entity.hasEffect(Effect.FREEZE) || (target is Entity && target.hasWalkSteps() && WorldUtil.collides(entity, target))) return false entity.resetWalkSteps() addSteps(entity, route, true) return false } private fun simpleCheck(entity: Entity): Boolean { return when(target) { is Entity -> entity.plane == target.plane && !target.hasFinished() is GameObject -> entity.plane == target.plane && World.getObject(target.tile, target.type) != null is GroundItem -> entity.plane == target.tile.plane && ChunkManager.getChunk(target.tile.chunkId).itemExists(target) is Tile -> entity.plane == target.plane else -> throw RuntimeException("$target is not instanceof any reachable entity.") } } val cantReachThat = { player: Player? -> player?.let { it.sendMessage("You can't reach that.") it.session.writeToQueue(MinimapFlag()) } } }
@file:Suppress("DuplicatedCode") package com.rs.engine.pathfinder private const val DEFAULT_RESET_ON_SEARCH = true internal const val DEFAULT_SEARCH_MAP_SIZE = 128 private const val DEFAULT_RING_BUFFER_SIZE = 4096 private const val DEFAULT_DISTANCE_VALUE = 999 // Default is 99_999_999 but it is unnecessary and we bitpack private const val DEFAULT_SRC_DIRECTION_VALUE = 99 private const val MAX_ALTERNATIVE_ROUTE_LOWEST_COST = 1000 private const val MAX_ALTERNATIVE_ROUTE_SEEK_RANGE = 100 private const val MAX_ALTERNATIVE_ROUTE_DISTANCE_FROM_DESTINATION = 10 private const val DEFAULT_MOVE_NEAR_FLAG = true private const val DEFAULT_ROUTE_BLOCKER_FLAGS = false private const val INITIAL_DEQUE_SIZE = 25 private const val DEFAULT_SRC_SIZE = 1 private const val DEFAULT_DEST_WIDTH = 1 private const val DEFAULT_DEST_HEIGHT = 1 private const val DEFAULT_MAX_TURNS = 25 private const val DEFAULT_OBJ_ROT = 10 private const val DEFAULT_OBJ_SHAPE = -1 private const val DEFAULT_ACCESS_BITMASK = 0 public class PathFinder( private val resetOnSearch: Boolean = DEFAULT_RESET_ON_SEARCH, private val searchMapSize: Int = DEFAULT_SEARCH_MAP_SIZE, private val ringBufferSize: Int = DEFAULT_RING_BUFFER_SIZE, private val graphInfo: IntArray = IntArray(searchMapSize * searchMapSize), private val validLocalCoords: IntArray = IntArray(ringBufferSize), private var bufReaderIndex: Int = 0, private var bufWriterIndex: Int = 0, private var currLocalX: Int = 0, private var currLocalY: Int = 0, private val useRouteBlockerFlags: Boolean = DEFAULT_ROUTE_BLOCKER_FLAGS, private val flags: Array<IntArray?>, private val moveNear: Boolean = DEFAULT_MOVE_NEAR_FLAG, private val initialDequeSize: Int = INITIAL_DEQUE_SIZE, ) { public fun findPath( srcX: Int, srcY: Int, destX: Int, destY: Int, z: Int, srcSize: Int = DEFAULT_SRC_SIZE, destWidth: Int = DEFAULT_DEST_WIDTH, destHeight: Int = DEFAULT_DEST_HEIGHT, objRot: Int = DEFAULT_OBJ_ROT, objShape: Int = DEFAULT_OBJ_SHAPE, accessBitMask: Int = DEFAULT_ACCESS_BITMASK, maxTurns: Int = DEFAULT_MAX_TURNS, collision: CollisionStrategy = CollisionStrategyType.NORMAL.strategy, reachStrategy: ReachStrategy = DefaultReachStrategy ): Route { if (resetOnSearch) { reset() } val baseX = srcX - (searchMapSize / 2) val baseY = srcY - (searchMapSize / 2) val localSrcX = srcX - baseX val localSrcY = srcY - baseY val localDestX = destX - baseX val localDestY = destY - baseY setNextValidLocalCoords(localSrcX, localSrcY, DEFAULT_SRC_DIRECTION_VALUE, 0) val pathFound = if (useRouteBlockerFlags) { when (srcSize) { 1 -> findPath1RouteBlocker( baseX, baseY, z, localDestX, localDestY, destWidth, destHeight, srcSize, objRot, objShape, accessBitMask, collision, reachStrategy ) 2 -> findPath2RouteBlocker( baseX, baseY, z, localDestX, localDestY, destWidth, destHeight, srcSize, objRot, objShape, accessBitMask, collision, reachStrategy ) else -> findPathNRouteBlocker( baseX, baseY, z, localDestX, localDestY, destWidth, destHeight, srcSize, objRot, objShape, accessBitMask, collision, reachStrategy ) } } else { when (srcSize) { 1 -> findPath1( baseX, baseY, z, localDestX, localDestY, destWidth, destHeight, srcSize, objRot, objShape, accessBitMask, collision, reachStrategy ) 2 -> findPath2( baseX, baseY, z, localDestX, localDestY, destWidth, destHeight, srcSize, objRot, objShape, accessBitMask, collision, reachStrategy ) else -> findPathN( baseX, baseY, z, localDestX, localDestY, destWidth, destHeight, srcSize, objRot, objShape, accessBitMask, collision, reachStrategy ) } } if (!pathFound) { if (!moveNear) { return FAILED_ROUTE } else if (!findClosestApproachPoint(localDestX, localDestY, destWidth, destHeight)) { return FAILED_ROUTE } } val coordinates = ArrayDeque<RouteCoordinates>(initialDequeSize) var nextDir = getDirection(currLocalX, currLocalY) var currDir = -1 var turns = 0 for (i in 0 until searchMapSize * searchMapSize) { if (currLocalX == localSrcX && currLocalY == localSrcY) break if (currDir != nextDir) { turns++ if (coordinates.size >= maxTurns) coordinates.removeLast() val coords = RouteCoordinates(currLocalX + baseX, currLocalY + baseY) coordinates.addFirst(coords) currDir = nextDir } if ((currDir and DirectionFlag.EAST) != 0) { currLocalX++ } else if ((currDir and DirectionFlag.WEST) != 0) { currLocalX-- } if ((currDir and DirectionFlag.NORTH) != 0) { currLocalY++ } else if ((currDir and DirectionFlag.SOUTH) != 0) { currLocalY-- } nextDir = getDirection(currLocalX, currLocalY) } return Route(coordinates, alternative = !pathFound, success = true) } private fun findPath1( baseX: Int, baseY: Int, z: Int, localDestX: Int, localDestY: Int, destWidth: Int, destHeight: Int, srcSize: Int, objRot: Int, objShape: Int, accessBitMask: Int, collision: CollisionStrategy, reachStrategy: ReachStrategy ): Boolean { var x: Int var y: Int var clipFlag: Int var dirFlag: Int val relativeSearchSize = searchMapSize - 1 val validCoords = validLocalCoords val flags = flags while (bufWriterIndex != bufReaderIndex) { val coord = validCoords[bufReaderIndex] currLocalX = coord ushr 16 currLocalY = coord and 0xFFFF bufReaderIndex = (bufReaderIndex + 1) and (ringBufferSize - 1) if (reachStrategy.reached( flags, currLocalX + baseX, currLocalY + baseY, z, localDestX + baseX, localDestY + baseY, destWidth, destHeight, srcSize, objRot, objShape, accessBitMask, ) ) { return true } val nextDistance = getDistance(currLocalX, currLocalY) + 1 /* east to west */ x = currLocalX - 1 y = currLocalY clipFlag = CollisionFlag.BLOCK_WEST dirFlag = DirectionFlag.EAST if (currLocalX > 0 && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, y, z], clipFlag ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* west to east */ x = currLocalX + 1 y = currLocalY clipFlag = CollisionFlag.BLOCK_EAST dirFlag = DirectionFlag.WEST if (currLocalX < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove(flags[baseX, baseY, x, y, z], clipFlag) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* north to south */ x = currLocalX y = currLocalY - 1 clipFlag = CollisionFlag.BLOCK_SOUTH dirFlag = DirectionFlag.NORTH if (currLocalY > 0 && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, y, z], clipFlag ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* south to north */ x = currLocalX y = currLocalY + 1 clipFlag = CollisionFlag.BLOCK_NORTH dirFlag = DirectionFlag.SOUTH if (currLocalY < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove(flags[baseX, baseY, x, y, z], clipFlag) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* north-east to south-west */ x = currLocalX - 1 y = currLocalY - 1 dirFlag = DirectionFlag.NORTH_EAST if (currLocalX > 0 && currLocalY > 0 && getDirection(x, y) == 0 && collision.canMove(flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_SOUTH_WEST) && collision.canMove( flags[baseX, baseY, x, currLocalY, z], CollisionFlag.BLOCK_WEST ) && collision.canMove(flags[baseX, baseY, currLocalX, y, z], CollisionFlag.BLOCK_SOUTH) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* north-west to south-east */ x = currLocalX + 1 y = currLocalY - 1 dirFlag = DirectionFlag.NORTH_WEST if (currLocalX < relativeSearchSize && currLocalY > 0 && getDirection(x, y) == 0 && collision.canMove(flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_SOUTH_EAST) && collision.canMove( flags[baseX, baseY, x, currLocalY, z], CollisionFlag.BLOCK_EAST ) && collision.canMove(flags[baseX, baseY, currLocalX, y, z], CollisionFlag.BLOCK_SOUTH) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* south-east to north-west */ x = currLocalX - 1 y = currLocalY + 1 dirFlag = DirectionFlag.SOUTH_EAST if (currLocalX > 0 && currLocalY < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove(flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_NORTH_WEST) && collision.canMove( flags[baseX, baseY, x, currLocalY, z], CollisionFlag.BLOCK_WEST ) && collision.canMove(flags[baseX, baseY, currLocalX, y, z], CollisionFlag.BLOCK_NORTH) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* south-west to north-east */ x = currLocalX + 1 y = currLocalY + 1 dirFlag = DirectionFlag.SOUTH_WEST if (currLocalX < relativeSearchSize && currLocalY < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove(flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_NORTH_EAST) && collision.canMove( flags[baseX, baseY, x, currLocalY, z], CollisionFlag.BLOCK_EAST ) && collision.canMove(flags[baseX, baseY, currLocalX, y, z], CollisionFlag.BLOCK_NORTH) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } return false } private fun findPath2( baseX: Int, baseY: Int, z: Int, localDestX: Int, localDestY: Int, destWidth: Int, destHeight: Int, srcSize: Int, objRot: Int, objShape: Int, accessBitMask: Int, collision: CollisionStrategy, reachStrategy: ReachStrategy ): Boolean { var x: Int var y: Int var dirFlag: Int val relativeSearchSize = searchMapSize - 2 val validCoords = validLocalCoords val flags = flags while (bufWriterIndex != bufReaderIndex) { val coord = validCoords[bufReaderIndex] currLocalX = coord ushr 16 currLocalY = coord and 0xFFFF bufReaderIndex = (bufReaderIndex + 1) and (ringBufferSize - 1) if (reachStrategy.reached( flags, currLocalX + baseX, currLocalY + baseY, z, localDestX + baseX, localDestY + baseY, destWidth, destHeight, srcSize, objRot, objShape, accessBitMask, ) ) { return true } val nextDistance = getDistance(currLocalX, currLocalY) + 1 /* east to west */ x = currLocalX - 1 y = currLocalY dirFlag = DirectionFlag.EAST if (currLocalX > 0 && getDirection(x, y) == 0 && collision.canMove(flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_SOUTH_WEST) && collision.canMove( flags[baseX, baseY, x, currLocalY + 1, z], CollisionFlag.BLOCK_NORTH_WEST ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* west to east */ x = currLocalX + 1 y = currLocalY dirFlag = DirectionFlag.WEST if (currLocalX < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, currLocalX + 2, y, z], CollisionFlag.BLOCK_SOUTH_EAST ) && collision.canMove( flags[baseX, baseY, currLocalX + 2, currLocalY + 1, z], CollisionFlag.BLOCK_NORTH_EAST ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* north to south */ x = currLocalX y = currLocalY - 1 dirFlag = DirectionFlag.NORTH if (currLocalY > 0 && getDirection(x, y) == 0 && collision.canMove(flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_SOUTH_WEST) && collision.canMove( flags[baseX, baseY, currLocalX + 1, y, z], CollisionFlag.BLOCK_SOUTH_EAST ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* south to north */ x = currLocalX y = currLocalY + 1 dirFlag = DirectionFlag.SOUTH if (currLocalY < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, currLocalY + 2, z], CollisionFlag.BLOCK_NORTH_WEST ) && collision.canMove( flags[baseX, baseY, currLocalX + 1, currLocalY + 2, z], CollisionFlag.BLOCK_NORTH_EAST ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* north-east to south-west */ x = currLocalX - 1 y = currLocalY - 1 dirFlag = DirectionFlag.NORTH_EAST if (currLocalX > 0 && currLocalY > 0 && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, currLocalY, z], CollisionFlag.BLOCK_NORTH_AND_SOUTH_EAST ) && collision.canMove(flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_SOUTH_WEST) && collision.canMove( flags[baseX, baseY, currLocalX, y, z], CollisionFlag.BLOCK_NORTH_EAST_AND_WEST ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* north-west to south-east */ x = currLocalX + 1 y = currLocalY - 1 dirFlag = DirectionFlag.NORTH_WEST if (currLocalX < relativeSearchSize && currLocalY > 0 && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_NORTH_EAST_AND_WEST ) && collision.canMove( flags[baseX, baseY, currLocalX + 2, y, z], CollisionFlag.BLOCK_SOUTH_EAST ) && collision.canMove( flags[baseX, baseY, currLocalX + 2, currLocalY, z], CollisionFlag.BLOCK_NORTH_AND_SOUTH_WEST ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* south-east to north-west */ x = currLocalX - 1 y = currLocalY + 1 dirFlag = DirectionFlag.SOUTH_EAST if (currLocalX > 0 && currLocalY < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_NORTH_AND_SOUTH_EAST ) && collision.canMove( flags[baseX, baseY, x, currLocalY + 2, z], CollisionFlag.BLOCK_NORTH_WEST ) && collision.canMove( flags[baseX, baseY, currLocalX, currLocalY + 2, z], CollisionFlag.BLOCK_SOUTH_EAST_AND_WEST ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* south-west to north-east */ x = currLocalX + 1 y = currLocalY + 1 dirFlag = DirectionFlag.SOUTH_WEST if (currLocalX < relativeSearchSize && currLocalY < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, currLocalY + 2, z], CollisionFlag.BLOCK_SOUTH_EAST_AND_WEST ) && collision.canMove( flags[baseX, baseY, currLocalX + 2, currLocalY + 2, z], CollisionFlag.BLOCK_NORTH_EAST ) && collision.canMove( flags[baseX, baseY, currLocalX + 2, y, z], CollisionFlag.BLOCK_NORTH_AND_SOUTH_WEST ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } return false } private fun findPathN( baseX: Int, baseY: Int, z: Int, localDestX: Int, localDestY: Int, destWidth: Int, destHeight: Int, srcSize: Int, objRot: Int, objShape: Int, accessBitMask: Int, collision: CollisionStrategy, reachStrategy: ReachStrategy ): Boolean { var x: Int var y: Int var dirFlag: Int val relativeSearchSize = searchMapSize - srcSize val validCoords = validLocalCoords val flags = flags while (bufWriterIndex != bufReaderIndex) { val coord = validCoords[bufReaderIndex] currLocalX = coord ushr 16 currLocalY = coord and 0xFFFF bufReaderIndex = (bufReaderIndex + 1) and (ringBufferSize - 1) if (reachStrategy.reached( flags, currLocalX + baseX, currLocalY + baseY, z, localDestX + baseX, localDestY + baseY, destWidth, destHeight, srcSize, objRot, objShape, accessBitMask, ) ) { return true } val nextDistance = getDistance(currLocalX, currLocalY) + 1 /* east to west */ x = currLocalX - 1 y = currLocalY dirFlag = DirectionFlag.EAST if (currLocalX > 0 && getDirection(x, y) == 0 && collision.canMove(flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_SOUTH_WEST) && collision.canMove( flags[baseX, baseY, x, currLocalY + srcSize - 1, z], CollisionFlag.BLOCK_NORTH_WEST ) ) { val clipFlag = CollisionFlag.BLOCK_NORTH_AND_SOUTH_EAST val blocked = (1 until srcSize - 1).any { !collision.canMove( flags[baseX, baseY, x, currLocalY + it, z], clipFlag ) } if (!blocked) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } /* west to east */ x = currLocalX + 1 y = currLocalY dirFlag = DirectionFlag.WEST if (currLocalX < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, currLocalX + srcSize, y, z], CollisionFlag.BLOCK_SOUTH_EAST ) && collision.canMove( flags[baseX, baseY, currLocalX + srcSize, currLocalY + srcSize - 1, z], CollisionFlag.BLOCK_NORTH_EAST ) ) { val clipFlag = CollisionFlag.BLOCK_NORTH_AND_SOUTH_WEST val blocked = (1 until srcSize - 1).any { !collision.canMove(flags[baseX, baseY, currLocalX + srcSize, currLocalY + it, z], clipFlag) } if (!blocked) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } /* north to south */ x = currLocalX y = currLocalY - 1 dirFlag = DirectionFlag.NORTH if (currLocalY > 0 && getDirection(x, y) == 0 && collision.canMove(flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_SOUTH_WEST) && collision.canMove( flags[baseX, baseY, currLocalX + srcSize - 1, y, z], CollisionFlag.BLOCK_SOUTH_EAST ) ) { val clipFlag = CollisionFlag.BLOCK_NORTH_EAST_AND_WEST val blocked = (1 until srcSize - 1).any { !collision.canMove( flags[baseX, baseY, currLocalX + it, y, z], clipFlag ) } if (!blocked) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } /* south to north */ x = currLocalX y = currLocalY + 1 dirFlag = DirectionFlag.SOUTH if (currLocalY < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, currLocalY + srcSize, z], CollisionFlag.BLOCK_NORTH_WEST ) && collision.canMove( flags[baseX, baseY, currLocalX + srcSize - 1, currLocalY + srcSize, z], CollisionFlag.BLOCK_NORTH_EAST ) ) { val clipFlag = CollisionFlag.BLOCK_SOUTH_EAST_AND_WEST val blocked = (1 until srcSize - 1).any { !collision.canMove( flags[baseX, baseY, x + it, currLocalY + srcSize, z], clipFlag ) } if (!blocked) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } /* north-east to south-west */ x = currLocalX - 1 y = currLocalY - 1 dirFlag = DirectionFlag.NORTH_EAST if (currLocalX > 0 && currLocalY > 0 && getDirection(x, y) == 0 && collision.canMove(flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_SOUTH_WEST) ) { val clipFlag1 = CollisionFlag.BLOCK_NORTH_AND_SOUTH_EAST val clipFlag2 = CollisionFlag.BLOCK_NORTH_EAST_AND_WEST val blocked = (1 until srcSize).any { !collision.canMove(flags[baseX, baseY, x, currLocalY + it - 1, z], clipFlag1) || !collision.canMove(flags[baseX, baseY, currLocalX + it - 1, y, z], clipFlag2) } if (!blocked) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } /* north-west to south-east */ x = currLocalX + 1 y = currLocalY - 1 dirFlag = DirectionFlag.NORTH_WEST if (currLocalX < relativeSearchSize && currLocalY > 0 && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, currLocalX + srcSize, y, z], CollisionFlag.BLOCK_SOUTH_EAST ) ) { val clipFlag1 = CollisionFlag.BLOCK_NORTH_AND_SOUTH_WEST val clipFlag2 = CollisionFlag.BLOCK_NORTH_EAST_AND_WEST val blocked = (1 until srcSize).any { !collision.canMove(flags[baseX, baseY, currLocalX + srcSize, currLocalY + it - 1, z], clipFlag1) || !collision.canMove(flags[baseX, baseY, currLocalX + it, y, z], clipFlag2) } if (!blocked) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } /* south-east to north-west */ x = currLocalX - 1 y = currLocalY + 1 dirFlag = DirectionFlag.SOUTH_EAST if (currLocalX > 0 && currLocalY < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, currLocalY + srcSize, z], CollisionFlag.BLOCK_NORTH_WEST ) ) { val clipFlag1 = CollisionFlag.BLOCK_NORTH_AND_SOUTH_EAST val clipFlag2 = CollisionFlag.BLOCK_SOUTH_EAST_AND_WEST val blocked = (1 until srcSize).any { !collision.canMove(flags[baseX, baseY, x, currLocalY + it, z], clipFlag1) || !collision.canMove(flags[baseX, baseY, currLocalX + it - 1, currLocalY + srcSize, z], clipFlag2) } if (!blocked) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } /* south-west to north-east */ x = currLocalX + 1 y = currLocalY + 1 dirFlag = DirectionFlag.SOUTH_WEST if (currLocalX < relativeSearchSize && currLocalY < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, currLocalX + srcSize, currLocalY + srcSize, z], CollisionFlag.BLOCK_NORTH_EAST ) ) { val clipFlag1 = CollisionFlag.BLOCK_SOUTH_EAST_AND_WEST val clipFlag2 = CollisionFlag.BLOCK_NORTH_AND_SOUTH_WEST val blocked = (1 until srcSize).any { !collision.canMove(flags[baseX, baseY, currLocalX + it, currLocalY + srcSize, z], clipFlag1) || !collision.canMove(flags[baseX, baseY, currLocalX + srcSize, currLocalY + it, z], clipFlag2) } if (!blocked) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } } return false } private fun findPath1RouteBlocker( baseX: Int, baseY: Int, z: Int, localDestX: Int, localDestY: Int, destWidth: Int, destHeight: Int, srcSize: Int, objRot: Int, objShape: Int, accessBitMask: Int, collision: CollisionStrategy, reachStrategy: ReachStrategy ): Boolean { var x: Int var y: Int var clipFlag: Int var dirFlag: Int val relativeSearchSize = searchMapSize - 1 val validCoords = validLocalCoords val flags = flags while (bufWriterIndex != bufReaderIndex) { val coord = validCoords[bufReaderIndex] currLocalX = coord ushr 16 currLocalY = coord and 0xFFFF bufReaderIndex = (bufReaderIndex + 1) and (ringBufferSize - 1) if (reachStrategy.reached( flags, currLocalX + baseX, currLocalY + baseY, z, localDestX + baseX, localDestY + baseY, destWidth, destHeight, srcSize, objRot, objShape, accessBitMask, ) ) { return true } val nextDistance = getDistance(currLocalX, currLocalY) + 1 /* east to west */ x = currLocalX - 1 y = currLocalY clipFlag = CollisionFlag.BLOCK_WEST_ROUTE_BLOCKER dirFlag = DirectionFlag.EAST if (currLocalX > 0 && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, y, z], clipFlag ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* west to east */ x = currLocalX + 1 y = currLocalY clipFlag = CollisionFlag.BLOCK_EAST_ROUTE_BLOCKER dirFlag = DirectionFlag.WEST if (currLocalX < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove(flags[baseX, baseY, x, y, z], clipFlag) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* north to south */ x = currLocalX y = currLocalY - 1 clipFlag = CollisionFlag.BLOCK_SOUTH_ROUTE_BLOCKER dirFlag = DirectionFlag.NORTH if (currLocalY > 0 && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, y, z], clipFlag ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* south to north */ x = currLocalX y = currLocalY + 1 clipFlag = CollisionFlag.BLOCK_NORTH_ROUTE_BLOCKER dirFlag = DirectionFlag.SOUTH if (currLocalY < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove(flags[baseX, baseY, x, y, z], clipFlag) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* north-east to south-west */ x = currLocalX - 1 y = currLocalY - 1 dirFlag = DirectionFlag.NORTH_EAST if (currLocalX > 0 && currLocalY > 0 && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_SOUTH_WEST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, x, currLocalY, z], CollisionFlag.BLOCK_WEST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, currLocalX, y, z], CollisionFlag.BLOCK_SOUTH_ROUTE_BLOCKER ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* north-west to south-east */ x = currLocalX + 1 y = currLocalY - 1 dirFlag = DirectionFlag.NORTH_WEST if (currLocalX < relativeSearchSize && currLocalY > 0 && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_SOUTH_EAST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, x, currLocalY, z], CollisionFlag.BLOCK_EAST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, currLocalX, y, z], CollisionFlag.BLOCK_SOUTH_ROUTE_BLOCKER ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* south-east to north-west */ x = currLocalX - 1 y = currLocalY + 1 dirFlag = DirectionFlag.SOUTH_EAST if (currLocalX > 0 && currLocalY < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_NORTH_WEST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, x, currLocalY, z], CollisionFlag.BLOCK_WEST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, currLocalX, y, z], CollisionFlag.BLOCK_NORTH_ROUTE_BLOCKER ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* south-west to north-east */ x = currLocalX + 1 y = currLocalY + 1 dirFlag = DirectionFlag.SOUTH_WEST if (currLocalX < relativeSearchSize && currLocalY < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_NORTH_EAST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, x, currLocalY, z], CollisionFlag.BLOCK_EAST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, currLocalX, y, z], CollisionFlag.BLOCK_NORTH_ROUTE_BLOCKER ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } return false } private fun findPath2RouteBlocker( baseX: Int, baseY: Int, z: Int, localDestX: Int, localDestY: Int, destWidth: Int, destHeight: Int, srcSize: Int, objRot: Int, objShape: Int, accessBitMask: Int, collision: CollisionStrategy, reachStrategy: ReachStrategy ): Boolean { var x: Int var y: Int var dirFlag: Int val relativeSearchSize = searchMapSize - 2 val validCoords = validLocalCoords val flags = flags while (bufWriterIndex != bufReaderIndex) { val coord = validCoords[bufReaderIndex] currLocalX = coord ushr 16 currLocalY = coord and 0xFFFF bufReaderIndex = (bufReaderIndex + 1) and (ringBufferSize - 1) if (reachStrategy.reached( flags, currLocalX + baseX, currLocalY + baseY, z, localDestX + baseX, localDestY + baseY, destWidth, destHeight, srcSize, objRot, objShape, accessBitMask, ) ) { return true } val nextDistance = getDistance(currLocalX, currLocalY) + 1 /* east to west */ x = currLocalX - 1 y = currLocalY dirFlag = DirectionFlag.EAST if (currLocalX > 0 && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_SOUTH_WEST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, x, currLocalY + 1, z], CollisionFlag.BLOCK_NORTH_WEST_ROUTE_BLOCKER ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* west to east */ x = currLocalX + 1 y = currLocalY dirFlag = DirectionFlag.WEST if (currLocalX < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, currLocalX + 2, y, z], CollisionFlag.BLOCK_SOUTH_EAST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, currLocalX + 2, currLocalY + 1, z], CollisionFlag.BLOCK_NORTH_EAST_ROUTE_BLOCKER ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* north to south */ x = currLocalX y = currLocalY - 1 dirFlag = DirectionFlag.NORTH if (currLocalY > 0 && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_SOUTH_WEST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, currLocalX + 1, y, z], CollisionFlag.BLOCK_SOUTH_EAST_ROUTE_BLOCKER ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* south to north */ x = currLocalX y = currLocalY + 1 dirFlag = DirectionFlag.SOUTH if (currLocalY < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, currLocalY + 2, z], CollisionFlag.BLOCK_NORTH_WEST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, currLocalX + 1, currLocalY + 2, z], CollisionFlag.BLOCK_NORTH_EAST_ROUTE_BLOCKER ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* north-east to south-west */ x = currLocalX - 1 y = currLocalY - 1 dirFlag = DirectionFlag.NORTH_EAST if (currLocalX > 0 && currLocalY > 0 && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, currLocalY, z], CollisionFlag.BLOCK_NORTH_AND_SOUTH_EAST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_SOUTH_WEST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, currLocalX, y, z], CollisionFlag.BLOCK_NORTH_EAST_AND_WEST_ROUTE_BLOCKER ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* north-west to south-east */ x = currLocalX + 1 y = currLocalY - 1 dirFlag = DirectionFlag.NORTH_WEST if (currLocalX < relativeSearchSize && currLocalY > 0 && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_NORTH_EAST_AND_WEST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, currLocalX + 2, y, z], CollisionFlag.BLOCK_SOUTH_EAST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, currLocalX + 2, currLocalY, z], CollisionFlag.BLOCK_NORTH_AND_SOUTH_WEST_ROUTE_BLOCKER ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* south-east to north-west */ x = currLocalX - 1 y = currLocalY + 1 dirFlag = DirectionFlag.SOUTH_EAST if (currLocalX > 0 && currLocalY < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_NORTH_AND_SOUTH_EAST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, x, currLocalY + 2, z], CollisionFlag.BLOCK_NORTH_WEST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, currLocalX, currLocalY + 2, z], CollisionFlag.BLOCK_SOUTH_EAST_AND_WEST_ROUTE_BLOCKER ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } /* south-west to north-east */ x = currLocalX + 1 y = currLocalY + 1 dirFlag = DirectionFlag.SOUTH_WEST if (currLocalX < relativeSearchSize && currLocalY < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, currLocalY + 2, z], CollisionFlag.BLOCK_SOUTH_EAST_AND_WEST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, currLocalX + 2, currLocalY + 2, z], CollisionFlag.BLOCK_NORTH_EAST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, currLocalX + 2, y, z], CollisionFlag.BLOCK_NORTH_AND_SOUTH_WEST_ROUTE_BLOCKER ) ) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } return false } private fun findPathNRouteBlocker( baseX: Int, baseY: Int, z: Int, localDestX: Int, localDestY: Int, destWidth: Int, destHeight: Int, srcSize: Int, objRot: Int, objShape: Int, accessBitMask: Int, collision: CollisionStrategy, reachStrategy: ReachStrategy ): Boolean { var x: Int var y: Int var dirFlag: Int val relativeSearchSize = searchMapSize - srcSize val validCoords = validLocalCoords val flags = flags while (bufWriterIndex != bufReaderIndex) { val coord = validCoords[bufReaderIndex] currLocalX = coord ushr 16 currLocalY = coord and 0xFFFF bufReaderIndex = (bufReaderIndex + 1) and (ringBufferSize - 1) if (reachStrategy.reached( flags, currLocalX + baseX, currLocalY + baseY, z, localDestX + baseX, localDestY + baseY, destWidth, destHeight, srcSize, objRot, objShape, accessBitMask, ) ) { return true } val nextDistance = getDistance(currLocalX, currLocalY) + 1 /* east to west */ x = currLocalX - 1 y = currLocalY dirFlag = DirectionFlag.EAST if (currLocalX > 0 && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_SOUTH_WEST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, x, currLocalY + srcSize - 1, z], CollisionFlag.BLOCK_NORTH_WEST_ROUTE_BLOCKER ) ) { val clipFlag = CollisionFlag.BLOCK_NORTH_AND_SOUTH_EAST_ROUTE_BLOCKER val blocked = (1 until srcSize - 1).any { !collision.canMove( flags[baseX, baseY, x, currLocalY + it, z], clipFlag ) } if (!blocked) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } /* west to east */ x = currLocalX + 1 y = currLocalY dirFlag = DirectionFlag.WEST if (currLocalX < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, currLocalX + srcSize, y, z], CollisionFlag.BLOCK_SOUTH_EAST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, currLocalX + srcSize, currLocalY + srcSize - 1, z], CollisionFlag.BLOCK_NORTH_EAST_ROUTE_BLOCKER ) ) { val clipFlag = CollisionFlag.BLOCK_NORTH_AND_SOUTH_WEST_ROUTE_BLOCKER val blocked = (1 until srcSize - 1).any { !collision.canMove(flags[baseX, baseY, currLocalX + srcSize, currLocalY + it, z], clipFlag) } if (!blocked) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } /* north to south */ x = currLocalX y = currLocalY - 1 dirFlag = DirectionFlag.NORTH if (currLocalY > 0 && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_SOUTH_WEST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, currLocalX + srcSize - 1, y, z], CollisionFlag.BLOCK_SOUTH_EAST_ROUTE_BLOCKER ) ) { val clipFlag = CollisionFlag.BLOCK_NORTH_EAST_AND_WEST_ROUTE_BLOCKER val blocked = (1 until srcSize - 1).any { !collision.canMove( flags[baseX, baseY, currLocalX + it, y, z], clipFlag ) } if (!blocked) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } /* south to north */ x = currLocalX y = currLocalY + 1 dirFlag = DirectionFlag.SOUTH if (currLocalY < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, currLocalY + srcSize, z], CollisionFlag.BLOCK_NORTH_WEST_ROUTE_BLOCKER ) && collision.canMove( flags[baseX, baseY, currLocalX + srcSize - 1, currLocalY + srcSize, z], CollisionFlag.BLOCK_NORTH_EAST_ROUTE_BLOCKER ) ) { val clipFlag = CollisionFlag.BLOCK_SOUTH_EAST_AND_WEST_ROUTE_BLOCKER val blocked = (1 until srcSize - 1).any { !collision.canMove( flags[baseX, baseY, x + it, currLocalY + srcSize, z], clipFlag ) } if (!blocked) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } /* north-east to south-west */ x = currLocalX - 1 y = currLocalY - 1 dirFlag = DirectionFlag.NORTH_EAST if (currLocalX > 0 && currLocalY > 0 && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, y, z], CollisionFlag.BLOCK_SOUTH_WEST_ROUTE_BLOCKER ) ) { val clipFlag1 = CollisionFlag.BLOCK_NORTH_AND_SOUTH_EAST_ROUTE_BLOCKER val clipFlag2 = CollisionFlag.BLOCK_NORTH_EAST_AND_WEST_ROUTE_BLOCKER val blocked = (1 until srcSize).any { !collision.canMove(flags[baseX, baseY, x, currLocalY + it - 1, z], clipFlag1) || !collision.canMove(flags[baseX, baseY, currLocalX + it - 1, y, z], clipFlag2) } if (!blocked) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } /* north-west to south-east */ x = currLocalX + 1 y = currLocalY - 1 dirFlag = DirectionFlag.NORTH_WEST if (currLocalX < relativeSearchSize && currLocalY > 0 && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, currLocalX + srcSize, y, z], CollisionFlag.BLOCK_SOUTH_EAST_ROUTE_BLOCKER ) ) { val clipFlag1 = CollisionFlag.BLOCK_NORTH_AND_SOUTH_WEST_ROUTE_BLOCKER val clipFlag2 = CollisionFlag.BLOCK_NORTH_EAST_AND_WEST_ROUTE_BLOCKER val blocked = (1 until srcSize).any { !collision.canMove(flags[baseX, baseY, currLocalX + srcSize, currLocalY + it - 1, z], clipFlag1) || !collision.canMove(flags[baseX, baseY, currLocalX + it, y, z], clipFlag2) } if (!blocked) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } /* south-east to north-west */ x = currLocalX - 1 y = currLocalY + 1 dirFlag = DirectionFlag.SOUTH_EAST if (currLocalX > 0 && currLocalY < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, x, currLocalY + srcSize, z], CollisionFlag.BLOCK_NORTH_WEST_ROUTE_BLOCKER ) ) { val clipFlag1 = CollisionFlag.BLOCK_NORTH_AND_SOUTH_EAST_ROUTE_BLOCKER val clipFlag2 = CollisionFlag.BLOCK_SOUTH_EAST_AND_WEST_ROUTE_BLOCKER val blocked = (1 until srcSize).any { !collision.canMove(flags[baseX, baseY, x, currLocalY + it, z], clipFlag1) || !collision.canMove(flags[baseX, baseY, currLocalX + it - 1, currLocalY + srcSize, z], clipFlag2) } if (!blocked) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } /* south-west to north-east */ x = currLocalX + 1 y = currLocalY + 1 dirFlag = DirectionFlag.SOUTH_WEST if (currLocalX < relativeSearchSize && currLocalY < relativeSearchSize && getDirection(x, y) == 0 && collision.canMove( flags[baseX, baseY, currLocalX + srcSize, currLocalY + srcSize, z], CollisionFlag.BLOCK_NORTH_EAST_ROUTE_BLOCKER ) ) { val clipFlag1 = CollisionFlag.BLOCK_SOUTH_EAST_AND_WEST_ROUTE_BLOCKER val clipFlag2 = CollisionFlag.BLOCK_NORTH_AND_SOUTH_WEST_ROUTE_BLOCKER val blocked = (1 until srcSize).any { !collision.canMove(flags[baseX, baseY, currLocalX + it, currLocalY + srcSize, z], clipFlag1) || !collision.canMove(flags[baseX, baseY, currLocalX + srcSize, currLocalY + it, z], clipFlag2) } if (!blocked) { setNextValidLocalCoords(x, y, dirFlag, nextDistance) } } } return false } private fun findClosestApproachPoint( localDestX: Int, localDestY: Int, width: Int, length: Int, ): Boolean { var lowestCost = MAX_ALTERNATIVE_ROUTE_LOWEST_COST var maxAlternativePath = MAX_ALTERNATIVE_ROUTE_SEEK_RANGE val alternativeRouteRange = MAX_ALTERNATIVE_ROUTE_DISTANCE_FROM_DESTINATION val radiusX = localDestX - alternativeRouteRange..localDestX + alternativeRouteRange val radiusY = localDestY - alternativeRouteRange..localDestY + alternativeRouteRange val range = 0 until searchMapSize for (x in radiusX) { for (y in radiusY) { if (x !in range || y !in range || getDistance(x, y) >= MAX_ALTERNATIVE_ROUTE_SEEK_RANGE ) { continue } val dx = if (x < localDestX) { localDestX - x } else if (x > localDestX + width - 1) { x - (width + localDestX - 1) } else { 0 } val dy = if (y < localDestY) { localDestY - y } else if (y > localDestY + length - 1) { y - (localDestY + length - 1) } else { 0 } val cost = dx * dx + dy * dy if (cost < lowestCost || (cost == lowestCost && maxAlternativePath > getDistance(x, y))) { currLocalX = x currLocalY = y lowestCost = cost maxAlternativePath = getDistance(x, y) } } } return lowestCost != MAX_ALTERNATIVE_ROUTE_LOWEST_COST } private fun reset() { graphInfo.fill(DEFAULT_DISTANCE_VALUE shl 7) bufReaderIndex = 0 bufWriterIndex = 0 } private fun setNextValidLocalCoords(localX: Int, localY: Int, direction: Int, distance: Int) { val pathIndex = (localY * searchMapSize) + localX val bitpacked = direction or (distance shl 7) graphInfo[pathIndex] = bitpacked validLocalCoords[bufWriterIndex] = (localX shl 16) or localY bufWriterIndex = (bufWriterIndex + 1) and (ringBufferSize - 1) } @Suppress("NOTHING_TO_INLINE") private inline fun getDistance(localX: Int, localY: Int): Int { val pathIndex = (localY * searchMapSize) + localX return graphInfo[pathIndex] ushr 7 } @Suppress("NOTHING_TO_INLINE") private inline fun getDirection(localX: Int, localY: Int): Int { val pathIndex = (localY * searchMapSize) + localX return graphInfo[pathIndex] and 0x7F } @Suppress("NOTHING_TO_INLINE") private inline operator fun IntArray.get(localX: Int, localY: Int): Int { val index = (localY * searchMapSize) + localX return this[index] } @Suppress("NOTHING_TO_INLINE") private inline operator fun Array<IntArray?>.get(baseX: Int, baseY: Int, localX: Int, localY: Int, z: Int): Int { val x = baseX + localX val y = baseY + localY val zone = this[getZoneIndex(x, y, z)] ?: return -1 return zone[getIndexInZone(x, y)] } private companion object { private val FAILED_ROUTE = Route(ArrayDeque(), alternative = false, success = false) } } @Suppress("NOTHING_TO_INLINE") internal inline fun getZoneIndex(x: Int, y: Int, z: Int): Int { return (y shr 3) or ((x shr 3) shl 11) or (z shl 22) } @Suppress("NOTHING_TO_INLINE") internal inline fun getIndexInZone(x: Int, y: Int): Int { return (x and 0x7) or ((y and 0x7) shl 3) } fun routeEntityToObject(entity: Entity, obj: GameObject, maxTurns: Int = DEFAULT_MAX_TURNS): Route { return PathFinder(flags = WorldCollision.allFlags, useRouteBlockerFlags = true) .findPath( entity.x, entity.y, obj.x, obj.y, entity.plane, collision = entity.collisionStrategy, srcSize = entity.size, destWidth = if (obj.rotation == 0 || obj.rotation == 2) obj.definitions.getSizeX() else obj.definitions.getSizeY(), destHeight = if (obj.rotation == 0 || obj.rotation == 2) obj.definitions.getSizeY() else obj.definitions.getSizeX(), objRot = obj.rotation, objShape = if (obj.routeType == RouteType.WALK_ONTO) -1 else obj.type.id, accessBitMask = if (obj.rotation != 0) ((obj.definitions.accessBlockFlag shl obj.rotation) and 0xF) + (obj.definitions.accessBlockFlag shr (4 - obj.rotation)) else obj.definitions.accessBlockFlag, maxTurns = maxTurns ) } fun routeEntityToEntity(entity: Entity, target: Entity, maxTurns: Int = DEFAULT_MAX_TURNS): Route { return PathFinder(flags = WorldCollision.allFlags, useRouteBlockerFlags = true) .findPath( entity.x, entity.y, target.x, target.y, entity.plane, collision = entity.collisionStrategy, objShape = -2, srcSize = entity.size, destWidth = target.size, destHeight = target.size, maxTurns = maxTurns ) } fun routeEntityToTile(entity: Entity, tile: Tile, maxTurns: Int = DEFAULT_MAX_TURNS): Route { return PathFinder(flags = WorldCollision.allFlags, useRouteBlockerFlags = true) .findPath(entity.x, entity.y, tile.x, tile.y, entity.plane, collision = entity.collisionStrategy, srcSize = entity.size, maxTurns = maxTurns) } fun routeEntityWalkRequest(entity: Entity, request: Walk, maxTurns: Int = DEFAULT_MAX_TURNS): Route { return PathFinder(flags = WorldCollision.allFlags, useRouteBlockerFlags = true) .findPath(entity.x, entity.y, request.x, request.y, entity.plane, collision = entity.collisionStrategy, srcSize = entity.size, maxTurns = maxTurns) } fun routeEntityTo(entity: Entity, target: Any, maxTurns: Int = DEFAULT_MAX_TURNS): Route { return when(target) { is Entity -> routeEntityToEntity(entity, target, maxTurns) is GameObject -> routeEntityToObject(entity, target, maxTurns) is GroundItem -> routeEntityToTile(entity, target.tile, maxTurns) is Tile -> routeEntityToTile(entity, target, maxTurns) else -> throw IllegalStateException("Unexpected value: $target") } } fun walkRoute(entity: Entity, route: Route, forceSteps: Boolean): Boolean { if (!route.success) return false if (entity is Player) entity.stopAll() entity.resetWalkSteps() addSteps(entity, route, forceSteps) return true } fun addSteps(entity: Entity, route: Route, forceSteps: Boolean, maxSteps: Int = -1) { var lastStep: RouteCoordinates? = null for (coord in route.coords) { if (!entity.addWalkSteps(coord.x, coord.y, maxSteps, true, forceSteps)) break lastStep = coord } if (lastStep != null && entity is Player) { val tile = Tile.of(lastStep.x, lastStep.y, entity.plane) entity.session.writeToQueue(MinimapFlag(tile.getXInScene(entity.getSceneBaseChunkId()), tile.getYInScene(entity.getSceneBaseChunkId()))) } }
package com.rs.engine.pathfinder /** * @author Kris | 16/03/2022 */ public class StepValidator(private val flags: Array<IntArray?>) { public fun canTravel( level: Int, x: Int, y: Int, offsetX: Int, offsetY: Int, size: Int = 1, extraFlag: Int, collision: CollisionStrategy = CollisionStrategyType.NORMAL.strategy, ): Boolean { val blocked = when { offsetX == 0 && offsetY == -1 -> isBlockedSouth(flags, level, x, y, size, extraFlag, collision) offsetX == 0 && offsetY == 1 -> isBlockedNorth(flags, level, x, y, size, extraFlag, collision) offsetX == -1 && offsetY == 0 -> isBlockedWest(flags, level, x, y, size, extraFlag, collision) offsetX == 1 && offsetY == 0 -> isBlockedEast(flags, level, x, y, size, extraFlag, collision) offsetX == -1 && offsetY == -1 -> isBlockedSouthWest(flags, level, x, y, size, extraFlag, collision) offsetX == -1 && offsetY == 1 -> isBlockedNorthWest(flags, level, x, y, size, extraFlag, collision) offsetX == 1 && offsetY == -1 -> isBlockedSouthEast(flags, level, x, y, size, extraFlag, collision) offsetX == 1 && offsetY == 1 -> isBlockedNorthEast(flags, level, x, y, size, extraFlag, collision) else -> error("Invalid offsets: $offsetX, $offsetY") } return !blocked } @Suppress("NOTHING_TO_INLINE") private inline operator fun Array<IntArray?>.get(x: Int, y: Int, level: Int): Int { val zone = this[getZoneIndex(x, y, level)] ?: return -1 return zone[getIndexInZone(x, y)] } private fun isBlockedSouth( flags: Array<IntArray?>, level: Int, x: Int, y: Int, size: Int, extraFlag: Int, collision: CollisionStrategy ): Boolean { return when (size) { 1 -> !collision.canMove(flags[x, y - 1, level], BLOCK_SOUTH or extraFlag) 2 -> !collision.canMove(flags[x, y - 1, level], BLOCK_SOUTH_WEST or extraFlag) || !collision.canMove(flags[x + 1, y - 1, level], BLOCK_SOUTH_EAST or extraFlag) else -> { if ( !collision.canMove(flags[x, y - 1, level], BLOCK_SOUTH_WEST or extraFlag) || !collision.canMove(flags[x + size - 1, y - 1, level], BLOCK_SOUTH_EAST or extraFlag) ) { return true } for (midX in x + 1 until x + size - 1) { if (!collision.canMove( flags[midX, y - 1, level], BLOCK_NORTH_EAST_AND_WEST or extraFlag ) ) { return true } } return false } } } private fun isBlockedNorth( flags: Array<IntArray?>, level: Int, x: Int, y: Int, size: Int, extraFlag: Int, collision: CollisionStrategy ): Boolean { return when (size) { 1 -> !collision.canMove(flags[x, y + 1, level], BLOCK_NORTH or extraFlag) 2 -> !collision.canMove(flags[x, y + 2, level], BLOCK_NORTH_WEST or extraFlag) || !collision.canMove(flags[x + 1, y + 2, level], BLOCK_NORTH_EAST or extraFlag) else -> { if ( !collision.canMove(flags[x, y + size, level], BLOCK_NORTH_WEST or extraFlag) || !collision.canMove( flags[x + size - 1, y + size, level], BLOCK_NORTH_EAST or extraFlag ) ) { return true } for (midX in x + 1 until x + size - 1) { if (!collision.canMove( flags[midX, y + size, level], BLOCK_SOUTH_EAST_AND_WEST or extraFlag ) ) { return true } } return false } } } private fun isBlockedWest( flags: Array<IntArray?>, level: Int, x: Int, y: Int, size: Int, extraFlag: Int, collision: CollisionStrategy ): Boolean { return when (size) { 1 -> !collision.canMove(flags[x - 1, y, level], BLOCK_WEST or extraFlag) 2 -> !collision.canMove(flags[x - 1, y, level], BLOCK_SOUTH_WEST or extraFlag) || !collision.canMove(flags[x - 1, y + 1, level], BLOCK_NORTH_WEST or extraFlag) else -> { if ( !collision.canMove(flags[x - 1, y, level], BLOCK_SOUTH_WEST or extraFlag) || !collision.canMove(flags[x - 1, y + size - 1, level], BLOCK_NORTH_WEST or extraFlag) ) { return true } for (midY in y + 1 until y + size - 1) { if (!collision.canMove( flags[x - 1, midY, level], BLOCK_NORTH_AND_SOUTH_EAST or extraFlag ) ) { return true } } return false } } } private fun isBlockedEast( flags: Array<IntArray?>, level: Int, x: Int, y: Int, size: Int, extraFlag: Int, collision: CollisionStrategy ): Boolean { return when (size) { 1 -> !collision.canMove(flags[x + 1, y, level], BLOCK_EAST or extraFlag) 2 -> !collision.canMove(flags[x + 2, y, level], BLOCK_SOUTH_EAST or extraFlag) || !collision.canMove(flags[x + 2, y + 1, level], BLOCK_NORTH_EAST or extraFlag) else -> { if ( !collision.canMove(flags[x + size, y, level], BLOCK_SOUTH_EAST or extraFlag) || !collision.canMove( flags[x + size, y + size - 1, level], BLOCK_NORTH_EAST or extraFlag ) ) { return true } for (midY in y + 1 until y + size - 1) { if (!collision.canMove( flags[x + size, midY, level], BLOCK_NORTH_AND_SOUTH_WEST or extraFlag ) ) { return true } } return false } } } private fun isBlockedSouthWest( flags: Array<IntArray?>, level: Int, x: Int, y: Int, size: Int, extraFlag: Int, collision: CollisionStrategy ): Boolean { return when (size) { 1 -> !collision.canMove(flags[x - 1, y - 1, level], BLOCK_SOUTH_WEST or extraFlag) || !collision.canMove(flags[x - 1, y, level], BLOCK_WEST or extraFlag) || !collision.canMove(flags[x, y - 1, level], BLOCK_SOUTH or extraFlag) 2 -> !collision.canMove(flags[x - 1, y, level], BLOCK_NORTH_AND_SOUTH_EAST or extraFlag) || !collision.canMove(flags[x - 1, y - 1, level], BLOCK_SOUTH_WEST or extraFlag) || !collision.canMove(flags[x, y - 1, level], BLOCK_NORTH_EAST_AND_WEST or extraFlag) else -> { if (!collision.canMove(flags[x - 1, y - 1, level], BLOCK_SOUTH_WEST or extraFlag)) { return true } for (mid in 1 until size) { if ( !collision.canMove( flags[x - 1, y + mid - 1, level], BLOCK_NORTH_AND_SOUTH_EAST or extraFlag ) || !collision.canMove( flags[x + mid - 1, y - 1, level], BLOCK_NORTH_EAST_AND_WEST or extraFlag ) ) { return true } } return false } } } private fun isBlockedNorthWest( flags: Array<IntArray?>, level: Int, x: Int, y: Int, size: Int, extraFlag: Int, collision: CollisionStrategy ): Boolean { return when (size) { 1 -> !collision.canMove(flags[x - 1, y + 1, level], BLOCK_NORTH_WEST or extraFlag) || !collision.canMove(flags[x - 1, y, level], BLOCK_WEST or extraFlag) || !collision.canMove(flags[x, y + 1, level], BLOCK_NORTH or extraFlag) 2 -> !collision.canMove(flags[x - 1, y + 1, level], BLOCK_NORTH_AND_SOUTH_EAST or extraFlag) || !collision.canMove(flags[x - 1, y + 2, level], BLOCK_NORTH_WEST or extraFlag) || !collision.canMove(flags[x, y + 2, level], BLOCK_SOUTH_EAST_AND_WEST or extraFlag) else -> { if (!collision.canMove(flags[x - 1, y + size, level], BLOCK_NORTH_WEST or extraFlag)) { return true } for (mid in 1 until size) { if ( !collision.canMove( flags[x - 1, y + mid, level], BLOCK_NORTH_AND_SOUTH_EAST or extraFlag ) || !collision.canMove( flags[x + mid - 1, y + size, level], BLOCK_SOUTH_EAST_AND_WEST or extraFlag ) ) { return true } } return false } } } private fun isBlockedSouthEast( flags: Array<IntArray?>, level: Int, x: Int, y: Int, size: Int, extraFlag: Int, collision: CollisionStrategy ): Boolean { return when (size) { 1 -> !collision.canMove(flags[x + 1, y - 1, level], BLOCK_SOUTH_EAST or extraFlag) || !collision.canMove(flags[x + 1, y, level], BLOCK_EAST or extraFlag) || !collision.canMove(flags[x, y - 1, level], BLOCK_SOUTH or extraFlag) 2 -> !collision.canMove(flags[x + 1, y - 1, level], BLOCK_NORTH_EAST_AND_WEST or extraFlag) || !collision.canMove(flags[x + 2, y - 1, level], BLOCK_SOUTH_EAST or extraFlag) || !collision.canMove(flags[x + 2, y, level], BLOCK_NORTH_AND_SOUTH_WEST or extraFlag) else -> { if (!collision.canMove( flags[x + size, y - 1, level], BLOCK_SOUTH_EAST or extraFlag ) ) return true for (mid in 1 until size) { if ( !collision.canMove( flags[x + size, y + mid - 1, level], BLOCK_NORTH_AND_SOUTH_WEST or extraFlag ) || !collision.canMove( flags[x + mid, y - 1, level], BLOCK_NORTH_EAST_AND_WEST or extraFlag ) ) { return true } } return false } } } private fun isBlockedNorthEast( flags: Array<IntArray?>, level: Int, x: Int, y: Int, size: Int, extraFlag: Int, collision: CollisionStrategy ): Boolean { return when (size) { 1 -> !collision.canMove(flags[x + 1, y + 1, level], BLOCK_NORTH_EAST or extraFlag) || !collision.canMove(flags[x + 1, y, level], BLOCK_EAST or extraFlag) || !collision.canMove(flags[x, y + 1, level], BLOCK_NORTH or extraFlag) 2 -> !collision.canMove(flags[x + 1, y + 2, level], BLOCK_SOUTH_EAST_AND_WEST or extraFlag) || !collision.canMove(flags[x + 2, y + 2, level], BLOCK_NORTH_EAST or extraFlag) || !collision.canMove(flags[x + 2, y + 1, level], BLOCK_NORTH_AND_SOUTH_WEST or extraFlag) else -> { if (!collision.canMove(flags[x + size, y + size, level], BLOCK_NORTH_EAST or extraFlag)) { return true } for (mid in 1 until size) { if ( !collision.canMove( flags[x + mid, y + size, level], BLOCK_SOUTH_EAST_AND_WEST or extraFlag ) || !collision.canMove( flags[x + size, y + mid, level], BLOCK_NORTH_AND_SOUTH_WEST or extraFlag ) ) { return true } } return false } } } }
package com.rs.engine.pathfinder class WalkStep(@JvmField val dir: Direction, @JvmField val x: Int, @JvmField val y: Int, private var clip: Boolean) { fun checkClip(): Boolean { return clip } fun setCheckClip(clip: Boolean) { this.clip = clip } override fun toString(): String { return "[$x, $y, $dir, $clip]" } }
package com.rs.engine.pathfinder object WorldCollision { private const val CHUNK_SIZE = 2048 //2048 chunk size = max capacity 16384x16384 tiles val allFlags: Array<IntArray?> = arrayOfNulls(CHUNK_SIZE * CHUNK_SIZE * 4) private val LOCK = Any() @JvmStatic fun clipNPC(npc: NPC) { if (!npc.blocksOtherNpcs()) return val lastTile = if (npc.lastTile == null) npc.tile else npc.lastTile fillNPCClip(lastTile, npc.size, false) if (!npc.hasFinished()) fillNPCClip(npc.tile, npc.size, true) } @JvmStatic fun fillNPCClip(tile: Tile, size: Int, blocks: Boolean) { for (x in 0 until size) for (y in 0 until size) { val local = tile.transform(x, y) if (blocks) addClipNPC(local) else removeClipNPC(local) } } @JvmStatic fun getClipNPC(tile: Tile): Boolean { return ClipFlag.flagged(getFlags(tile), ClipFlag.BW_NPC) } @JvmStatic fun checkNPCClip(npc: NPC, dir: Direction): Boolean { val size = npc.size val toX = npc.x + dir.dx val toY = npc.y + dir.dy val eastMostX = npc.x + (size - 1) val northMostY = npc.y + (size - 1) for (x in toX until (toX + size)) for (y in toY until (toY + size)) { if (x >= npc.x && x <= eastMostX && y >= npc.y && y <= northMostY) /* stepping within itself, allow it */ continue if (getClipNPC(Tile.of(x, y, npc.plane))) return false } return true } @JvmStatic fun clearChunk(chunkCollisionHash: Int) { synchronized(LOCK) { allFlags[chunkCollisionHash] = null } } @JvmStatic fun removeFlag(tile: Tile, vararg flags: ClipFlag) { var flag = 0 for (f in flags) flag = flag or f.flag removeFlag(tile, flag) } @JvmStatic fun addFlag(tile: Tile, vararg flags: ClipFlag) { var flag = 0 for (f in flags) flag = flag or f.flag addFlag(tile, flag) } @JvmStatic fun setFlags(tile: Tile, vararg flags: ClipFlag) { var flag = 0 for (f in flags) flag = flag or f.flag setFlags(tile, flag) } @JvmStatic fun addBlockedTile(tile: Tile) { addFlag(tile, ClipFlag.PFBW_FLOOR) } @JvmStatic fun removeBlockedTile(tile: Tile) { removeFlag(tile, ClipFlag.PFBW_FLOOR) } @JvmStatic fun addBlockWalkAndProj(tile: Tile) { addFlag(tile, ClipFlag.PFBW_GROUND_DECO) } @JvmStatic fun removeBlockWalkAndProj(tile: Tile) { removeFlag(tile, ClipFlag.PFBW_GROUND_DECO) } @JvmStatic fun addClipNPC(tile: Tile) { addFlag(tile, ClipFlag.BW_NPC) } @JvmStatic fun removeClipNPC(tile: Tile) { removeFlag(tile, ClipFlag.BW_NPC) } @JvmStatic fun addClipPlayer(tile: Tile) { addFlag(tile, ClipFlag.BW_PLAYER) } @JvmStatic fun removeClipPlayer(tile: Tile) { removeFlag(tile, ClipFlag.BW_PLAYER) } @JvmStatic fun addObject(tile: Tile, sizeX: Int, sizeY: Int, blocksProjectiles: Boolean, pathfinder: Boolean) { var flag = ClipFlag.BW_FULL.flag if (blocksProjectiles) flag = flag or ClipFlag.BP_FULL.flag if (pathfinder) flag = flag or ClipFlag.PF_FULL.flag for (tileX in tile.x() until tile.x() + sizeX) for (tileY in tile.y() until tile.y() + sizeY) addFlag(Tile.of(tileX, tileY, tile.plane().toInt()), flag) } @JvmStatic fun removeObject(tile: Tile, sizeX: Int, sizeY: Int, blocksProjectiles: Boolean, pathfinder: Boolean) { var flag = ClipFlag.BW_FULL.flag if (blocksProjectiles) flag = flag or ClipFlag.BP_FULL.flag if (pathfinder) flag = flag or ClipFlag.PF_FULL.flag for (tileX in tile.x() until tile.x() + sizeX) for (tileY in tile.y() until tile.y() + sizeY) removeFlag(Tile.of(tileX, tileY, tile.plane().toInt()), flag) } @JvmStatic fun addWall(tile: Tile, type: ObjectType?, rotation: Int, blocksProjectiles: Boolean, pathfinder: Boolean) { when (type) { ObjectType.WALL_STRAIGHT -> { when (rotation) { 0 -> { addFlag(tile, ClipFlag.blockWest(true, blocksProjectiles, pathfinder)) addFlag(tile.transform(-1, 0, 0), ClipFlag.blockEast(true, blocksProjectiles, pathfinder)) } 1 -> { addFlag(tile, ClipFlag.blockNorth(true, blocksProjectiles, pathfinder)) addFlag(tile.transform(0, 1, 0), ClipFlag.blockSouth(true, blocksProjectiles, pathfinder)) } 2 -> { addFlag(tile, ClipFlag.blockEast(true, blocksProjectiles, pathfinder)) addFlag(tile.transform(1, 0, 0), ClipFlag.blockWest(true, blocksProjectiles, pathfinder)) } 3 -> { addFlag(tile, ClipFlag.blockSouth(true, blocksProjectiles, pathfinder)) addFlag(tile.transform(0, -1, 0), ClipFlag.blockNorth(true, blocksProjectiles, pathfinder)) } } } ObjectType.WALL_DIAGONAL_CORNER, ObjectType.WALL_STRAIGHT_CORNER -> { when (rotation) { 0 -> { addFlag(tile, ClipFlag.blockNorthWest(true, blocksProjectiles, pathfinder)) addFlag(tile.transform(-1, 1, 0), ClipFlag.blockSouthEast(true, blocksProjectiles, pathfinder)) } 1 -> { addFlag(tile, ClipFlag.blockNorthEast(true, blocksProjectiles, pathfinder)) addFlag(tile.transform(1, 1, 0), ClipFlag.blockSouthWest(true, blocksProjectiles, pathfinder)) } 2 -> { addFlag(tile, ClipFlag.blockSouthEast(true, blocksProjectiles, pathfinder)) addFlag(tile.transform(1, -1, 0), ClipFlag.blockNorthWest(true, blocksProjectiles, pathfinder)) } 3 -> { addFlag(tile, ClipFlag.blockSouthWest(true, blocksProjectiles, pathfinder)) addFlag(tile.transform(-1, -1, 0), ClipFlag.blockNorthEast(true, blocksProjectiles, pathfinder)) } } } ObjectType.WALL_WHOLE_CORNER -> { when (rotation) { 0 -> { addFlag(tile, ClipFlag.blockNorth(true, blocksProjectiles, pathfinder) or ClipFlag.blockWest(true, blocksProjectiles, pathfinder)) addFlag(tile.transform(-1, 0, 0), ClipFlag.blockEast(true, blocksProjectiles, pathfinder)) addFlag(tile.transform(0, 1, 0), ClipFlag.blockSouth(true, blocksProjectiles, pathfinder)) } 1 -> { addFlag(tile, ClipFlag.blockNorth(true, blocksProjectiles, pathfinder) or ClipFlag.blockEast(true, blocksProjectiles, pathfinder)) addFlag(tile.transform(0, 1, 0), ClipFlag.blockSouth(true, blocksProjectiles, pathfinder)) addFlag(tile.transform(1, 0, 0), ClipFlag.blockWest(true, blocksProjectiles, pathfinder)) } 2 -> { addFlag(tile, ClipFlag.blockEast(true, blocksProjectiles, pathfinder) or ClipFlag.blockSouth(true, blocksProjectiles, pathfinder)) addFlag(tile.transform(1, 0, 0), ClipFlag.blockWest(true, blocksProjectiles, pathfinder)) addFlag(tile.transform(0, -1, 0), ClipFlag.blockNorth(true, blocksProjectiles, pathfinder)) } 3 -> { addFlag(tile, ClipFlag.blockSouth(true, blocksProjectiles, pathfinder) or ClipFlag.blockWest(true, blocksProjectiles, pathfinder)) addFlag(tile.transform(0, -1, 0), ClipFlag.blockNorth(true, blocksProjectiles, pathfinder)) addFlag(tile.transform(-1, 0, 0), ClipFlag.blockEast(true, blocksProjectiles, pathfinder)) } } } else -> {} } } @JvmStatic fun removeWall(tile: Tile, type: ObjectType?, rotation: Int, blocksProjectiles: Boolean, pathfinder: Boolean) { when (type) { ObjectType.WALL_STRAIGHT -> { when (rotation) { 0 -> { removeFlag(tile, ClipFlag.blockWest(true, blocksProjectiles, pathfinder)) removeFlag(tile.transform(-1, 0, 0), ClipFlag.blockEast(true, blocksProjectiles, pathfinder)) } 1 -> { removeFlag(tile, ClipFlag.blockNorth(true, blocksProjectiles, pathfinder)) removeFlag(tile.transform(0, 1, 0), ClipFlag.blockSouth(true, blocksProjectiles, pathfinder)) } 2 -> { removeFlag(tile, ClipFlag.blockEast(true, blocksProjectiles, pathfinder)) removeFlag(tile.transform(1, 0, 0), ClipFlag.blockWest(true, blocksProjectiles, pathfinder)) } 3 -> { removeFlag(tile, ClipFlag.blockSouth(true, blocksProjectiles, pathfinder)) removeFlag(tile.transform(0, -1, 0), ClipFlag.blockNorth(true, blocksProjectiles, pathfinder)) } } } ObjectType.WALL_DIAGONAL_CORNER, ObjectType.WALL_STRAIGHT_CORNER -> { when (rotation) { 0 -> { removeFlag(tile, ClipFlag.blockNorthWest(true, blocksProjectiles, pathfinder)) removeFlag(tile.transform(-1, 1, 0), ClipFlag.blockSouthEast(true, blocksProjectiles, pathfinder)) } 1 -> { removeFlag(tile, ClipFlag.blockNorthEast(true, blocksProjectiles, pathfinder)) removeFlag(tile.transform(1, 1, 0), ClipFlag.blockSouthWest(true, blocksProjectiles, pathfinder)) } 2 -> { removeFlag(tile, ClipFlag.blockSouthEast(true, blocksProjectiles, pathfinder)) removeFlag(tile.transform(1, -1, 0), ClipFlag.blockNorthWest(true, blocksProjectiles, pathfinder)) } 3 -> { removeFlag(tile, ClipFlag.blockSouthWest(true, blocksProjectiles, pathfinder)) removeFlag(tile.transform(-1, -1, 0), ClipFlag.blockNorthEast(true, blocksProjectiles, pathfinder)) } } } ObjectType.WALL_WHOLE_CORNER -> { when (rotation) { 0 -> { removeFlag(tile, ClipFlag.blockNorth(true, blocksProjectiles, pathfinder) or ClipFlag.blockWest(true, blocksProjectiles, pathfinder)) removeFlag(tile.transform(-1, 0, 0), ClipFlag.blockEast(true, blocksProjectiles, pathfinder)) removeFlag(tile.transform(0, 1, 0), ClipFlag.blockSouth(true, blocksProjectiles, pathfinder)) } 1 -> { removeFlag(tile, ClipFlag.blockNorth(true, blocksProjectiles, pathfinder) or ClipFlag.blockEast(true, blocksProjectiles, pathfinder)) removeFlag(tile.transform(0, 1, 0), ClipFlag.blockSouth(true, blocksProjectiles, pathfinder)) removeFlag(tile.transform(1, 0, 0), ClipFlag.blockWest(true, blocksProjectiles, pathfinder)) } 2 -> { removeFlag(tile, ClipFlag.blockEast(true, blocksProjectiles, pathfinder) or ClipFlag.blockSouth(true, blocksProjectiles, pathfinder)) removeFlag(tile.transform(1, 0, 0), ClipFlag.blockWest(true, blocksProjectiles, pathfinder)) removeFlag(tile.transform(0, -1, 0), ClipFlag.blockNorth(true, blocksProjectiles, pathfinder)) } 3 -> { removeFlag(tile, ClipFlag.blockSouth(true, blocksProjectiles, pathfinder) or ClipFlag.blockWest(true, blocksProjectiles, pathfinder)) removeFlag(tile.transform(0, -1, 0), ClipFlag.blockNorth(true, blocksProjectiles, pathfinder)) removeFlag(tile.transform(-1, 0, 0), ClipFlag.blockEast(true, blocksProjectiles, pathfinder)) } } } else -> {} } } @JvmStatic fun getFlags(tile: Tile): Int { synchronized(LOCK) { val chunkId = tile.chunkId if (allFlags[chunkId] == null) return -1 return allFlags[chunkId]!![tile.xInChunk or (tile.yInChunk shl 3)] } } @JvmStatic fun getFlags(x: Int, y: Int, plane: Int): Int { synchronized(LOCK) { val chunkId = MapUtils.encode(MapUtils.Structure.CHUNK, x shr 3, y shr 3, plane) if (allFlags[chunkId] == null) return -1 return allFlags[chunkId]!![x and 7 or ((y and 7) shl 3)] } } @JvmStatic fun addFlag(tile: Tile, flag: Int) { synchronized(LOCK) { val chunkId = tile.chunkId if (allFlags[chunkId] == null) allFlags[chunkId] = IntArray(64) allFlags[chunkId]!![tile.xInChunk or (tile.yInChunk shl 3)] = allFlags[chunkId]!![tile.xInChunk or (tile.yInChunk shl 3)] or flag } } @JvmStatic fun removeFlag(tile: Tile, flag: Int) { synchronized(LOCK) { val chunkId = tile.chunkId if (allFlags[chunkId] == null) allFlags[chunkId] = IntArray(64) allFlags[chunkId]!![tile.xInChunk or (tile.yInChunk shl 3)] = allFlags[chunkId]!![tile.xInChunk or (tile.yInChunk shl 3)] and flag.inv() } } @JvmStatic fun setFlags(tile: Tile, flag: Int) { synchronized(LOCK) { val chunkId = tile.chunkId if (allFlags[chunkId] == null) allFlags[chunkId] = IntArray(64) allFlags[chunkId]!![tile.xInChunk or (tile.yInChunk shl 3)] = flag } } @JvmStatic fun clip(obj: GameObject) { if (obj.getId() == -1) return val type: ObjectType = obj.type val rotation: Int = obj.rotation val defs: ObjectDefinitions = ObjectDefinitions.getDefs(obj.id) if (defs.getClipType() == 0) return when (type) { ObjectType.WALL_STRAIGHT, ObjectType.WALL_DIAGONAL_CORNER, ObjectType.WALL_WHOLE_CORNER, ObjectType.WALL_STRAIGHT_CORNER -> addWall(obj.tile, type, rotation, defs.blocks(), !defs.ignoresPathfinder) ObjectType.WALL_INTERACT, ObjectType.SCENERY_INTERACT, ObjectType.GROUND_INTERACT, ObjectType.STRAIGHT_SLOPE_ROOF, ObjectType.DIAGONAL_SLOPE_ROOF, ObjectType.DIAGONAL_SLOPE_CONNECT_ROOF, ObjectType.STRAIGHT_SLOPE_CORNER_CONNECT_ROOF, ObjectType.STRAIGHT_SLOPE_CORNER_ROOF, ObjectType.STRAIGHT_FLAT_ROOF, ObjectType.STRAIGHT_BOTTOM_EDGE_ROOF, ObjectType.DIAGONAL_BOTTOM_EDGE_CONNECT_ROOF, ObjectType.STRAIGHT_BOTTOM_EDGE_CONNECT_ROOF, ObjectType.STRAIGHT_BOTTOM_EDGE_CONNECT_CORNER_ROOF -> { val sizeX: Int val sizeY: Int if (rotation != 1 && rotation != 3) { sizeX = defs.getSizeX() sizeY = defs.getSizeY() } else { sizeX = defs.getSizeY() sizeY = defs.getSizeX() } addObject(obj.tile, sizeX, sizeY, defs.blocks(), !defs.ignoresPathfinder) } ObjectType.GROUND_DECORATION -> if (defs.clipType == 1) addBlockWalkAndProj(obj.tile) else -> {} } } @JvmStatic fun unclip(tile: Tile) { setFlags(tile, 0) } @JvmStatic fun unclip(obj: GameObject) { if (obj.id == -1) // dont clip or noclip with id -1 return val type: ObjectType = obj.type val rotation: Int = obj.rotation val defs: ObjectDefinitions = ObjectDefinitions.getDefs(obj.id) if (defs.getClipType() == 0) return when (type) { ObjectType.WALL_STRAIGHT, ObjectType.WALL_DIAGONAL_CORNER, ObjectType.WALL_WHOLE_CORNER, ObjectType.WALL_STRAIGHT_CORNER -> removeWall(obj.getTile(), type, rotation, defs.blocks(), !defs.ignoresPathfinder) ObjectType.WALL_INTERACT, ObjectType.SCENERY_INTERACT, ObjectType.GROUND_INTERACT, ObjectType.STRAIGHT_SLOPE_ROOF, ObjectType.DIAGONAL_SLOPE_ROOF, ObjectType.DIAGONAL_SLOPE_CONNECT_ROOF, ObjectType.STRAIGHT_SLOPE_CORNER_CONNECT_ROOF, ObjectType.STRAIGHT_SLOPE_CORNER_ROOF, ObjectType.STRAIGHT_FLAT_ROOF, ObjectType.STRAIGHT_BOTTOM_EDGE_ROOF, ObjectType.DIAGONAL_BOTTOM_EDGE_CONNECT_ROOF, ObjectType.STRAIGHT_BOTTOM_EDGE_CONNECT_ROOF, ObjectType.STRAIGHT_BOTTOM_EDGE_CONNECT_CORNER_ROOF -> { val sizeX: Int val sizeY: Int if (rotation == 1 || rotation == 3) { sizeX = defs.getSizeY() sizeY = defs.getSizeX() } else { sizeX = defs.getSizeX() sizeY = defs.getSizeY() } removeObject(obj.tile, sizeX, sizeY, defs.blocks(), !defs.ignoresPathfinder) } ObjectType.GROUND_DECORATION -> if (defs.clipType == 1) removeBlockWalkAndProj(obj.tile) else -> {} } } }
package com.rs.engine.pathfinder /** * @author Kris | 16/03/2022 */ @JvmInline public value class ZoneCoords(public val packedCoords: Int) { public constructor( x: Int, y: Int, z: Int, ) : this((x and 0x7FF) or ((y and 0x7FF) shl 11) or ((z and 0x3) shl 22)) public val x: Int get() = packedCoords and 0x7FF public val y: Int get() = (packedCoords shr 11) and 0x7FF public val z: Int get() = (packedCoords shr 22) and 0x3 /** * Converts these zone coordinates to the absolute coordinates of the south-western * tile of this zone. */ public fun toAbsoluteCoords(): AbsoluteCoords = AbsoluteCoords(x shl 3, y shl 3, z) override fun toString(): String = "ZoneCoords($x, $y, $z)" }
package com.rs.engine.pathfinder /** * @author Kris | 16/03/2022 * * A class to hold all the flags for every tile in the game. * The flags are placed into a two-dimensional array, where the outer array * returns the flags array for a given zone(1 x 8 x 8 flags total). * This is done for memory reasons, as it is rather expensive to allocate a * 16384 x 16384 x 4 size int array all in one go(it would also require over a * gigabyte of memory). * * Without any flags, this object initializes as a size 16,777,216 array of * int arrays, all of which are null. This consumes roughly ~67mb of memory to * initialize. */ @Suppress("NOTHING_TO_INLINE") public class ZoneFlags { /** * A two-dimensional array to carry all the flags of the game, including instances. */ public val flags: Array<IntArray?> = arrayOfNulls(TOTAL_ZONES) /** * Destroys the flags array for the zone at [zoneCoords]. */ public inline fun alloc(zoneCoords: ZoneCoords): IntArray { val packed = zoneCoords.packedCoords val current = flags[packed] if (current != null) return current val new = IntArray(ZONE_SIZE) flags[packed] = new return new } /** * Destroys the flags array for the zone at [zoneCoords]. * It should be noted that [zoneCoords] are not absolute. * To convert from absolute coordinates to zone coordinates, divide the x and y values * each by 8(the size of one zone). * Example: * Converting absolute coordinates [3251, 9422, 1] to [zoneCoords] produces [406, 1177, 1]. */ public inline fun destroy(zoneCoords: ZoneCoords) { flags[zoneCoords.packedCoords] = null } /** * Gets the flag at the absolute coordinates [x, y, z], returning the [default] if the zone is not allocated. */ public inline operator fun get(x: Int, y: Int, z: Int, default: Int = -1): Int { val zoneCoords = ZoneCoords(x shr 3, y shr 3, z) val array = flags[zoneCoords.packedCoords] ?: return default return array[zoneLocal(x, y)] } /** * Sets the flag at the absolute coordinates [x, y, z] to [flag]. */ public inline operator fun set(x: Int, y: Int, z: Int, flag: Int) { alloc(ZoneCoords(x shr 3, y shr 3, z))[zoneLocal(x, y)] = flag } /** * Adds the [flag] bits to the existing flag at the absolute coordinates [x, y, z]. */ public inline fun add(x: Int, y: Int, z: Int, flag: Int) { val flags = alloc(ZoneCoords(x shr 3, y shr 3, z)) val index = zoneLocal(x, y) val cur = flags[index] flags[index] = cur or flag } /** * Removes the [flag] bits from the existing flag at the absolute coordinates [x, y, z]. */ public inline fun remove(x: Int, y: Int, z: Int, flag: Int) { val flags = alloc(ZoneCoords(x shr 3, y shr 3, z)) val index = zoneLocal(x, y) val cur = flags[index] flags[index] = cur and flag.inv() } /** * Gets the flag at the absolute coordinates, returning the [default] if the zone is not allocated. */ public inline operator fun get(absoluteCoords: AbsoluteCoords, default: Int = -1): Int { return get(absoluteCoords.x, absoluteCoords.y, absoluteCoords.z, default) } /** * Sets the flag at the absolute coordinates to [flag]. */ public inline operator fun set(absoluteCoords: AbsoluteCoords, flag: Int) { set(absoluteCoords.x, absoluteCoords.y, absoluteCoords.z, flag) } /** * Adds the [flag] bits to the existing flag at the absolute coordinates. */ public inline fun add(absoluteCoords: AbsoluteCoords, flag: Int) { add(absoluteCoords.x, absoluteCoords.y, absoluteCoords.z, flag) } /** * Removes the [flag] bits from the existing flag at the absolute coordinates. */ public inline fun remove(absoluteCoords: AbsoluteCoords, flag: Int) { remove(absoluteCoords.x, absoluteCoords.y, absoluteCoords.z, flag) } public inline fun zoneLocal(x: Int, y: Int): Int = (x and 0x7) or ((y and 0x7) shl 3) public companion object { public const val TOTAL_ZONES: Int = 2048 * 2048 * 4 public const val ZONE_SIZE: Int = 8 * 8 } }
package com.rs.engine.pathfinder.bound /** * @author Kris | 12/09/2021 */ public object RectangleBoundaryUtils { public fun collides( srcX: Int, srcY: Int, destX: Int, destY: Int, srcWidth: Int, srcHeight: Int, destWidth: Int, destHeight: Int ): Boolean = if (srcX >= destX + destWidth || srcX + srcWidth <= destX) { false } else { srcY < destY + destHeight && destY < srcHeight + srcY } internal fun reachRectangle1( flags: Array<IntArray?>, x: Int, y: Int, z: Int, accessBitMask: Int, destX: Int, destY: Int, destWidth: Int, destHeight: Int ): Boolean { val east = destX + destWidth - 1 val north = destY + destHeight - 1 if (x == destX - 1 && y >= destY && y <= north && (flags[x, y, z] and CollisionFlag.WALL_EAST) == 0 && (accessBitMask and AccessBitFlag.BLOCK_WEST) == 0 ) return true if (x == east + 1 && y >= destY && y <= north && (flags[x, y, z] and CollisionFlag.WALL_WEST) == 0 && (accessBitMask and AccessBitFlag.BLOCK_EAST) == 0 ) return true if (y + 1 == destY && x >= destX && x <= east && (flags[x, y, z] and CollisionFlag.WALL_NORTH) == 0 && (accessBitMask and AccessBitFlag.BLOCK_SOUTH) == 0 ) return true return y == north + 1 && x >= destX && x <= east && (flags[x, y, z] and CollisionFlag.WALL_SOUTH) == 0 && (accessBitMask and AccessBitFlag.BLOCK_NORTH) == 0 } internal fun reachRectangleN( flags: Array<IntArray?>, x: Int, y: Int, z: Int, accessBitMask: Int, destX: Int, destY: Int, srcWidth: Int, srcHeight: Int, destWidth: Int, destHeight: Int ): Boolean { val srcEast = x + srcWidth val srcNorth = srcHeight + y val destEast = destWidth + destX val destNorth = destHeight + destY if (destEast == x && (accessBitMask and AccessBitFlag.BLOCK_EAST) == 0) { val fromY = max(y, destY) val toY = min(srcNorth, destNorth) for (sideY in fromY until toY) { if (flags[destEast - 1, sideY, z] and CollisionFlag.WALL_EAST == 0) { return true } } } else if (srcEast == destX && (accessBitMask and AccessBitFlag.BLOCK_WEST) == 0) { val fromY = max(y, destY) val toY = min(srcNorth, destNorth) for (sideY in fromY until toY) { if (flags[destX, sideY, z] and CollisionFlag.WALL_WEST == 0) { return true } } } else if (y == destNorth && (accessBitMask and AccessBitFlag.BLOCK_NORTH) == 0) { val fromX = max(x, destX) val toX = min(srcEast, destEast) for (sideX in fromX until toX) { if (flags[sideX, destNorth - 1, z] and CollisionFlag.WALL_NORTH == 0) { return true } } } else if (destY == srcNorth && (accessBitMask and AccessBitFlag.BLOCK_SOUTH) == 0) { val fromX = max(x, destX) val toX = min(srcEast, destEast) for (sideX in fromX until toX) { if (flags[sideX, destY, z] and CollisionFlag.WALL_SOUTH == 0) { return true } } } return false } @Suppress("NOTHING_TO_INLINE") private inline operator fun Array<IntArray?>.get( x: Int, y: Int, z: Int ): Int { val zone = this[getZoneIndex(x, y, z)] ?: return -1 return zone[getIndexInZone(x, y)] } }
package com.rs.engine.pathfinder.bound internal fun reachRectangle( flags: Array<IntArray?>, x: Int, y: Int, z: Int, accessBitMask: Int, destX: Int, destY: Int, srcSize: Int, destWidth: Int, destHeight: Int ): Boolean = when { srcSize > 1 -> { RectangleBoundaryUtils .collides(x, y, destX, destY, srcSize, srcSize, destWidth, destHeight) || RectangleBoundaryUtils.reachRectangleN( flags, x, y, z, accessBitMask, destX, destY, srcSize, srcSize, destWidth, destHeight ) } else -> RectangleBoundaryUtils .collides(x, y, destX, destY, srcSize, srcSize, destWidth, destHeight) || RectangleBoundaryUtils.reachRectangle1( flags, x, y, z, accessBitMask, destX, destY, destWidth, destHeight ) }
package com.rs.engine.pathfinder.bound /** * @author Kris | 12/09/2021 */ internal fun reachExclusiveRectangle( flags: Array<IntArray?>, x: Int, y: Int, z: Int, accessBitMask: Int, destX: Int, destY: Int, srcSize: Int, destWidth: Int, destHeight: Int ): Boolean = when { srcSize > 1 -> { if (RectangleBoundaryUtils.collides(x, y, destX, destY, srcSize, srcSize, destWidth, destHeight)) false else RectangleBoundaryUtils.reachRectangleN( flags, x, y, z, accessBitMask, destX, destY, srcSize, srcSize, destWidth, destHeight ) } else -> { if (RectangleBoundaryUtils.collides(x, y, destX, destY, srcSize, srcSize, destWidth, destHeight)) false else RectangleBoundaryUtils.reachRectangle1( flags, x, y, z, accessBitMask, destX, destY, destWidth, destHeight ) } }
@file:Suppress("DuplicatedCode") package com.rs.engine.pathfinder.bound internal fun reachWall( flags: Array<IntArray?>, x: Int, y: Int, z: Int, destX: Int, destY: Int, srcSize: Int, shape: Int, rot: Int ): Boolean = when { srcSize == 1 && x == destX && y == destY -> true srcSize != 1 && destX >= x && srcSize + x - 1 >= destX && destY >= y && srcSize + y - 1 >= destY -> true srcSize == 1 -> reachWall1( flags, x, y, z, destX, destY, shape, rot ) else -> reachWallN( flags, x, y, z, destX, destY, srcSize, shape, rot ) } private fun reachWall1( flags: Array<IntArray?>, x: Int, y: Int, z: Int, destX: Int, destY: Int, shape: Int, rot: Int ): Boolean { when (shape) { 0 -> { when (rot) { 0 -> { if (x == destX - 1 && y == destY) { return true } if (x == destX && y == destY + 1 && (flags[x, y, z] and CollisionFlag.BLOCK_NORTH) == 0 ) return true if (x == destX && y == destY - 1 && (flags[x, y, z] and CollisionFlag.BLOCK_SOUTH) == 0 ) return true } 1 -> { if (x == destX && y == destY + 1) { return true } if (x == destX - 1 && y == destY && (flags[x, y, z] and CollisionFlag.BLOCK_WEST) == 0 ) return true if (x == destX + 1 && y == destY && (flags[x, y, z] and CollisionFlag.BLOCK_EAST) == 0 ) return true } 2 -> { if (x == destX + 1 && y == destY) { return true } if (x == destX && y == destY + 1 && (flags[x, y, z] and CollisionFlag.BLOCK_NORTH) == 0 ) return true if (x == destX && y == destY - 1 && (flags[x, y, z] and CollisionFlag.BLOCK_SOUTH) == 0 ) return true } 3 -> { if (x == destX && y == destY - 1) { return true } if (x == destX - 1 && y == destY && (flags[x, y, z] and CollisionFlag.BLOCK_WEST) == 0 ) return true if (x == destX + 1 && y == destY && (flags[x, y, z] and CollisionFlag.BLOCK_EAST) == 0 ) return true } } } 2 -> { when (rot) { 0 -> { if (x == destX - 1 && y == destY) { return true } if (x == destX && y == destY + 1) { return true } if (x == destX + 1 && y == destY && (flags[x, y, z] and CollisionFlag.BLOCK_EAST) == 0 ) return true if (x == destX && y == destY - 1 && (flags[x, y, z] and CollisionFlag.BLOCK_SOUTH) == 0 ) return true } 1 -> { if (x == destX - 1 && y == destY && (flags[x, y, z] and CollisionFlag.BLOCK_WEST) == 0 ) return true if (x == destX && y == destY + 1) { return true } if (x == destX + 1 && y == destY) { return true } if (x == destX && y == destY - 1 && (flags[x, y, z] and CollisionFlag.BLOCK_SOUTH) == 0 ) return true } 2 -> { if (x == destX - 1 && y == destY && (flags[x, y, z] and CollisionFlag.BLOCK_WEST) == 0 ) return true if (x == destX && y == destY + 1 && (flags[x, y, z] and CollisionFlag.BLOCK_NORTH) == 0 ) return true if (x == destX + 1 && y == destY) { return true } if (x == destX && y == destY - 1) { return true } } 3 -> { if (x == destX - 1 && y == destY) { return true } if (x == destX && y == destY + 1 && (flags[x, y, z] and CollisionFlag.BLOCK_NORTH) == 0 ) return true if (x == destX + 1 && y == destY && (flags[x, y, z] and CollisionFlag.BLOCK_EAST) == 0 ) return true if (x == destX && y == destY - 1) { return true } } } } 9 -> { if (x == destX && y == destY + 1 && (flags[x, y, z] and CollisionFlag.WALL_SOUTH) == 0 ) return true if (x == destX && y == destY - 1 && (flags[x, y, z] and CollisionFlag.WALL_NORTH) == 0 ) return true if (x == destX - 1 && y == destY && (flags[x, y, z] and CollisionFlag.WALL_EAST) == 0 ) return true return x == destX + 1 && y == destY && (flags[x, y, z] and CollisionFlag.WALL_WEST) == 0 } } return false } private fun reachWallN( flags: Array<IntArray?>, x: Int, y: Int, z: Int, destX: Int, destY: Int, srcSize: Int, shape: Int, rot: Int ): Boolean { val east = x + srcSize - 1 val north = y + srcSize - 1 when (shape) { 0 -> { when (rot) { 0 -> { if (x == destX - srcSize && y <= destY && north >= destY) { return true } if (destX in x..east && y == destY + 1 && (flags[destX, y, z] and CollisionFlag.BLOCK_NORTH) == 0 ) return true if (destX in x..east && y == destY - srcSize && (flags[destX, north, z] and CollisionFlag.BLOCK_SOUTH) == 0 ) return true } 1 -> { if (destX in x..east && y == destY + 1) { return true } if (x == destX - srcSize && y <= destY && north >= destY && (flags[east, destY, z] and CollisionFlag.BLOCK_WEST) == 0 ) return true if (x == destX + 1 && y <= destY && north >= destY && (flags[x, destY, z] and CollisionFlag.BLOCK_EAST) == 0 ) return true } 2 -> { if (x == destX + 1 && y <= destY && north >= destY) { return true } if (destX in x..east && y == destY + 1 && (flags[destX, y, z] and CollisionFlag.BLOCK_NORTH) == 0 ) return true if (destX in x..east && y == destY - srcSize && (flags[destX, north, z] and CollisionFlag.BLOCK_SOUTH) == 0 ) return true } 3 -> { if (destX in x..east && y == destY - srcSize) { return true } if (x == destX - srcSize && y <= destY && north >= destY && (flags[east, destY, z] and CollisionFlag.BLOCK_WEST) == 0 ) return true if (x == destX + 1 && y <= destY && north >= destY && (flags[x, destY, z] and CollisionFlag.BLOCK_EAST) == 0 ) return true } } } 2 -> { when (rot) { 0 -> { if (x == destX - srcSize && y <= destY && north >= destY) { return true } if (destX in x..east && y == destY + 1) { return true } if (x == destX + 1 && y <= destY && north >= destY && (flags[x, destY, z] and CollisionFlag.BLOCK_EAST) == 0 ) return true if (destX in x..east && y == destY - srcSize && (flags[destX, north, z] and CollisionFlag.BLOCK_SOUTH) == 0 ) return true } 1 -> { if (x == destX - srcSize && y <= destY && north >= destY && (flags[east, destY, z] and CollisionFlag.BLOCK_WEST) == 0 ) return true if (destX in x..east && y == destY + 1) { return true } if (x == destX + 1 && y <= destY && north >= destY) { return true } if (destX in x..east && y == destY - srcSize && (flags[destX, north, z] and CollisionFlag.BLOCK_SOUTH) == 0 ) return true } 2 -> { if (x == destX - srcSize && y <= destY && north >= destY && (flags[east, destY, z] and CollisionFlag.BLOCK_WEST) == 0 ) return true if (destX in x..east && y == destY + 1 && (flags[destX, y, z] and CollisionFlag.BLOCK_NORTH) == 0 ) return true if (x == destX + 1 && y <= destY && north >= destY) { return true } if (destX in x..east && y == destY - srcSize) { return true } } 3 -> { if (x == destX - srcSize && y <= destY && north >= destY) { return true } if (destX in x..east && y == destY + 1 && (flags[destX, y, z] and CollisionFlag.BLOCK_NORTH) == 0 ) return true if (x == destX + 1 && y <= destY && north >= destY && (flags[x, destY, z] and CollisionFlag.BLOCK_EAST) == 0 ) return true if (destX in x..east && y == destY - srcSize) { return true } } } } 9 -> { if (destX in x..east && y == destY + 1 && (flags[destX, y, z] and CollisionFlag.BLOCK_NORTH) == 0 ) return true if (destX in x..east && y == destY - srcSize && (flags[destX, north, z] and CollisionFlag.BLOCK_SOUTH) == 0 ) return true if (x == destX - srcSize && y <= destY && north >= destY && (flags[east, destY, z] and CollisionFlag.BLOCK_WEST) == 0 ) return true return x == destX + 1 && y <= destY && north >= destY && (flags[x, destY, z] and CollisionFlag.BLOCK_EAST) == 0 } } return false } @Suppress("NOTHING_TO_INLINE") private inline operator fun Array<IntArray?>.get( x: Int, y: Int, z: Int ): Int { val zone = this[getZoneIndex(x, y, z)] ?: return -1 return zone[getIndexInZone(x, y)] }
@file:Suppress("DuplicatedCode") package com.rs.engine.pathfinder.bound internal fun reachWallDeco( flags: Array<IntArray?>, x: Int, y: Int, z: Int, destX: Int, destY: Int, srcSize: Int, shape: Int, rot: Int ): Boolean = when { srcSize == 1 && x == destX && destY == y -> true srcSize != 1 && destX >= x && srcSize + x - 1 >= destX && destY >= y && srcSize + y - 1 >= destY -> true srcSize == 1 -> reachWallDeco1( flags, x, y, z, destX, destY, shape, rot ) else -> reachWallDecoN( flags, x, y, z, destX, destY, srcSize, shape, rot ) } private fun reachWallDeco1( flags: Array<IntArray?>, x: Int, y: Int, z: Int, destX: Int, destY: Int, shape: Int, rot: Int ): Boolean { if (shape in 6..7) { when (rot.alteredRotation(shape)) { 0 -> { if (x == destX + 1 && y == destY && (flags[x, y, z] and CollisionFlag.WALL_WEST) == 0 ) return true if (x == destX && y == destY - 1 && (flags[x, y, z] and CollisionFlag.WALL_NORTH) == 0 ) return true } 1 -> { if (x == destX - 1 && y == destY && (flags[x, y, z] and CollisionFlag.WALL_EAST) == 0 ) return true if (x == destX && y == destY - 1 && (flags[x, y, z] and CollisionFlag.WALL_NORTH) == 0 ) return true } 2 -> { if (x == destX - 1 && y == destY && (flags[x, y, z] and CollisionFlag.WALL_EAST) == 0 ) return true if (x == destX && y == destY + 1 && (flags[x, y, z] and CollisionFlag.WALL_SOUTH) == 0 ) return true } 3 -> { if (x == destX + 1 && y == destY && (flags[x, y, z] and CollisionFlag.WALL_WEST) == 0 ) return true if (x == destX && y == destY + 1 && (flags[x, y, z] and CollisionFlag.WALL_SOUTH) == 0 ) return true } } } else if (shape == 8) { if (x == destX && y == destY + 1 && (flags[x, y, z] and CollisionFlag.WALL_SOUTH) == 0 ) return true if (x == destX && y == destY - 1 && (flags[x, y, z] and CollisionFlag.WALL_NORTH) == 0 ) return true if (x == destX - 1 && y == destY && (flags[x, y, z] and CollisionFlag.WALL_EAST) == 0 ) return true return x == destX + 1 && y == destY && (flags[x, y, z] and CollisionFlag.WALL_WEST) == 0 } return false } private fun reachWallDecoN( flags: Array<IntArray?>, x: Int, y: Int, z: Int, destX: Int, destY: Int, srcSize: Int, shape: Int, rot: Int ): Boolean { val east = x + srcSize - 1 val north = y + srcSize - 1 if (shape in 6..7) { when (rot.alteredRotation(shape)) { 0 -> { if (x == destX + 1 && y <= destY && north >= destY && (flags[x, destY, z] and CollisionFlag.WALL_WEST) == 0 ) return true if (x <= destX && y == destY - srcSize && east >= destX && (flags[destX, north, z] and CollisionFlag.WALL_NORTH) == 0 ) return true } 1 -> { if (x == destX - srcSize && y <= destY && north >= destY && (flags[east, destY, z] and CollisionFlag.WALL_EAST) == 0 ) return true if (x <= destX && y == destY - srcSize && east >= destX && (flags[destX, north, z] and CollisionFlag.WALL_NORTH) == 0 ) return true } 2 -> { if (x == destX - srcSize && y <= destY && north >= destY && (flags[east, destY, z] and CollisionFlag.WALL_EAST) == 0 ) return true if (x <= destX && y == destY + 1 && east >= destX && (flags[destX, y, z] and CollisionFlag.WALL_SOUTH) == 0 ) return true } 3 -> { if (x == destX + 1 && y <= destY && north >= destY && (flags[x, destY, z] and CollisionFlag.WALL_WEST) == 0 ) return true if (x <= destX && y == destY + 1 && east >= destX && (flags[destX, y, z] and CollisionFlag.WALL_SOUTH) == 0 ) return true } } } else if (shape == 8) { if (x <= destX && y == destY + 1 && east >= destX && (flags[destX, y, z] and CollisionFlag.WALL_SOUTH) == 0 ) return true if (x <= destX && y == destY - srcSize && east >= destX && (flags[destX, north, z] and CollisionFlag.WALL_NORTH) == 0 ) return true if (x == destX - srcSize && y <= destY && north >= destY && (flags[east, destY, z] and CollisionFlag.WALL_EAST) == 0 ) return true return x == destX + 1 && y <= destY && north >= destY && (flags[x, destY, z] and CollisionFlag.WALL_WEST) == 0 } return false } private fun Int.alteredRotation(shape: Int): Int { return if (shape == 7) (this + 2) and 0x3 else this } @Suppress("NOTHING_TO_INLINE") private inline operator fun Array<IntArray?>.get( x: Int, y: Int, z: Int ): Int { val zone = this[getZoneIndex(x, y, z)] ?: return -1 return zone[getIndexInZone(x, y)] }
@file:Suppress("unused") package com.rs.engine.pathfinder.collision enum class CollisionStrategyType(val strategy: CollisionStrategy) { NORMAL(NormalBlockFlagCollision()), WATER(BlockedFlagCollision()), FLY(LineOfSightBlockFlagCollision()), INDOOR(IndoorsFlagCollision()), OUTDOOR(OutdoorsFlagCollision()) }
package com.rs.engine.pathfinder.collision public interface CollisionStrategy { public fun canMove(tileFlag: Int, blockFlag: Int): Boolean } public class NormalBlockFlagCollision : CollisionStrategy { override fun canMove(tileFlag: Int, blockFlag: Int): Boolean { return (tileFlag and blockFlag) == 0 } } public class IndoorsFlagCollision : CollisionStrategy { override fun canMove(tileFlag: Int, blockFlag: Int): Boolean { return (tileFlag and blockFlag) == 0 && (tileFlag and CollisionFlag.ROOF) != 0 } } public class OutdoorsFlagCollision : CollisionStrategy { override fun canMove(tileFlag: Int, blockFlag: Int): Boolean { return (tileFlag and (blockFlag or CollisionFlag.ROOF)) == 0 } } public class BlockedFlagCollision() : CollisionStrategy { override fun canMove(tileFlag: Int, blockFlag: Int): Boolean { val flag = blockFlag and CollisionFlag.FLOOR.inv() return (tileFlag and flag) == 0 && (tileFlag and CollisionFlag.FLOOR) != 0 } } public class LineOfSightBlockFlagCollision : CollisionStrategy { override fun canMove(tileFlag: Int, blockFlag: Int): Boolean { val movementFlags = (blockFlag and BLOCK_MOVEMENT) shl 9 val routeFlags = (blockFlag and BLOCK_ROUTE) shr 13 val finalBlockFlag = movementFlags or routeFlags return (tileFlag and finalBlockFlag) == 0 } private companion object { private const val BLOCK_MOVEMENT = CollisionFlag.WALL_NORTH_WEST or CollisionFlag.WALL_NORTH or CollisionFlag.WALL_NORTH_EAST or CollisionFlag.WALL_EAST or CollisionFlag.WALL_SOUTH_EAST or CollisionFlag.WALL_SOUTH or CollisionFlag.WALL_SOUTH_WEST or CollisionFlag.WALL_WEST or CollisionFlag.OBJECT private const val BLOCK_ROUTE = CollisionFlag.WALL_NORTH_WEST_ROUTE_BLOCKER or CollisionFlag.WALL_NORTH_ROUTE_BLOCKER or CollisionFlag.WALL_NORTH_EAST_ROUTE_BLOCKER or CollisionFlag.WALL_EAST_ROUTE_BLOCKER or CollisionFlag.WALL_SOUTH_EAST_ROUTE_BLOCKER or CollisionFlag.WALL_SOUTH_ROUTE_BLOCKER or CollisionFlag.WALL_SOUTH_WEST_ROUTE_BLOCKER or CollisionFlag.WALL_WEST_ROUTE_BLOCKER or CollisionFlag.OBJECT_ROUTE_BLOCKER } }
package com.rs.engine.pathfinder.flag /** * @author Kris | 15/01/2022 */ public object AccessBitFlag { public const val BLOCK_NORTH: Int = 0x1 public const val BLOCK_EAST: Int = 0x2 public const val BLOCK_SOUTH: Int = 0x4 public const val BLOCK_WEST: Int = 0x8 }
@file:Suppress("MemberVisibilityCanBePrivate", "unused") package com.rs.engine.pathfinder.flag public object CollisionFlag { public const val WALL_NORTH_WEST: Int = 0x1 public const val WALL_NORTH: Int = 0x2 public const val WALL_NORTH_EAST: Int = 0x4 public const val WALL_EAST: Int = 0x8 public const val WALL_SOUTH_EAST: Int = 0x10 public const val WALL_SOUTH: Int = 0x20 public const val WALL_SOUTH_WEST: Int = 0x40 public const val WALL_WEST: Int = 0x80 public const val OBJECT: Int = 0x100 public const val WALL_NORTH_WEST_PROJECTILE_BLOCKER: Int = 0x200 public const val WALL_NORTH_PROJECTILE_BLOCKER: Int = 0x400 public const val WALL_NORTH_EAST_PROJECTILE_BLOCKER: Int = 0x800 public const val WALL_EAST_PROJECTILE_BLOCKER: Int = 0x1000 public const val WALL_SOUTH_EAST_PROJECTILE_BLOCKER: Int = 0x2000 public const val WALL_SOUTH_PROJECTILE_BLOCKER: Int = 0x4000 public const val WALL_SOUTH_WEST_PROJECTILE_BLOCKER: Int = 0x8000 public const val WALL_WEST_PROJECTILE_BLOCKER: Int = 0x10000 public const val OBJECT_PROJECTILE_BLOCKER: Int = 0x20000 public const val FLOOR_DECORATION: Int = 0x40000 /** * Custom flag dedicated to blocking NPCs. */ public const val BLOCK_NPCS: Int = 0x80000 /** * Custom flag dedicated to blocking players, projectiles as well as NPCs. * An example of a monster to set this flag is Brawler. Note that it is unclear if this flag * prevents NPCs, as there is a separate flag option for it. * This flag is similar to the one above, except it's strictly for NPCs. */ public const val BLOCK_PLAYERS: Int = 0x100000 public const val FLOOR: Int = 0x200000 public const val WALL_NORTH_WEST_ROUTE_BLOCKER: Int = 0x400000 public const val WALL_NORTH_ROUTE_BLOCKER: Int = 0x800000 public const val WALL_NORTH_EAST_ROUTE_BLOCKER: Int = 0x1000000 public const val WALL_EAST_ROUTE_BLOCKER: Int = 0x2000000 public const val WALL_SOUTH_EAST_ROUTE_BLOCKER: Int = 0x4000000 public const val WALL_SOUTH_ROUTE_BLOCKER: Int = 0x8000000 public const val WALL_SOUTH_WEST_ROUTE_BLOCKER: Int = 0x10000000 public const val WALL_WEST_ROUTE_BLOCKER: Int = 0x20000000 public const val OBJECT_ROUTE_BLOCKER: Int = 0x40000000 /** * Roof flag, used to bind NPCs to not leave the buildings they spawn in. This is a custom flag. */ public const val ROOF: Int = 0x80000000.toInt() /* A shorthand combination of both the floor flags. */ private const val FLOOR_BLOCKED = FLOOR or FLOOR_DECORATION /* Mixed masks of the above flags */ public const val BLOCK_WEST: Int = WALL_EAST or OBJECT or FLOOR_BLOCKED public const val BLOCK_EAST: Int = WALL_WEST or OBJECT or FLOOR_BLOCKED public const val BLOCK_SOUTH: Int = WALL_NORTH or OBJECT or FLOOR_BLOCKED public const val BLOCK_NORTH: Int = WALL_SOUTH or OBJECT or FLOOR_BLOCKED public const val BLOCK_SOUTH_WEST: Int = WALL_NORTH or WALL_NORTH_EAST or WALL_EAST or OBJECT or FLOOR_BLOCKED public const val BLOCK_SOUTH_EAST: Int = WALL_NORTH_WEST or WALL_NORTH or WALL_WEST or OBJECT or FLOOR_BLOCKED public const val BLOCK_NORTH_WEST: Int = WALL_EAST or WALL_SOUTH_EAST or WALL_SOUTH or OBJECT or FLOOR_BLOCKED public const val BLOCK_NORTH_EAST: Int = WALL_SOUTH or WALL_SOUTH_WEST or WALL_WEST or OBJECT or FLOOR_BLOCKED public const val BLOCK_NORTH_AND_SOUTH_EAST: Int = WALL_NORTH or WALL_NORTH_EAST or WALL_EAST or WALL_SOUTH_EAST or WALL_SOUTH or OBJECT or FLOOR_BLOCKED public const val BLOCK_NORTH_AND_SOUTH_WEST: Int = WALL_NORTH_WEST or WALL_NORTH or WALL_SOUTH or WALL_SOUTH_WEST or WALL_WEST or OBJECT or FLOOR_BLOCKED public const val BLOCK_NORTH_EAST_AND_WEST: Int = WALL_NORTH_WEST or WALL_NORTH or WALL_NORTH_EAST or WALL_EAST or WALL_WEST or OBJECT or FLOOR_BLOCKED public const val BLOCK_SOUTH_EAST_AND_WEST: Int = WALL_EAST or WALL_SOUTH_EAST or WALL_SOUTH or WALL_SOUTH_WEST or WALL_WEST or OBJECT or FLOOR_BLOCKED /* Route blocker flags. These are used in ~550+ clients to generate paths through bankers and such. */ public const val BLOCK_WEST_ROUTE_BLOCKER: Int = WALL_EAST_ROUTE_BLOCKER or OBJECT_ROUTE_BLOCKER or FLOOR_BLOCKED public const val BLOCK_EAST_ROUTE_BLOCKER: Int = WALL_WEST_ROUTE_BLOCKER or OBJECT_ROUTE_BLOCKER or FLOOR_BLOCKED public const val BLOCK_SOUTH_ROUTE_BLOCKER: Int = WALL_NORTH_ROUTE_BLOCKER or OBJECT_ROUTE_BLOCKER or FLOOR_BLOCKED public const val BLOCK_NORTH_ROUTE_BLOCKER: Int = WALL_SOUTH_ROUTE_BLOCKER or OBJECT_ROUTE_BLOCKER or FLOOR_BLOCKED public const val BLOCK_SOUTH_WEST_ROUTE_BLOCKER: Int = WALL_NORTH_ROUTE_BLOCKER or WALL_NORTH_EAST_ROUTE_BLOCKER or WALL_EAST_ROUTE_BLOCKER or OBJECT_ROUTE_BLOCKER or FLOOR_BLOCKED public const val BLOCK_SOUTH_EAST_ROUTE_BLOCKER: Int = WALL_NORTH_WEST_ROUTE_BLOCKER or WALL_NORTH_ROUTE_BLOCKER or WALL_WEST_ROUTE_BLOCKER or OBJECT_ROUTE_BLOCKER or FLOOR_BLOCKED public const val BLOCK_NORTH_WEST_ROUTE_BLOCKER: Int = WALL_EAST_ROUTE_BLOCKER or WALL_SOUTH_EAST_ROUTE_BLOCKER or WALL_SOUTH_ROUTE_BLOCKER or OBJECT_ROUTE_BLOCKER or FLOOR_BLOCKED public const val BLOCK_NORTH_EAST_ROUTE_BLOCKER: Int = WALL_SOUTH_ROUTE_BLOCKER or WALL_SOUTH_WEST_ROUTE_BLOCKER or WALL_WEST_ROUTE_BLOCKER or OBJECT_ROUTE_BLOCKER or FLOOR_BLOCKED public const val BLOCK_NORTH_AND_SOUTH_EAST_ROUTE_BLOCKER: Int = WALL_NORTH_ROUTE_BLOCKER or WALL_NORTH_EAST_ROUTE_BLOCKER or WALL_EAST_ROUTE_BLOCKER or WALL_SOUTH_EAST_ROUTE_BLOCKER or WALL_SOUTH_ROUTE_BLOCKER or OBJECT_ROUTE_BLOCKER or FLOOR_BLOCKED public const val BLOCK_NORTH_AND_SOUTH_WEST_ROUTE_BLOCKER: Int = WALL_NORTH_WEST_ROUTE_BLOCKER or WALL_NORTH_ROUTE_BLOCKER or WALL_SOUTH_ROUTE_BLOCKER or WALL_SOUTH_WEST_ROUTE_BLOCKER or WALL_WEST_ROUTE_BLOCKER or OBJECT_ROUTE_BLOCKER or FLOOR_BLOCKED public const val BLOCK_NORTH_EAST_AND_WEST_ROUTE_BLOCKER: Int = WALL_NORTH_WEST_ROUTE_BLOCKER or WALL_NORTH_ROUTE_BLOCKER or WALL_NORTH_EAST_ROUTE_BLOCKER or WALL_EAST_ROUTE_BLOCKER or WALL_WEST_ROUTE_BLOCKER or OBJECT_ROUTE_BLOCKER or FLOOR_BLOCKED public const val BLOCK_SOUTH_EAST_AND_WEST_ROUTE_BLOCKER: Int = WALL_EAST_ROUTE_BLOCKER or WALL_SOUTH_EAST_ROUTE_BLOCKER or WALL_SOUTH_ROUTE_BLOCKER or WALL_SOUTH_WEST_ROUTE_BLOCKER or WALL_WEST_ROUTE_BLOCKER or OBJECT_ROUTE_BLOCKER or FLOOR_BLOCKED }
package com.rs.engine.pathfinder.flag public object DirectionFlag { public const val NORTH: Int = 0x1 public const val EAST: Int = 0x2 public const val SOUTH: Int = 0x4 public const val WEST: Int = 0x8 public const val SOUTH_WEST: Int = WEST or SOUTH public const val NORTH_WEST: Int = WEST or NORTH public const val SOUTH_EAST: Int = EAST or SOUTH public const val NORTH_EAST: Int = EAST or NORTH }
package com.rs.engine.pathfinder.reach private const val WALL_STRATEGY = 0 private const val WALL_DECO_STRATEGY = 1 private const val RECTANGLE_STRATEGY = 2 private const val NO_STRATEGY = 3 private const val RECTANGLE_EXCLUSIVE_STRATEGY = 4 public object DefaultReachStrategy : ReachStrategy { override fun reached( flags: Array<IntArray?>, x: Int, y: Int, z: Int, destX: Int, destY: Int, destWidth: Int, destHeight: Int, srcSize: Int, rotation: Int, shape: Int, accessBitMask: Int, ): Boolean { val exitStrategy = shape.exitStrategy if (exitStrategy != RECTANGLE_EXCLUSIVE_STRATEGY && x == destX && y == destY) { return true } return when (exitStrategy) { WALL_STRATEGY -> reachWall( flags, x, y, z, destX, destY, srcSize, shape, rotation ) WALL_DECO_STRATEGY -> reachWallDeco( flags, x, y, z, destX, destY, srcSize, shape, rotation ) RECTANGLE_STRATEGY -> reachRectangle( flags, x, y, z, accessBitMask, destX, destY, srcSize, destWidth, destHeight ) RECTANGLE_EXCLUSIVE_STRATEGY -> reachExclusiveRectangle( flags, x, y, z, accessBitMask, destX, destY, srcSize, destWidth, destHeight ) else -> false } } private val Int.exitStrategy: Int get() = when { this == -2 -> RECTANGLE_EXCLUSIVE_STRATEGY this == -1 -> NO_STRATEGY this in 0..3 || this == 9 -> WALL_STRATEGY this < 9 -> WALL_DECO_STRATEGY this in 10..11 || this == 22 -> RECTANGLE_STRATEGY else -> NO_STRATEGY } }