diff --git a/docfx/docfx.json b/docfx/docfx.json index 516bf3be..a463c9f2 100644 --- a/docfx/docfx.json +++ b/docfx/docfx.json @@ -26,7 +26,7 @@ "resource": [ { "files": [ - "images/**" + "img/**" ] } ], @@ -36,8 +36,9 @@ "modern" ], "globalMetadata": { - "_appName": "multiclient", - "_appTitle": "multiclient", + "_appName": "Archipelago.MultiClient.Net", + "_appTitle": "Archipelago.MultiClient.Net", + "_appLogoPath": "img/logo/color-icon.svg", "_enableSearch": true, "pdf": false } diff --git a/docfx/docs/helpers/datastore.md b/docfx/docs/helpers/datastore.md new file mode 100644 index 00000000..2700aa1a --- /dev/null +++ b/docfx/docs/helpers/datastore.md @@ -0,0 +1,109 @@ +# DataStorage + +DataStorage support is included in the library. You may save values on the archipelago server in order to share them +across other player's sessions or to simply keep track of values outside your game's state. + +The DataStorage provides an interface based on keys and their scope. By assigning a value to a key, that value is stored +on the server and by reading from a key a value is retrieved from the server. +Assigning and reading values from the store can be done using simple assignments `=`: + +* `= session.DataStorage["Key"]`, read value from the data storage synchronously +* `session.DataStorage["Key"] =`, write value to the data storage asynchronously +* Complex objects need to be stored and retrieved in the form of a `JObject`, therefore you must wrap them into a + `JObject.FromObject()` + +The DataStorage also provides methods to retrieve the value of a key asynchronously using `[key].GetAsync`. +To set the initial value of a key without overriding any existing value, the `[key].Initialize` method can be used. +If you're interested in keeping track of when a value of a certain key is changed by any client you can use the +`[key].OnValueChanged` handler to register a callback for when the value gets updated. + +Mathematical operations on values stored on the server are supported using the following operators: + +* `+`, Add right value to left value +* `-`, Subtract right value from left value +* `*`, Multiply left value by right value +* `/`, Divide left value by right value +* `%`, Gets remainder after dividing left value by right value +* `^`, Multiply left value by the power of the right value + +Bitwise operations on values stored on the server are supported using the following operations: + +* `+ Bitwise.Xor(x)`, apply logical exclusive OR to the left value using value x +* `+ Bitwise.Or(x)`, apply logical OR to the left value using value x +* `+ Bitwise.And(x)`, apply logical AND to the left value using value x +* `+ Bitwise.LeftShift(x)`, binary shift the left value to the left by x +* `+ Bitwise.RightShift(x)`, binary shift the left value to the right by x + +Other operations on values stored on the server are supported using the following operations: + +* `+ Operation.Min(x)`, get the lowest value of the left value and x +* `+ Operation.Max(x)`, get the highest value of the left value and x +* `+ Operation.Remove(x)`, when the left value is a list, removes the first element with value x +* `+ Operation.Pop(x)`, when the left value is a list or dictionary, removes the element at index x or key x +* `+ Operation.Update(x)`, when the left value is a list or dictionary, updates the dictionary with the keys/values in x + +Operation specific callbacks are supported, these get called only once with the results of the current operation: + +* `+ Callback.Add((oldValue, newValue) => {});`, calls this method after your operation or chain of operations are + processed by the server + +Mathematical operations, bitwise operations and callbacks can be chained, given the extended syntax with `()` around +each operation. + +Examples: + +```csharp +var session = ArchipelagoSessionFactory.CreateSession("localhost", 38281); +session.TryConnectAndLogin("Timespinner", "Jarno", ItemsHandlingFlags.AllItems); + +//Initializing +session.DataStorage["B"].Initialize(20); //Set initial value for B in global scope if it has no value assigned yet + +//Storing/Updating +session.DataStorage[Scope.Slot, "SetPersonal"] = 20; //Set `SetPersonal` to 20, in scope of the current connected user\slot +session.DataStorage[Scope.Global, "SetGlobal"] = 30; //Set `SetGlobal` to 30, in global scope shared among all players (the default scope is global) +session.DataStorage["Add"] += 50; //Add 50 to the current value of `Add` +session.DataStorage["Divide"] /= 2; //Divide current value of `Divide` in half +session.DataStorage["Max"] += + Operation.Max(80); //Set `Max` to 80 if the stored value is lower than 80 +session.DataStorage["Dictionary"] = JObject.FromObject(new Dictionary()); //Set `Dictionary` to a Dictionary +session.DataStorage["SetObject"] = JObject.FromObject(new SomeClassOrStruct()); //Set `SetObject` to a custom object +session.DataStorage["BitShiftLeft"] += Bitwise.LeftShift(1); //Bitshift current value of `BitShiftLeft` to left by 1 +session.DataStorage["Xor"] += Bitwise.Xor(0xFF); //Modify `Xor` using the Bitwise exclusive or operation +session.DataStorage["DifferentKey"] = session.DataStorage["A"] - 30; //Get value of `A`, Assign it to `DifferentKey` and then subtract 30 +session.DataStorage["Array"] = new []{ "One", "Two" }; //Arrays can be stored directly, List's needs to be converted ToArray() first +session.DataStorage["Array"] += new []{ "Three" }; //Append array values to existing array on the server + +//Chaining operations +session.DataStorage["Min"] = (session.DataStorage["Min"] + 40) + Operation.Min(100); //Add 40 to `Min`, then Set `Min` to 100 if `Min` is bigger than 100 +session.DataStorage["C"] = ((session.DataStorage["C"] - 6) + Bitwise.RightShift(1)) ^ 3; //Subtract 6 from `C`, then multiply `C` by 2 using bitshifting, then take `C` to the power of 3 + +//Update callbacks +//EnergyLink deplete pattern, subtract 50, then set value to 0 if its lower than 0 +session.DataStorage["EnergyLink"] = ((session.DataStorage["EnergyLink"] - 50) + Operation.Min(0)) + Callback.Add((oldData, newData) => { + var actualDepleted = (float)newData - (float)oldData; //calculate the actual change, might differ if there was less than 50 left on the server +}); + +//Keeping track of changes +session.DataStorage["OnChangeHandler"].OnValueChanged += (oldData, newData) => { + var changed = (int)newData - (int)oldData; //Keep track of changes made to `OnChangeHandler` by any client, and calculate the difference +}; + +//Keeping track of change (but for more complex data structures) +session.DataStorage["OnChangeHandler"].OnValueChanged += (oldData, newData) => { + var old_dict = oldData.ToObject>(); + var new_dict = newData.ToObject>(); +}; + +//Retrieving +session.DataStorage["Async"].GetAsync(s => { string r = s }); //Retrieve value of `Async` asynchronously +float f = session.DataStorage["Float"]; //Retrieve value for `Float` synchronously and store it as a float +var d = session.DataStorage["DateTime"].To() //Retrieve value for `DateTime` as a DateTime struct +var array = session.DataStorage["Strings"].To() //Retrieve value for `Strings` as string Array + +//Handling anonymous object, if the target type is not known you can use `To()` and use its interface to access the members +session.DataStorage["Anonymous"] = JObject.FromObject(new { Number = 10, Text = "Hello" }); //Set `Anonymous` to an anonymous object +var obj = session.DataStorage["Anonymous"].To(); //Retrieve value for `Anonymous` where an anonymous object was stored +var number = (int)obj["Number"]; //Get value for anonymous object key `Number` +var text = (string)obj["Text"]; //Get value for anonymous object key `Text` + +``` diff --git a/docfx/docs/helpers/events.md b/docfx/docs/helpers/events.md new file mode 100644 index 00000000..134e3471 --- /dev/null +++ b/docfx/docs/helpers/events.md @@ -0,0 +1,108 @@ +# Event Hooks + +## ArchipelagoSocket + +@"Archipelago.MultiClient.Net.Helpers.ArchipelagoSocketHelper?text=ArchipelagoSocketHelper", accessible through +`Session.Socket` + +| Event | Call Event | +|-------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------| +| @"Archipelago.MultiClient.Net.Helpers.ArchipelagoSocketHelperDelagates.ErrorReceivedHandler?text=ErrorReceived" | Called when there is an error in the socket connection or while parsing a packet. | +| @"Archipelago.MultiClient.Net.Helpers.ArchipelagoSocketHelperDelagates.PacketReceivedHandler?text=PacketReceived" | Called when a packet has been received from the server and identified. | +| @"Archipelago.MultiClient.Net.Helpers.ArchipelagoSocketHelperDelagates.PacketsSentHandler?text=PacketsSent" | Called just before submitting a packet to the server. | +| @"Archipelago.MultiClient.Net.Helpers.ArchipelagoSocketHelperDelagates.SocketClosedHandler?text=SocketClosed" | Called when the underlying socket connection has been closed. | +| @"Archipelago.MultiClient.Net.Helpers.ArchipelagoSocketHelperDelagates.SocketOpenedHandler?text=SocketOpened" | Called when the underlying socket connection is opened to the server. | + +## ReceivedItemsHelper + +@"Archipelago.MultiClient.Net.Helpers.IReceivedItemsHelper?text=ReceivedItemsHelper", accessible through `Session.Items`. + +| Event | Call Event | +|--------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------| +| @"Archipelago.MultiClient.Net.Helpers.ReceivedItemsHelper.ItemReceivedHandler?text=ItemReceived" | When an item is received. If multiple items are received in a single packet, the event is fired for each individual item. | + +## LocationCheckHelper + +@"Archipelago.MultiClient.Net.Helpers.LocationCheckHelper?text=LocationCheckHelper", accessible through +`Session.Locations`. + +| Event | Call Event | +|------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------| +| @"Archipelago.MultiClient.Net.Helpers.LocationCheckHelper.CheckedLocationsUpdatedHandler?text=CheckedLocationsUpdated" | Called when new locations are checked, such as another player using !collect | + +## MessageLogHelper + +@"Archipelago.MultiClient.Net.Helpers.MessageLogHelper?text=MessageLogHelper", accessible through `Session.MessageLog` + +| Event | Call Event | +|-------------------------------------------------------------------------------------------------------|------------------------------------------------------------------| +| @"Archipelago.MultiClient.Net.Helpers.MessageLogHelper.MessageReceivedHandler?text=OnMessageReceived" | Called for each message that should be displayed for the player. | + +### Message Logging + +The Archipelago server can send messages to client to be displayed on screen as a sort of log, this is done by handling +the `PrintJsonPacket` packets. This library simplifies this process into a +@"Archipelago.MultiClient.Net.Helpers.IMessageLogHelper?text='single handler'". + +```csharp +var session = ArchipelagoSessionFactory.CreateSession("localhost", 38281); +session.MessageLog.OnMessageReceived += OnMessageReceived; +session.TryConnectAndLogin("Timespinner", "Jarno", ItemsHandlingFlags.AllItems, new Version(0,3,5)); + +static void OnMessageReceived(LogMessage message) +{ + DisplayOnScreen(message.ToString()); +} +``` + +In some cased you might want extra information that is provided by the server in such cases you can use type checking + +```csharp +static void OnMessageReceived(LogMessage message) +{ + switch (message) + { + case ItemHintLogMessage hintLogMessage: + var receiver = itemSendLogMessage.Receiver; + var sender = itemSendLogMessage.Sender; + var networkItem = itemSendLogMessage.Item; + var found = hintLogMessage.IsFound; + break; + case ItemSendLogMessage itemSendLogMessage: + var receiver = itemSendLogMessage.Receiver; + var sender = itemSendLogMessage.Sender; + var networkItem = itemSendLogMessage.Item; + break; + } + + DisplayOnScreen(message.ToString()); +} +``` + +If you want more control over how the message is displayed, like for example you might want to color certain parts of +the message, then you can use the `Parts` property. This returns each part of the message in order of appearance with +the `Text` to be displayed and also the `Color` it would normally be displayed in. If `IsBackgroundColor` is true, then +the color should be applied to the message background instead. The MessagePart message can also contain additional +information that can be retrieved by type checking. + +```csharp +foreach (part in message.Parts) +{ + switch (part) + { + case ItemMessagePart itemMessagePart: + var itemId = itemMessagePart.ItemId; + var flags = itemMessagePart.Flags; + break; + case LocationMessagePart locationMessagePart: + var locationId = locationMessagePart.LocationId; + break; + case PlayerMessagePart playerMessagePart: + var slotId = playerMessagePart.SlotId; + var isCurrentPlayer = playerMessagePart.IsActivePlayer; + break; + } + + DisplayOnScreen(part.Text, part.Color, part.IsBackgroundColor); +} +``` diff --git a/docfx/docs/helpers/helpers.md b/docfx/docs/helpers/helpers.md new file mode 100644 index 00000000..dcefb209 --- /dev/null +++ b/docfx/docs/helpers/helpers.md @@ -0,0 +1,128 @@ +# Helper Overview + +```csharp +session.Socket // Payload-agnostic interface for sending/receving the most basic transmission units between client/server +session.Items // Helpers for handling receipt of items +session.Locations // Helpers for reporting visited locations to the server +session.Players // Helpers for translating player information such as number, alias, name etc. +session.DataStorage // Helpers for reading/writing data globally accessible to any client connected in the room +session.ConnectionInfo // Helpers for reading/handling useful information on the current connection +session.RoomState // Information on the state of the room +session.MessageLog // Interface for the server to push info messages to the user +``` + +## Players + +The @"Archipelago.MultiClient.Net.Helpers.IPlayerHelper?text=Player Helper" provides methods for accessing details +about the other players currently connected to the Archipelago +session. + +## Locations + +The @"Archipelago.MultiClient.Net.Helpers.ILocationCheckHelper?text=Locations Helper" provides methods for accessing +information regarding the current player's locations, as well as updating the server on the status of their locations. + +### Report Collected Location(s) + +Call the following method to inform the server of locations whose items have been "found", and therefore should be +distributed if necessary: + +```csharp +// Report multiple at once +session.Locations.CompleteLocationChecks(new []{1,3,8}); + +// Or report one at a time +session.Locations.CompleteLocationChecks(3); +``` + +The location ID used is of that defined in the AP world. + +### Scout Location Checks + +Scouting means asking the server what is stored in a specific location *without* collecting it. This can also be +utilized in order to create a hint, if - for instance - the current player knows what is on the location to inform other +players of this knowledge. + +```csharp +session.Locations.ScoutLocationsAsync(locationInfoPacket => Console.WriteLine(locationInfoPacket.Locations.Count), HintCreationPolicy.CreateAndAnnounceOnce, new []{4, 5}); +``` + +## Items + +The @"Archipelago.MultiClient.Net.Helpers.IReceivedItemsHelper?text=Received Items Helper" provides methods for +checking the player's current inventory, and receiving items from the server. + +### Received Item Callback Handler (Asynchronous) + +```csharp +// Must go BEFORE a successful connection attempt +session.Items.ItemReceived += (receivedItemsHelper) => { + var itemReceivedName = receivedItemsHelper.PeekItemName() ?? $"Item: {itemId}"; + + // ... Handle item receipt here + + receivedItemsHelper.DequeueItem(); +}; +``` + +*Note: This callback event will occur for every item on connection and reconnection.* + +## RoomState + +The @"Archipelago.MultiClient.Net.Helpers.IRoomStateHelper?text=RoomState Helper" provides access to values that +represent the current state of the multiworld room, with information such as the cost of a hint and or your current +accumulated amount of hint point or the permissions for things like forfeiting. + +```csharp +Console.WriteLine($"You have {session.RoomState.HintPoints}, and need {session.RoomState.HintCost} for a hint"); +``` + +## ConnectionInfo + +The @"Archipelago.MultiClient.Net.Helpers.IConnectionInfoProvider?text=ConnectionInfo Helper" provides access to +values under which you are currently connected, such as your slot number or your currently used tags and item handling +flags. + +```csharp +Console.WriteLine($"You are connected on slot {session.ConnectionInfo.Slot}, on team {session.ConnectionInfo.Team}"); +``` + +## ArchipelagoSocket + +The @"Archipelago.MultiClient.Net.Helpers.IConnectionInfoProvider?text=Socket Helper" is a lower level API allowing +for direct access to the socket which the session object uses to communicate with the Archipelago server. You may use +this object to hook onto when messages are received, or you may use it to send any packets defined in the library. +Various events are exposed to allow for receipt of errors or notifying of socket close. + +```csharp +session.Socket.SendPacket(new SayPacket(){Text = "Woof woof!"}); +``` + +## MessageLog + +The Archipelago server can send messages to client to be displayed on screen as a sort of log, this is done by handling +the `PrintJsonPacket` packets. This library simplifies this process into a +@"Archipelago.MultiClient.Net.Helpers.IMessageLogHelper?text=single handler" that can be subscribed to with an +[event hook](events.md). + +## DeathLink + +DeathLink support is included in the library. You may enable it by creating a new +@"Archipelago.MultiClient.Net.BounceFeatures.DeathLink.DeathLinkService?text=DeathLinkService" from the +@"Archipelago.MultiClient.Net.BounceFeatures.DeathLink.DeathLinkProvider?text=DeathLinkProvider", and subscribing to the +`OnDeathLinkReceived` event. Deathlink can then be toggled on and off using the `EnableDeathlink` and `DisableDeathlink` +methods on the service. + +```csharp +var session = ArchipelagoSessionFactory.CreateSession("localhost", 38281); + +var deathLinkService = session.CreateDeathLinkService(); + +deathLinkService.OnDeathLinkReceived += (deathLinkObject) => { + // ... Kill your player(s). +}; + +deathLinkService.EnableDeathlink(); +// ... On death: +deathLinkService.SendDeathLink(new DeathLink("Ijwu", "Died to exposure.")); +``` diff --git a/docfx/docs/packets.md b/docfx/docs/packets.md new file mode 100644 index 00000000..06373840 --- /dev/null +++ b/docfx/docs/packets.md @@ -0,0 +1,150 @@ +# Packets + +@"Archipelago.MultiClient.Net.Packets?text=Packets" are the payload used for communicating with the Archipelago server. +For more fine-tuned handling, the library splits them up even more for digesting into the various helpers. This +document will only cover a few of the main ones and some methods for interacting with them. + +### Manual Packet Handling + +If you have a use case for a packet that isn't exposed, or can be handled through one of the available helpers, you can +manually subscribe to the socket's +@"Archipelago.MultiClient.Net.Helpers.ArchipelagoSocketHelperDelagates.PacketReceivedHandler?text=PacketReceivedHandler" +and process the packet from there. + +```csharp +public static void RegisterBounceHandler() +{ + Session.Socket.PacketReceived += OnPacketReceived; +} + +public static void OnPacketReceived(ArchipelagoPacketBase packet) +{ + switch (packet) + { + case ItemCheatPrintJsonPacket: + Console.WriteLine("You're a dirty cheater."); + break; + } +} +``` + +## ReceivedItemsPacket + +A @"Archipelago.MultiClient.Net.Packets.ReceivedItemsPacket?text=ReceivedItemsPacket" is received whenever the player +receives one or more items from the server. The @"Archipelago.MultiClient.Net.Helpers.IReceivedItemsHelper?text=Items Helper" +will digest the packet for you and should be used for any item processing. + +```csharp +public static void RegisterItemsHandler() +{ + // subscribe to the ItemReceived event + Session.Items.ItemReceived += HandleItem; +} + +public static void HandleItem(ReceivedItemsHelper itemHandler) +{ + // The event is fired for every received item. Keep a local index to compare against in the case of continuing + // an existing session after an earlier disconnection. + var itemToHandle = itemHandler.DequeueItem(); + // Since we dequeued the current item already, the index on the handler is the index of the *next* upcoming item, + // not the currently processing one. + if (itemHandler.Index <= MyIndex) + { + return; + } + MyIndex++; + // Do whatever other item handling +} +``` + +## LocationChecksPacket + +@"Archipelago.MultiClient.Net.Packets.LocationChecksPacket?text=This Packet" is used for notifying the server of what +locations have been completed by the player. This can be achieved by using one of the +@"Archipelago.MultiClient.Net.Helpers.ILocationCheckHelper?text=Location Check Helper's" methods; +`CompleteLocationChecks` or `CompleteLocationChecksAsync`. + +## LocationScoutsPacket + +A @"Archipelago.MultiClient.Net.Packets.LocationScoutsPacket?text=LocationScoutsPacket" is sent to the server in order +to request locations get scouted. This can also be used to create hints for these locations. After this packet is sent, +the server will reply with a @"Archipelago.MultiClient.Net.Packets.LocationInfoPacket?text=LocationInfoPacket", which +is digested and returned to the callback as a dictionary of the location id to its +@"Archipelago.MultiClient.Net.Models.ScoutedItemInfo?text=ScoutedItemInfo". + +```csharp +public static void ScoutLocations() +{ + // Send a LocationScoutsPacket to the server for locations 1, 2, and 3, register `HandleScoutInfo` as the + // callback for the reply packet, and do not create any hints + Session.Locations.ScoutLocationsAsync(HandleScouteInfo, new []{1, 2, 3}); +} + +public static void HandleScoutInfo(Dictionary scoutedLocationInfo) +{ + // handle the Info however necessary +} +``` + +## StatusUpdatePacket + +The @"Archipelago.MultiClient.Net.Packets.StatusUpdatePacket?text=StatusUpdatePacket" is used to inform the server that +the player has changed their @"Archipelago.MultiClient.Net.Enums.ArchipelagoClientState?text=client status". The most +common usage of this is to tell the server the player is in game and has started playing, or that the player has +completed their goal. This packet type has helpers directly on the ArchipelagoSession with `SetClientState` and +`SetGoalAchieved`. + +```csharp +public static void UpdateStatus(ArchipelagoClientState state) +{ + Session.SetClientState(state); +} +``` + +or + +```csharp +public static void OnGoalCompleted() +{ + Session.SetGoalAchieved(); +} +``` + +## SayPacket + +A @"Archipelago.MultiClient.Net.Packets.SayPacket?text=SayPacket" is used to communicate with other players. This is also the packet to use if you are trying to send a client command to the server such as `!release`. + +```csharp +public static void SendReleaseCommand() +{ + Session.Say("!release"); +} +``` + +or we can do it manually: +```csharp +public static void SendReleaseCommand() +{ + SendSayPacket("!release"); +} +public static void SendSayPacket(string text) +{ + Session.Socket.SendPacket(new SayPacket { Text = text }); +} +``` + +## BouncePacket + +A @"Archipelago.MultiClient.Net.Packets.BouncePacket?text=BouncePacket" is a special type of packet that can be sent +and received to specific slots, games, or client tags. DeathLink is the most common usage of this and has its own +helper, but for any other use they will need to be handled manually. + +```csharp +public static void ProcessBouncePacket(BouncePacket bouncePacket) +{ + foreach (var key in bouncePacket.Data.keys()) + { + Console.WriteLine(key); + } +} +``` diff --git a/docfx/docs/quick-start.md b/docfx/docs/quick-start.md new file mode 100644 index 00000000..9c0da83f --- /dev/null +++ b/docfx/docs/quick-start.md @@ -0,0 +1,98 @@ +# Quick Start + +## Create Session Instance + +```csharp +var session = ArchipelagoSessionFactory.CreateSession("localhost", 38281); + +// alternatively... +var session = ArchipelagoSessionFactory.CreateSession(new Uri("ws://localhost:38281")); +var session = ArchipelagoSessionFactory.CreateSession("localhost:38281"); +var session = ArchipelagoSessionFactory.CreateSession("localhost"); +``` + +The freshly created `ArchipelagoSession` object is the entrypoint for all incoming and outgoing interactions with the +server. Keep it in scope for at least the lifetime of the connection. If the room changes ports, or the user needs to +connect to a different room, then a new session needs to be created at the new host and port. + +## Connect to Room + +Connect to a server at a specific room slot using the following method: + +```csharp +LoginResult TryConnectAndLogin( + string game, // Name of the game implemented by this client, SHOULD match what is used in the world implementation + string name, // Name of the slot to connect as (a.k.a player name) + ItemsHandlingFlags itemsHandlingFlags, /* One of the following (see AP docs for details): + NoItems + RemoteItems + IncludeOwnItems + IncludeStartingInventory + AllItems + */ + Version version = null, // Minimum Archipelago API specification version which this client can successfuly interface with + string[] tags = null, /* One of the following (see AP docs for details) + "DeathLink" + "Tracker" + "TextOnly" + */ + string uuid = null, // Unique identifier for this player/client, if null randomly generated + string password = null, // Password that was set when the room was created + bool requestSlotData = true // If the LoginResult should contain the slot data + ); +``` + +For example, + +```csharp +LoginResult result = session.TryConnectAndLogin("Risk of Rain 2", "Ijwu", ItemsHandlingFlags.AllItems); +``` + +would attempt to connect to a password-less room with the slot name `Ijwu`, report the game as `Risk of Rain 2`, and +tell the server that we need to be sent ReceivedItems Packets for all item sources. + +Once connected, you have access to a suite of helper objects which provide an interface for sending/receiving +information with the server. + +### Example Connection + +```csharp +private static void Connect(string server, string user, string pass) +{ + LoginResult result; + + try + { + // handle TryConnectAndLogin attempt here and save the returned object to `result` + result = session.TryConnectAndLogin("Risk of Rain 2", "Ijwu", ItemsHandlingFlags.AllItems); + } + catch (Exception e) + { + result = new LoginFailure(e.GetBaseException().Message); + } + + if (!result.Successful) + { + LoginFailure failure = (LoginFailure)result; + string errorMessage = $"Failed to Connect to {server} as {user}:"; + foreach (string error in failure.Errors) + { + errorMessage += $"\n {error}"; + } + foreach (ConnectionRefusedError error in failure.ErrorCodes) + { + errorMessage += $"\n {error}"; + } + + return; // Did not connect, show the user the contents of `errorMessage` + } + + // Successfully connected, `ArchipelagoSession` (assume statically defined as `session` from now on) can now be + // used to interact with the server and the returned `LoginSuccessful` contains some useful information about the + // initial connection (e.g. a copy of the slot data as `loginSuccess.SlotData`) + var loginSuccess = (LoginSuccessful)result; +} +``` + +If using .net 4.0 or higher, you can use `ConnectAsync` and `LoginAsync` to prevent hitching for injection-based +implementations like harmony. diff --git a/docfx/docs/toc.yml b/docfx/docs/toc.yml index e93466df..b61cf7f9 100644 --- a/docfx/docs/toc.yml +++ b/docfx/docs/toc.yml @@ -1,2 +1,11 @@ -- name: Get Started -- href: ../index.md \ No newline at end of file +items: + - name: Get Started + items: + - href: ../index.md + - href: quick-start.md + - name: Helpers + items: + - href: helpers/helpers.md + - href: helpers/events.md + - href: helpers/datastore.md + - href: packets.md diff --git a/docfx/img/logo/LICENSE.txt b/docfx/img/logo/LICENSE.txt new file mode 100644 index 00000000..24bc1fb9 --- /dev/null +++ b/docfx/img/logo/LICENSE.txt @@ -0,0 +1 @@ +This work © 2022 by Krista Corkos and Christopher Wilson is licensed under Attribution-NonCommercial 4.0 International. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/4.0/ \ No newline at end of file diff --git a/docfx/img/logo/color-icon.svg b/docfx/img/logo/color-icon.svg new file mode 100644 index 00000000..c9c7f614 --- /dev/null +++ b/docfx/img/logo/color-icon.svg @@ -0,0 +1,43 @@ + + + + + + + + + + + + + diff --git a/docfx/index.md b/docfx/index.md index e053c0dd..9c00cc1c 100644 --- a/docfx/index.md +++ b/docfx/index.md @@ -1,408 +1,34 @@ -# Getting Started +# Introduction -## Installing the package - -First, install [the Archipelago.MultiClient.Net package from NuGet](https://www.nuget.org/packages/Archipelago.MultiClient.Net). NuGet provides several options for how to do this with examples given on the page. Optionally, you can also install the community-supported [Archipelago.MultiClient.Net.Analyzers package](https://www.nuget.org/packages/Archipelago.MultiClient.Net.Analyzers), which provides source generators, code analysis, and fixes to help prevent and correct common usage errors at compile time. - -## Create Session Instance - -```csharp -var session = ArchipelagoSessionFactory.CreateSession("localhost", 38281); - -// alternatively... -var session = ArchipelagoSessionFactory.CreateSession(new Uri("ws://localhost:38281")); -var session = ArchipelagoSessionFactory.CreateSession("localhost:38281"); -var session = ArchipelagoSessionFactory.CreateSession("localhost"); -``` - -The freshly created `ArchipelagoSession` object is the entrypoint for all incoming and outgoing interactions with the server. Keep it in scope for at least the lifetime of the connection. If the room changes ports, or the user needs to connect to a different room, then a new session needs to be created at the new host and port. - -## Connect to Room - -Connect to a server at a specific room slot using the following method: - -```csharp -LoginResult TryConnectAndLogin( - string game, // Name of the game implemented by this client, SHOULD match what is used in the world implementation - string name, // Name of the slot to connect as (a.k.a player name) - ItemsHandlingFlags itemsHandlingFlags, /* One of the following (see AP docs for details): - NoItems - RemoteItems - IncludeOwnItems - IncludeStartingInventory - AllItems - */ - Version version = null, // Minimum Archipelago world specification version which this client can successfuly interface with - string[] tags = null, /* One of the following (see AP docs for details) - "DeathLink" - "Tracker" - "TextOnly" - */ - string uuid = null, // Unique identifier for this player/client, if null randomly generated - string password = null, // Password that was set when the room was created - bool requestSlotData = true // If the LoginResult should contain the slot data - ); -``` - -For example, - -```csharp -LoginResult result = session.TryConnectAndLogin("Risk of Rain 2", "Ijwu", ItemsHandlingFlags.AllItems); -``` - -Would attempt to connect to a password-less room at the slot `Ijwu`, and report the game `Risk of Rain 2` with a minimum apworld version of `v2.1.0`. - -Once connected, you have access to a suite of helper objects which provide an interface for sending/receiving information with the server. - -### Example Connection - -```csharp -private static void Connect(string server, string user, string pass) -{ - LoginResult result; - - try - { - // handle TryConnectAndLogin attempt here and save the returned object to `result` - } - catch (Exception e) - { - result = new LoginFailure(e.GetBaseException().Message); - } - - if (!result.Successful) - { - LoginFailure failure = (LoginFailure)result; - string errorMessage = $"Failed to Connect to {server} as {user}:"; - foreach (string error in failure.Errors) - { - errorMessage += $"\n {error}"; - } - foreach (ConnectionRefusedError error in failure.ErrorCodes) - { - errorMessage += $"\n {error}"; - } - - return; // Did not connect, show the user the contents of `errorMessage` - } - - // Successfully connected, `ArchipelagoSession` (assume statically defined as `session` from now on) can now be used to interact with the server and the returned `LoginSuccessful` contains some useful information about the initial connection (e.g. a copy of the slot data as `loginSuccess.SlotData`) - var loginSuccess = (LoginSuccessful)result; -} -``` - -If using .net 4.0 or higher, you can use `ConnectAsync` and `LoginAsync` to prevent hitching for injection-based implementations like harmony. - -## Helper Overview - -```csharp -session.Socket // Payload-agnostic interface for sending/receving the most basic transmission units between client/server -session.Items // Helpers for handling receipt of items -session.Locations // Helpers for reporting visited locations to the servers -session.Players // Helpers for translating player number, alias, name etc. -session.DataStorage // Helpers for reading/writing globally accessible to any client connected in the room -session.ConnectionInfo // Helpers for reading/handling useful information on the current connection -session.RoomState // Information on the state of the room -session.MessageLog // Interface for the server to push info messages to the user -``` - -## Players - -The player helper provides methods for accessing details about the other players currently connected to the Archipelago session. - -### Get All Player Names - -```csharp -var sortedPlayerNames = session.Players.AllPlayers.Select(x => x.Name).OrderBy(x => x); -``` - -### Get Current Player Name - -```csharp -string playerName = session.Players.GetPlayerAliasAndName(session.ConnectionInfo.Slot); -``` - -## Locations - -### Report Collected Location(s) - -Call the following method to inform the server of locations whose items have been "found", and therefore should be distributed (if neccessary): - -```csharp -// Report multiple at once -session.Locations.CompleteLocationChecks(new []{1,3,8}); - -// Or report one at a time -session.Locations.CompleteLocationChecks(3); -``` - -The location ID used is of that defined in the AP world. - -### Location ID <--> Name - -```csharp -string locationName = session.Locations.GetLocationNameFromId(42) ?? $"Location: {locationId}"; -long locationId = session.Locations.GetLocationIdFromName(locationName); -``` - -### Scout Location Checks - -Scouting means asking the server what is stored in a specific location *without* collecting it: - -```csharp -session.Locations.ScoutLocationsAsync(locationInfoPacket => Console.WriteLine(locationInfoPacket.Locations.Count)); -``` - -## Items - -### Item ID --> Name - -```csharp -string itemName = session.Items.GetItemName(88) ?? $"Item: {itemId}"; -``` - -### Access Received Items - -At any time, you can access the current inventory for the active session/slot via the `Items` helper like so: - -```csharp -foreach(NetworkItem item in session.Items.AllItemsReceived) -{ - long itemId = item.Item; -} -``` +Archipelago.MultiClient.net is a client library for use with .NET based applications for interfacing with +[Archipelago](https://github.com/ArchipelagoMW/Archipelago) server hosts. This library conforms with the latest stable +[Archipelago Network Protocol Specification](https://github.com/ArchipelagoMW/Archipelago/blob/main/docs/network%20protocol.md). -*Note: The list of received items will never shrink and the collection is guaranteed to be in the order that the server sent the items. Because of this, it is safe to assume that if the size of this collection has changed it's because new items were received and appended to the end of the collection.* - -### Received Item Callback Handler (Asynchronous) - -```csharp -// Must go AFTER a successful connection attempt -session.Items.ItemReceived += (receivedItemsHelper) => { - var itemReceivedName = receivedItemsHelper.PeekItemName() ?? $"Item: {itemId}"; - - // ... Handle item receipt here - - receivedItemsHelper.DequeueItem(); -}; -``` - -*Note: This callback event will occur for every item on connection and reconnection. Whether or not it includes the first batch of remote items depends on your `ItemHandlingFlags` when connecting.* - -## RoomState - -The roomstate helper provides access to values that represent the current state of the multiworld room, with information such as the cost of a hint and or your current accumulated amount of hint point or the permissions for things like forfeiting - -```csharp -Console.WriteLine($"You have {session.RoomState.HintPoints}, and need {session.RoomState.HintCost} for a hint"); -``` - -## ConnectionInfo - -The conection info helper provides access to values under which you are currently connected, such as your slot number or your currently used tags and item handling flags - -```csharp -Console.WriteLine($"You are connected on slot {session.ConnectionInfo.Slot}, on team {session.ConnectionInfo.Team}"); -``` - -## ArchipelagoSocket - -The socket helper is a lower level API allowing for direct access to the socket which the session object uses to communicate with the Archipelago server. You may use this object to hook onto when messages are received or you may use it to send any packets defined in the library. Various events are exposed to allow for receipt of errors or notifying of socket close. - -```csharp -session.Socket.SendPacket(new SayPacket(){Text = "Woof woof!"}); -``` - -## DeathLink - -DeathLink support is included in the library. You may enable it by using the `CreateDeathLinkService` in the `DeathLinkProvider` class, and the `EnableDeathlink` method on the service. Deathlink can be toggled on an off by the the `EnableDeathlink` and `DisableDeathlink` methods on the service - -```csharp -var session = ArchipelagoSessionFactory.CreateSession("localhost", 38281); - -var deathLinkService = session.CreateDeathLinkService().EnableDeathlink(); -session.TryConnectAndLogin("Risk of Rain 2", "Ijwu", ItemsHandlingFlags.AllItems); - -deathLinkService.OnDeathLinkReceived += (deathLinkObject) => { - // ... Kill your player(s). -}; - -// ... On death: -deathLinkService.SendDeathLink(new DeathLink("Ijwu", "Died to exposure.")); -``` - -## DataStorage - -DataStorage support is included in the library. You may save values on the archipelago server in order to share them across other player's sessions or to simply keep track of values outside of your game's state. - -The DataStorage provides an interface based on keys and their scope. By assigning a value to a key, that value is stored on the server and by reading from a key a value is retrieved from the server. -Assigning and reading values from the store can be done using simple assignments `=`: -* `= session.DataStorage["Key"]`, read value from the data storage synchronously -* `session.DataStorage["Key"] =`, write value to the data storage asynchronously -* Complex objects need to be stored and retrieved in the form of a `JObject`, therefor you must wrap them into a `JObject.FromObject()` - -The DataStorage also provides methods to retrieve the value of a key asynchronously using `[key].GetAsync`. -To set the initial value of a key without overriding any existing value the `[key].Initialize` method can be used. -If you're interested in keeping track of when a value of a certain key is changed by any client you can use the `[key].OnValueChanged` handler to register a callback for when the value gets updated. - -Mathematical operations on values stored on the server are supported using the following operators: -* `+`, Add right value to left value -* `-`, Subtract right value from left value -* `*`, Multiply left value by right value -* `/`, Divide left value by right value -* `%`, Gets remainder after dividing left value by right value -* `^`, Multiply left value by the power of the right value - -Bitwise operations on values stored on the server are supported using the following opperations: -* `+ Bitwise.Xor(x)`, apply logical exclusive OR to the left value using value x -* `+ Bitwise.Or(x)`, apply logical OR to the left value using value x -* `+ Bitwise.And(x)`, apply logical AND to the left value using value x -* `+ Bitwise.LeftShift(x)`, binary shift the left value to the left by x -* `+ Bitwise.RightShift(x)`, binary shift the left value to the right by x - -Other operations on values stored on the server are supported using the following opperations: -* `+ Operation.Min(x)`, get the lowest value of the left value and x -* `+ Operation.Max(x)`, get the highest value of the left value and x -* `+ Operation.Remove(x)`, when the left value is a list, removes the first element with value x -* `+ Operation.Pop(x)`, when the left value is a list or dictionary, removes the element at index x or key x -* `+ Operation.Update(x)`, when the left value is a list or dictionary, updates the dictionary with the keys/values in x - -Operation specific callbacks are supported, these get called only once with the results of the current operation: -* `+ Callback.Add((oldValue, newValue) => {});`, calls this method after your operation or chain of operations are proccesed by the server - -Mathematical operations, bitwise operations and callbacks can be chained, given the extended syntax with `()` around each operation. - -Examples: -```csharp -var session = ArchipelagoSessionFactory.CreateSession("localhost", 38281); -session.TryConnectAndLogin("Timespinner", "Jarno", ItemsHandlingFlags.AllItems); - -//Initializing -session.DataStorage["B"].Initialize(20); //Set initial value for B in global scope if it has no value assigned yet - -//Storing/Updating -session.DataStorage[Scope.Slot, "SetPersonal"] = 20; //Set `SetPersonal` to 20, in scope of the current connected user\slot -session.DataStorage[Scope.Global, "SetGlobal"] = 30; //Set `SetGlobal` to 30, in global scope shared among all players (the default scope is global) -session.DataStorage["Add"] += 50; //Add 50 to the current value of `Add` -session.DataStorage["Divide"] /= 2; //Divide current value of `Divide` in half -session.DataStorage["Max"] += + Operation.Max(80); //Set `Max` to 80 if the stored value is lower than 80 -session.DataStorage["Dictionary"] = JObject.FromObject(new Dictionary()); //Set `Dictionary` to a Dictionary -session.DataStorage["SetObject"] = JObject.FromObject(new SomeClassOrStruct()); //Set `SetObject` to a custom object -session.DataStorage["BitShiftLeft"] += Bitwise.LeftShift(1); //Bitshift current value of `BitShiftLeft` to left by 1 -session.DataStorage["Xor"] += Bitwise.Xor(0xFF); //Modify `Xor` using the Bitwise exclusive or operation -session.DataStorage["DifferentKey"] = session.DataStorage["A"] - 30; //Get value of `A`, Assign it to `DifferentKey` and then subtract 30 -session.DataStorage["Array"] = new []{ "One", "Two" }; //Arrays can be stored directly, List's needs to be converted ToArray() first -session.DataStorage["Array"] += new []{ "Three" }; //Append array values to existing array on the server - -//Chaining operations -session.DataStorage["Min"] = (session.DataStorage["Min"] + 40) + Operation.Min(100); //Add 40 to `Min`, then Set `Min` to 100 if `Min` is bigger than 100 -session.DataStorage["C"] = ((session.DataStorage["C"] - 6) + Bitwise.RightShift(1)) ^ 3; //Subtract 6 from `C`, then multiply `C` by 2 using bitshifting, then take `C` to the power of 3 - -//Update callbacks -//EnergyLink deplete pattern, subtract 50, then set value to 0 if its lower than 0 -session.DataStorage["EnergyLink"] = ((session.DataStorage["EnergyLink"] - 50) + Operation.Min(0)) + Callback.Add((oldData, newData) => { - var actualDepleted = (float)newData - (float)oldData; //calculate the actual change, might differ if there was less than 50 left on the server -}); - -//Keeping track of changes -session.DataStorage["OnChangeHandler"].OnValueChanged += (oldData, newData) => { - var changed = (int)newData - (int)oldData; //Keep track of changes made to `OnChangeHandler` by any client, and calculate the difference -}; - -//Keeping track of change (but for more complex data structures) -session.DataStorage["OnChangeHandler"].OnValueChanged += (oldData, newData) => { - var old_dict = oldData.ToObject>(); - var new_dict = newData.ToObject>(); -}; - -//Retrieving -session.DataStorage["Async"].GetAsync(s => { string r = s }); //Retrieve value of `Async` asynchronously -float f = session.DataStorage["Float"]; //Retrieve value for `Float` synchronously and store it as a float -var d = session.DataStorage["DateTime"].To() //Retrieve value for `DateTime` as a DateTime struct -var array = session.DataStorage["Strings"].To() //Retrieve value for `Strings` as string Array - -//Handling anonymous object, if the target type is not known you can use `To()` and use its interface to access the members -session.DataStorage["Anonymous"] = JObject.FromObject(new { Number = 10, Text = "Hello" }); //Set `Anonymous` to an anonymous object -var obj = session.DataStorage["Anonymous"].To(); //Retrieve value for `Anonymous` where an anonymous object was stored -var number = (int)obj["Number"]; //Get value for anonymous object key `Number` -var text = (string)obj["Text"]; //Get value for anonymous object key `Text` - -``` - -## Message Logging - -The Archipelago server can send messages to client to be displayed on screen as sort of a log, this is done by handling the `PrintJsonPacket` packets. This library simplifies this process into a single handler for you to handle. -```csharp -var session = ArchipelagoSessionFactory.CreateSession("localhost", 38281); -session.MessageLog.OnMessageReceived += OnMessageReceived; -session.TryConnectAndLogin("Timespinner", "Jarno", ItemsHandlingFlags.AllItems, new Version(0,3,5)); - -static void OnMessageReceived(LogMessage message) -{ - DisplayOnScreen(message.ToString()); -} -``` - -In some cased you might want extra information that is provided by the server in such cases you can use type checking +## Installing the package -```csharp -static void OnMessageReceived(LogMessage message) -{ - switch (message) - { - case ItemHintLogMessage hintLogMessage: - var receiver = itemSendLogMessage.Receiver; - var sender = itemSendLogMessage.Sender; - var networkItem = itemSendLogMessage.Item; - var found = hintLogMessage.IsFound; - break; - case ItemSendLogMessage itemSendLogMessage: - var receiver = itemSendLogMessage.Receiver; - var sender = itemSendLogMessage.Sender; - var networkItem = itemSendLogMessage.Item; - break; - } - DisplayOnScreen(message.ToString()); -} -``` +First, install the [Archipelago.MultiClient.Net package from NuGet](https://www.nuget.org/packages/Archipelago.MultiClient.Net). +NuGet provides several options for how to do this with examples given on the page. Optionally, you can also install the +community-supported [Archipelago.MultiClient.Net.Analyzers package](https://www.nuget.org/packages/Archipelago.MultiClient.Net.Analyzers), +which provides source generators, code analysis, and fixes to help prevent and correct common usage errors at compile +time. -If you want more control over how the message is displayed, like for example you might want to color certain parts of the message, -Then you can use the `Parts` property. This returns each part of the message in order of appearnce with the `Text` to be displayed and also the `Color` it would normally be diplayed in. -If `IsBackgroundColor` is true, then the color should be applied to the message background instead. -The MessagePart message can also contain additional information that can be retrieved by type checking. +## Concepts +### Session -```csharp -foreach (part in message.Parts) -{ - switch (part) - { - case ItemMessagePart itemMessagePart: - var itemId = itemMessagePart.ItemId; - var flags = itemMessagePart.Flags; - break; - case LocationMessagePart locationMessagePart: - var locationId = locationMessagePart.LocationId; - break; - case PlayerMessagePart playerMessagePart: - var slotId = playerMessagePart.SlotId; - var isCurrentPlayer = playerMessagePart.IsActivePlayer; - break; - } +The @"Archipelago.MultiClient.Net.ArchipelagoSession?text=ArchipelagoSession" is the basis of all operations involved +with communicating with the Archipelago server. Before any communicating can be executed, a new session must be created, +and any relevant [event hooks](docs/helpers/events.md) should be registered before attempting a connection. - DisplayOnScreen(part.Text, part.Color, part.IsBackgroundColor); -} -``` +### Helpers -## Send Completion +There exist many [helper classes and methods](docs/helpers/helpers.md) to help digest the information received from the server +into specific formats, or to send specific information to the server. If a helper doesn't do what you need, the raw +server data is also available to do what is needed through the +@"Archipelago.MultiClient.Net.Helpers.IArchipelagoSocketHelper?text=Session.Socket". -You can report the completion of the player's goal like so: +### Packets -```csharp -public static void send_completion() -{ - var statusUpdatePacket = new StatusUpdatePacket(); - statusUpdatePacket.Status = ArchipelagoClientState.ClientGoal; - Session.Socket.SendPacket(statusUpdatePacket); -} -``` +Communication with the Archipelago server is done by sending and receiving various json packets through the websocket +connection. Most packets that you want to send will have abstraction layers available through the helpers, but sometimes +there is need to send raw packets such as a @"Archipelago.MultiClient.Net.Packets.SayPacket?text=SayPacket".