## Pressing `>` on a TextDefinition did nothing useful
`#1217` moved `TextDefinition` into the Server project for serialization support and added `[PropertyObject]` along the way. `PropsGump` checks that attribute **before** its parsable fallback, so from that commit on the button either drilled into a read-only `Number`/`String` page (both get-only since `#1221`, so no `>` buttons — a dead end) or, when the value was null, re-sent the same page and looked inert.
Worth being clear that `#765` — which replaced the hand-maintained type list with a generic `IsParsable` branch — was **not** the regression. At that commit `TextDefinition` was `[Parsable]` only, fell through to the new branch, and the editor worked. Only the later attribute hijacked the routing.
`TextDefinition` is now caught ahead of the `[PropertyObject]` branch and routed to `SetGump`, which has had `TextDefinition`-specific code at line 35 all along.
## `0` and `"0"` could not be told apart
`Commands.Split` strips quotes before any parser runs, so this was never fixable in `TextDefinition.Parse` alone — the information is gone two layers earlier. The markers now travel inside the value:
| Input | Result |
|---|---|
| `1060847` | cliloc (unchanged) |
| `#1060847` | cliloc, explicit — the form `ToString()` already writes |
| `@"1060847"` | the literal string |
| `hello` | string (unchanged) |
| `(-null-)` | null (unchanged) |
`GetValue()` quotes a string that would not survive the trip back. That check is a real round trip through the parser rather than a pattern match, so it cannot drift from it. `Types.TryParse` decodes the same escape for plain strings — which is what `[get` has always written for the literal `"null"` without `[set` ever reading it back.
**Saved data is untouched.** Serialization reads a discriminated flag plus int/string (`IGenericReader.cs:175`) and the JSON converter switches on token type; neither calls `Parse`, so a stored string `"1060847"` stays a string and spawner JSON is unchanged. The new syntax stays in the text and command layer, where it reaches `[set`, `[add`, spawner props, the props gump and Advanced Search.
## `where` still parsed its constants its own way
`#2625` carried the hand-rolled constant parser across to `PropertyExpressions.Parse` unchanged. It looks for a static `Parse` overload on the property type and gives up if there is none — and `Type` and `IEntity` have neither:
```
where Subject Kind = Static -> Unable to convert string "Static" into type 'System.Type'.
where Subject Owner = 0x1 -> Unable to convert string "0x1" into type 'Server.Mobile'.
```
Both resolve fine for every other command. Routing through `Types.TryParse` picks up type-name lookup, entity resolution by serial, and the `@"..."` literal convention, so a value that works in one place now works everywhere. It also deletes the duplicate parser (−56 lines in `PropertyExpressions`).
Two things are load-bearing and preserved. `where` has always spelled a null constant as a bare `null`, where `[set` uses `(-null-)`; the shared parser reads a bare `null` as the text, so the null case is handled ahead of it and `= null` keeps meaning null. And nullable targets still unwrap first, so `where <int? prop> = 5` is unaffected.
Bare and hex integers, enums, bools, strings, `Map`, and TextDefinition's `#` / `@"..."` markers all resolve exactly as before — 13 of the 15 tests in `WhereConstantParsingTests` pin that and passed before the change as well as after.
## Documentation
The generic command system had no documentation anywhere in the repo: scopes, `where` and its operators, dot notation, `order by` / `distinct` / `limit`, the value and quoting syntax, `[interface` and `[batch` were all learn-by-reading-the-source. `dev-docs/generic-commands.md` covers them, linked from `CLAUDE.md` and `commands-targeting.md`, and points at <https://muo.gg/commands> for the per-command list rather than duplicating it.
Two behaviours it records that were news to me while writing it:
- `Contained` honours conditions on the normal command path but never sets `SupportsConditionals`, and `[batch` is the only place that reads the flag — so the same condition works typed directly and is refused under batch.
- `Multi`, `Single`, `Self` and `Serial` do not parse modifiers at all, so a `where` clause there is passed to the command as ordinary arguments rather than rejected.
Comments in the changed code were trimmed to what is not evident from the code itself; the rationale they carried is either in the doc now or in the commit that introduced it.
## Behavior changes worth a reviewer's attention
Two things go beyond strict bug-fixing, both deliberate:
- **Hex now parses into a TextDefinition.** Consolidating the three `Parse` overloads onto one span codec means `[set Message 0x102CE7` is cliloc 1060847 rather than the string. Previously only the 1-arg `Parse(string)` did hex and nothing called it. This makes the props gump's own `1060847 (0x102CE7)` display typeable.
- **`@"..."` decodes generally for strings**, not only the exact token `@"null"`. So `[set Name @"hello"` sets `hello`. A half-working escape seemed more surprising than a general one, and the `where` path already decoded it — but narrowing it back is a one-line change if preferred.
## Testing
40 tests, each written first and watched fail for the right reason. They cover the props gump routing (populated and null), cliloc/string/quoted parsing and `GetValue` round trips, `where` constant resolution for Type- and entity-valued properties, and the bare-`null` vs `@"null"` distinction that must not drift.
One sort case is added that #2625 left uncovered: ordering a value-typed chain whose intermediate is null, which reads as `default(int)` rather than throwing. Two other tests from the pre-rebase branch were dropped as duplicates of `ConditionalCompilerEdgeTests`.
Rebased onto `535a09899`. `dotnet build` clean, 0 warnings. **902 UOContent** and **869 Server** tests pass, 0 failures.
## Known gaps
- `Nullable<T>` comparisons work via #2625's lifted operators; nothing here changes that.
- Spawner **Params** are split on plain spaces (`BaseSpawner.cs:1035`) rather than through `Commands.Split`, so a constructor argument still cannot contain one. Untouched here — a tokenizer issue, not a TextDefinition one.
- `Types.ParseStringNumericParamTypes` is now unreferenced. Left in place because it is public and shards may use it.
10 KiB
10 KiB
ModernUO Commands & Targeting
This document covers ModernUO's command system for in-game [ commands and the targeting system for player interactions.
Command System
Overview
Commands are prefixed with [ by default (e.g., [MyCommand). They are registered in static Configure() methods and associated with an access level.
Registration
using Server.Commands;
namespace Server.Custom;
public static class MyCommands
{
public static void Configure()
{
CommandSystem.Register("MyCommand", AccessLevel.GameMaster, MyCommand_OnCommand);
}
[Usage("MyCommand <name> [count]")]
[Description("Does something with a name and optional count")]
[Aliases("mc", "mycmd")]
public static void MyCommand_OnCommand(CommandEventArgs e)
{
var from = e.Mobile;
if (e.Length < 1)
{
from.SendMessage("Usage: [MyCommand <name> [count]");
return;
}
var name = e.GetString(0);
var count = e.Length > 1 ? e.GetInt32(1) : 1;
from.SendMessage($"Processing {name} x{count}");
}
}
CommandSystem API
public static class CommandSystem
{
public static string Prefix { get; set; } = "[";
public static Dictionary<string, CommandEntry> Entries { get; }
public static void Register(string command, AccessLevel access, CommandEventHandler handler);
public static bool Handle(Mobile from, string text, MessageType type = MessageType.Regular);
public static string[] Split(string value);
}
CommandEventArgs
public class CommandEventArgs
{
public Mobile Mobile { get; } // Who issued the command
public string Command { get; } // Command name
public string ArgString { get; } // Raw argument string
public string[] Arguments { get; } // Split arguments
public int Length { get; } // Argument count
// Typed accessors (return default if index out of range)
public string GetString(int index); // "" if missing
public int GetInt32(int index); // 0 if missing
public uint GetUInt32(int index); // 0 if missing
public bool GetBoolean(int index); // false if missing
public double GetDouble(int index); // 0.0 if missing
public TimeSpan GetTimeSpan(int index); // TimeSpan.Zero if missing
}
Access Levels
public enum AccessLevel
{
Player, // 0 - Regular players
Counselor, // 1 - Support staff
GameMaster, // 2 - Game Masters
Seer, // 3 - Event coordinators
Administrator, // 4 - Server administrators
Developer, // 5 - Developers
Owner // 6 - Server owner
}
Command Attributes
[Usage("CommandName <required> [optional]")]
// Documents command syntax. Displayed in help listings.
[Description("What this command does")]
// Documents command purpose. Displayed in help listings.
[Aliases("alias1", "alias2")]
// Alternative names for the command.
Defined in Projects/Server/Attributes.cs.
Command + Targeting Pattern
A common pattern: command starts targeting, target handler performs the action.
public static class HealCommand
{
public static void Configure()
{
CommandSystem.Register("Heal", AccessLevel.GameMaster, Heal_OnCommand);
}
[Usage("Heal")]
[Description("Fully heals a targeted mobile")]
public static void Heal_OnCommand(CommandEventArgs e)
{
e.Mobile.SendMessage("Select a mobile to heal.");
e.Mobile.Target = new HealTarget();
}
private class HealTarget : Target
{
public HealTarget() : base(-1, false, TargetFlags.Beneficial) { }
protected override void OnTarget(Mobile from, object targeted)
{
if (targeted is Mobile m)
{
m.Hits = m.HitsMax;
m.Mana = m.ManaMax;
m.Stam = m.StamMax;
m.Poison = null;
from.SendMessage($"You have healed {m.Name}.");
}
else
{
from.SendMessage("That is not a mobile.");
}
}
}
}
Targeting System
Overview
The targeting system allows players to select objects in the game world. When a target is set on a mobile, the client shows a targeting cursor. The player clicks on something, and the server processes the selection.
Target Base Class
public abstract class Target
{
// Constructor
protected Target(
int range, // Max range (-1 for unlimited)
bool allowGround, // Can target ground tiles
TargetFlags flags // None, Harmful, Beneficial
);
// Properties
public int Range { get; set; }
public bool AllowGround { get; set; }
public TargetFlags Flags { get; set; }
public bool CheckLOS { get; set; } // Default: true
public bool DisallowMultis { get; set; } // Default: false
public bool AllowNonlocal { get; set; } // Default: false
public int TargetID { get; }
// Override for main handling
protected virtual void OnTarget(Mobile from, object targeted);
// Override for error handling
protected virtual void OnTargetCancel(Mobile from, TargetCancelType cancelType);
protected virtual void OnTargetFinish(Mobile from);
protected virtual void OnTargetOutOfRange(Mobile from, object targeted);
protected virtual void OnTargetOutOfLOS(Mobile from, object targeted);
protected virtual void OnTargetNotAccessible(Mobile from, object targeted);
protected virtual void OnTargetDeleted(Mobile from, object targeted);
protected virtual void OnTargetUntargetable(Mobile from, object targeted);
protected virtual void OnNonlocalTarget(Mobile from, object targeted);
protected virtual void OnCantSeeTarget(Mobile from, object targeted);
protected virtual void OnTargetInSecureTrade(Mobile from, object targeted);
// Validation overrides
protected virtual bool CanTarget(Mobile from, Mobile mobile, ref Point3D loc, ref Map map);
protected virtual bool CanTarget(Mobile from, Item item, ref Point3D loc, ref Map map);
protected virtual bool CanTarget(Mobile from, LandTarget land, ref Point3D loc, ref Map map);
protected virtual bool CanTarget(Mobile from, StaticTarget st, ref Point3D loc, ref Map map);
// Timeout
public void BeginTimeout(Mobile from, long delay);
public void CancelTimeout();
}
TargetFlags
[Flags]
public enum TargetFlags : byte
{
None = 0x00, // Neutral targeting
Harmful = 0x01, // Triggers criminal check, PvP flag
Beneficial = 0x02 // Healing, buffing
}
TargetCancelType
public enum TargetCancelType
{
Overridden, // New target replaced this one
Canceled, // Player pressed Escape
Disconnected, // Player disconnected
Timeout // Target timed out
}
Target Object Types
When OnTarget is called, the targeted parameter can be:
| Type | Description | Key Properties |
|---|---|---|
Mobile |
A player or creature | .Name, .Hits, .Location |
Item |
An item | .Name, .ItemID, .Location |
LandTarget |
Ground tile | .Location, .TileID, .Name |
StaticTarget |
Static map object | .Location, .ItemID, .Hue |
Setting a Target
// Set target on mobile (shows targeting cursor)
mobile.Target = new MyTarget();
// Cancel current target
Target.Cancel(mobile);
Basic Target Implementation
private class IdentifyTarget : Target
{
public IdentifyTarget() : base(12, false, TargetFlags.None)
{
// CheckLOS = false; // Uncomment to skip line-of-sight
}
protected override void OnTarget(Mobile from, object targeted)
{
switch (targeted)
{
case Mobile m:
from.SendMessage($"Mobile: {m.Name}, Hits: {m.Hits}/{m.HitsMax}");
break;
case Item item:
from.SendMessage($"Item: {item.Name ?? item.DefaultName}, ID: 0x{item.ItemID:X}");
break;
case LandTarget land:
from.SendMessage($"Land at {land.Location}, Tile: {land.TileID}");
break;
case StaticTarget st:
from.SendMessage($"Static at {st.Location}, ID: 0x{st.ItemID:X}");
break;
}
}
protected override void OnTargetCancel(Mobile from, TargetCancelType cancelType)
{
if (cancelType == TargetCancelType.Canceled)
from.SendMessage("Targeting cancelled.");
}
protected override void OnTargetFinish(Mobile from)
{
// Always called after success or cancel
}
}
Target Validation Flow
- Client sends target response
- Server validates: same map, within range, line of sight
- Calls
CanTarget()override for type-specific validation - If valid: calls
OnTarget() - If invalid: calls appropriate error handler
- Always calls
OnTargetFinish()at the end
SpellTarget
For spells, use the built-in SpellTarget<T>:
public override void OnCast()
{
Caster.Target = new SpellTarget<Mobile>(this, TargetFlags.Harmful);
}
// The spell's Target(Mobile m) method is called when the player targets
Best Practices
- Register commands in
Configure()-- it's called automatically during startup - Validate argument count before accessing --
GetInt32()returns 0 for missing args (not an error) - Use appropriate access levels -- don't give players GM commands
- Use
TargetFlags.Harmfulfor offensive actions (triggers criminal flagging) - Use
TargetFlags.Beneficialfor healing/buffing - Handle
OnTargetCancelto provide feedback when player cancels - Clean up in
OnTargetFinishif you have state to release
Key File References
| File | Description |
|---|---|
Projects/Server/Commands.cs |
CommandSystem, CommandEventArgs |
Projects/Server/Attributes.cs |
Usage, Description, Aliases |
Projects/Server/Targeting/Target.cs |
Target base class |
Projects/Server/Targeting/TargetFlags.cs |
TargetFlags enum |
Projects/Server/Targeting/TargetCancelType.cs |
Cancel types |
Projects/Server/Targeting/LandTarget.cs |
Land target |
Projects/Server/Targeting/StaticTarget.cs |
Static target |
See Also
dev-docs/generic-commands.md— the generic command system: scopes,whereconditions,order by/distinct/limit, dot notation, value and quoting syntax,[interface,[batch.- https://muo.gg/commands — the full command list, regenerated with distro updates.