Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions documentation/manual-test-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,24 @@ distance the walk check uses.
is refused from two cells further away
- [ ] Cast while walking: the hit lands and you are not pulled back to an old cell

### Cast time

A skill's cast time (Skill.dat, tenths of a second) is waited out on the server, after a
`ct` that shows the wind-up.

- [ ] Cast Slingshot (203, 1 s) at a monster: a cast bar and charging effect appear over the
character, and the damage lands about a second later, not at once
- [ ] A second character next to you sees the same wind-up
- [ ] Kill the target with another character during the wind-up: the cast ends without a hit
- [ ] A monster with a cast-time skill stops chasing while it winds up, then resumes

### Debuff resistance

- [ ] Let a monster whose skill causes Blackout hit you: Blackout lands on every hit that
connects
- [ ] Wear the Monkey Hat ("high chance of protection from Blackouts") and repeat: Blackout
lands only now and then (about one hit in ten)

### Area skills and bystanders

- [ ] Stand a second character next to a monster and cast an area skill at the monster: the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ namespace NosCore.GameObject.Ecs.Components;

// Per-skill cooldown tracker for non-player entities (monsters, pets, NPCs). Characters
// keep cooldown state on their CharacterSkill instances, so they don't need this.
public record struct SkillCooldownComponent(ConcurrentDictionary<short, Instant> NextUsableAt);
// CastingUntil holds the entity still while a skill with a cast time winds up.
public record struct SkillCooldownComponent(ConcurrentDictionary<short, Instant> NextUsableAt, Instant CastingUntil);
2 changes: 2 additions & 0 deletions src/NosCore.GameObject/Ecs/Interfaces/INonPlayableEntity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ public interface INonPlayableEntity : IAliveEntity

CachedPath? ChasePath { get; set; }

Instant CastingUntil { get; set; }

new bool IsAlive { get; set; }

new byte Speed { get; set; }
Expand Down
6 changes: 3 additions & 3 deletions src/NosCore.GameObject/Ecs/MapWorld.cs
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ public Entity CreateMonster(
new BuffStateComponent(new ConcurrentDictionary<short, BuffInstance>()),
new AggroComponent(VisualType.Object, 0, 0, Instant.MinValue),
new ChasePathComponent(null),
new SkillCooldownComponent(new ConcurrentDictionary<short, Instant>()),
new SkillCooldownComponent(new ConcurrentDictionary<short, Instant>(), Instant.MinValue),
new HitListComponent(new ConcurrentDictionary<Entity, int>()),
new RespawnComponent(null)
);
Expand Down Expand Up @@ -310,7 +310,7 @@ public Entity CreateNpc(
new BuffStateComponent(new ConcurrentDictionary<short, BuffInstance>()),
new AggroComponent(VisualType.Object, 0, 0, Instant.MinValue),
new ChasePathComponent(null),
new SkillCooldownComponent(new ConcurrentDictionary<short, Instant>()),
new SkillCooldownComponent(new ConcurrentDictionary<short, Instant>(), Instant.MinValue),
new HitListComponent(new ConcurrentDictionary<Entity, int>()),
new RespawnComponent(null)
);
Expand Down Expand Up @@ -344,7 +344,7 @@ public Entity CreateMate(
new BuffStateComponent(new ConcurrentDictionary<short, BuffInstance>()),
new AggroComponent(VisualType.Object, 0, 0, Instant.MinValue),
new ChasePathComponent(null),
new SkillCooldownComponent(new ConcurrentDictionary<short, Instant>()),
new SkillCooldownComponent(new ConcurrentDictionary<short, Instant>(), Instant.MinValue),
new MateStateComponent(mate, mate.CharacterId),
new HitListComponent(new ConcurrentDictionary<Entity, int>())
);
Expand Down
43 changes: 43 additions & 0 deletions src/NosCore.GameObject/Services/BattleService/BattleService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public sealed class BattleService(
ISessionRegistry sessionRegistry,
IClock clock,
ICaptureService captureService,
ICastDelayService castDelayService,
ILogger<BattleService> logger) : IBattleService, ISingletonService
{
public async Task<bool> Hit(IAliveEntity origin, IAliveEntity target, HitArguments arguments)
Expand Down Expand Up @@ -75,6 +76,12 @@ public async Task<bool> Hit(IAliveEntity origin, IAliveEntity target, HitArgumen
return true;
}

if (!await CastAsync(origin, target, skill))
{
await CancelAsync(origin, target);
return false;
}

var targets = targetResolver.Resolve(origin, target, skill);
if (skill.HitsSeveral && arguments.ListedTargets is { Count: > 0 } listed)
{
Expand Down Expand Up @@ -106,6 +113,12 @@ public async Task<bool> HitArea(IAliveEntity origin, short mapX, short mapY, Hit
return false;
}

if (!await CastAsync(origin, null, skill))
{
await CancelAsync(origin, null);
return false;
}

var presentation = new HitPresentation(mapX, mapY, true);
var targets = targetResolver.ResolveArea(origin, mapInstance, mapX, mapY, skill);
for (var i = 0; i < targets.Count; i++)
Expand Down Expand Up @@ -249,6 +262,36 @@ private static Task BroadcastHitAsync(IAliveEntity origin, IAliveEntity target,
// Where su draws the blow from and whether it is drawn as caught in an area.
private readonly record struct HitPresentation(short X, short Y, bool InArea);

// The client sends the skill as soon as it is used and leaves the wind-up to the server:
// ct starts the cast animation, and the hit resolves once the cast time has passed and
// both sides can still fight.
private async Task<bool> CastAsync(IAliveEntity origin, IAliveEntity? target, SkillInfo skill)
{
if (skill.CastTime <= 0)
{
return true;
}

var map = origin.MapInstance;
if (map != null)
{
await map.SendPacketAsync(new CtPacket
{
VisualType = origin.VisualType,
VisualId = origin.VisualId,
TargetVisualType = (target ?? origin).VisualType,
TargetId = (target ?? origin).VisualId,
CastAnimationId = skill.CastAnimation,
CastEffect = skill.CastEffect,
SkillId = skill.SkillVnum
});
}

await castDelayService.WaitAsync(Duration.FromMilliseconds(skill.CastTime * 100));
return ReferenceEquals(origin.MapInstance, map)
&& (target == null ? CanCast(origin) : CanAttack(origin, target));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

private void ScheduleCooldownReset(IAliveEntity origin, SkillInfo skill)
{
if (origin is not PlayerComponentBundle character) return;
Expand Down
16 changes: 16 additions & 0 deletions src/NosCore.GameObject/Services/BattleService/CastDelayService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// __ _ __ __ ___ __ ___ ___
// | \| |/__\ /' _/ / _//__\| _ \ __|
// | | ' | \/ |`._`.| \_| \/ | v / _|
// |_|\__|\__/ |___/ \__/\__/|_|_\___|
//

using System.Threading.Tasks;
using NodaTime;
using NosCore.GameObject.Infastructure;

namespace NosCore.GameObject.Services.BattleService;

public sealed class CastDelayService : ICastDelayService, ISingletonService
{
public Task WaitAsync(Duration castTime) => Task.Delay(castTime.ToTimeSpan());
}
15 changes: 15 additions & 0 deletions src/NosCore.GameObject/Services/BattleService/ICastDelayService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// __ _ __ __ ___ __ ___ ___
// | \| |/__\ /' _/ / _//__\| _ \ __|
// | | ' | \/ |`._`.| \_| \/ | v / _|
// |_|\__|\__/ |___/ \__/\__/|_|_\___|
//

using System.Threading.Tasks;
using NodaTime;

namespace NosCore.GameObject.Services.BattleService;

public interface ICastDelayService
{
Task WaitAsync(Duration castTime);
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ public sealed record SkillInfo(
short Duration,
short MpCost,
IReadOnlyList<BCardDto> BCards,
string? CellPattern = null)
string? CellPattern = null,
short CastAnimation = 0,
// Tenths of a second the caster winds up before the hit lands.
short CastTime = 0)
{
public bool IsAoe => HitType is TargetHitType.SingleAoeTargetHit
or TargetHitType.AoeTargetHit
Expand Down
40 changes: 38 additions & 2 deletions src/NosCore.GameObject/Services/BattleService/MonsterAi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ public async Task<bool> TickAsync(INonPlayableEntity entity)
{
if (!entity.IsAlive || entity.NpcMonster == null) return false;

if (entity.CastingUntil > clock.GetCurrentInstant()) return true;

var target = CurrentTarget(entity);
if (target == null && entity.NpcMonster.IsHostile)
{
Expand Down Expand Up @@ -359,7 +361,8 @@ private static bool SameGroup(NpcMonsterDto entity, NpcMonsterDto? other)
SkillVnum: dto.SkillVNum,
CastId: dto.CastId,
SkillRange: Math.Max(1, (int)dto.Range),
CooldownMs: Math.Max(200, dto.Cooldown * 100));
CooldownMs: Math.Max(200, dto.Cooldown * 100),
CastTimeMs: dto.CastTime * 100);
}
return null;
}
Expand All @@ -378,6 +381,20 @@ private async Task AttackAsync(INonPlayableEntity entity, IAliveEntity target, C
return;
}

if (skill.CastTimeMs > 0)
{
// The life loop must not wait out the cast: the monster stands still until the hit
// has resolved on its own.
if (cooldowns != null)
{
cooldowns.Value.NextUsableAt[skill.SkillVnum] = now.Plus(Duration.FromMilliseconds(skill.CooldownMs));
}

entity.CastingUntil = Instant.MaxValue;
_ = HitAfterCastAsync(entity, target, skill);
return;
}

var accepted = await battleService.Hit(entity, target, new HitArguments { SkillId = skill.CastId });

if (accepted && cooldowns != null)
Expand All @@ -386,6 +403,25 @@ private async Task AttackAsync(INonPlayableEntity entity, IAliveEntity target, C
}
}

private async Task HitAfterCastAsync(INonPlayableEntity entity, IAliveEntity target, ChosenSkill skill)
{
try
{
await battleService.Hit(entity, target, new HitArguments { SkillId = skill.CastId });
}
catch (Exception ex)
{
logger.LogError(ex, "Cast of skill {Skill} by {VisualId} failed", skill.SkillVnum, entity.VisualId);
}
finally
{
if (entity.MapInstance?.EcsWorld.IsAlive(entity.Handle) == true)
{
entity.CastingUntil = Instant.MinValue;
}
}
}

// Walks a cached JPS path toward the goal (a target's cell, or the spawn cell to go
// home), re-planning when the goal changed or the path ran out. Consumes `Speed / 2`
// cells per tick: the 400ms life-loop cadence is already the rate limit. The path
Expand Down Expand Up @@ -439,5 +475,5 @@ private async Task<bool> StepAlongPathAsync(INonPlayableEntity entity, short goa
return true;
}

private sealed record ChosenSkill(short SkillVnum, long CastId, int SkillRange, int CooldownMs);
private sealed record ChosenSkill(short SkillVnum, long CastId, int SkillRange, int CooldownMs, int CastTimeMs = 0);
}
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,8 @@ private SkillInfo BuildInfo(SkillDto main, SkillDto? upgrade, long castId)
Duration: main.Duration,
MpCost: main.MpCost,
BCards: _catalog.GetSkillBCards(main.SkillVNum),
CellPattern: main.CellPattern);
CellPattern: main.CellPattern,
CastAnimation: main.CastAnimation,
CastTime: main.CastTime);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ public async Task SetupAsync()
new Mock<GameObject.Services.BroadcastService.ISessionRegistry>().Object,
NodaTime.SystemClock.Instance,
new Mock<ICaptureService>().Object,
new Mock<NosCore.GameObject.Services.BattleService.ICastDelayService>().Object,
NullLogger<GameObject.Services.BattleService.BattleService>.Instance);
_origin = new FakeEntity { Hp = 100, VisualId = 1 };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ public async Task ACastSkillIsReadyAgainOnceItsCooldownHasRunOut()
var service = new GameObject.Services.BattleService.BattleService(
skillResolver.Object, targetResolver.Object, hitQueue.Object, new Mock<IMessageBus>().Object,
World.SessionRegistry, clock, new Mock<ICaptureService>().Object,
new Mock<NosCore.GameObject.Services.BattleService.ICastDelayService>().Object,
NullLogger<GameObject.Services.BattleService.BattleService>.Instance);

Assert.IsTrue(await service.Hit(session.Character, monster, new HitArguments { SkillId = 7 }));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public class BattleServiceTests
private Mock<ITargetResolver> _targetResolver;
private Mock<IHitQueue> _hitQueue;
private Mock<IMessageBus> _bus;
private Mock<ICastDelayService> _castDelay;
private GameObject.Services.BattleService.BattleService _service;

[TestInitialize]
Expand All @@ -43,6 +44,8 @@ public void Setup()
_targetResolver = new Mock<ITargetResolver>();
_hitQueue = new Mock<IHitQueue>();
_bus = new Mock<IMessageBus>();
_castDelay = new Mock<ICastDelayService>();
_castDelay.Setup(d => d.WaitAsync(It.IsAny<NodaTime.Duration>())).Returns(Task.CompletedTask);
_service = new GameObject.Services.BattleService.BattleService(
_skillResolver.Object,
_targetResolver.Object,
Expand All @@ -51,9 +54,53 @@ public void Setup()
new Mock<GameObject.Services.BroadcastService.ISessionRegistry>().Object,
NodaTime.SystemClock.Instance,
new Mock<NosCore.GameObject.Services.BattleService.ICaptureService>().Object,
_castDelay.Object,
NullLogger<NosCore.GameObject.Services.BattleService.BattleService>.Instance);
}

[TestMethod]
public async Task ASkillWithACastTimeHitsOnlyOnceTheCastEnds()
{
var origin = new FakeEntity { Hp = 100 };
var target = new FakeEntity { Hp = 100, VisualType = VisualType.Monster };
SetupLanding(origin, target, MakeSkill(TargetHitType.SingleTargetHit) with { CastTime = 10 });
var cast = new TaskCompletionSource();
_castDelay.Setup(d => d.WaitAsync(NodaTime.Duration.FromSeconds(1))).Returns(cast.Task);

var hit = _service.Hit(origin, target, new HitArguments { SkillId = 1 });
_hitQueue.Verify(q => q.EnqueueAsync(It.IsAny<HitRequest>()), Times.Never);

cast.SetResult();
Assert.IsTrue(await hit);
_hitQueue.Verify(q => q.EnqueueAsync(It.IsAny<HitRequest>()), Times.Once);
}

[TestMethod]
public async Task ACastWhoseTargetDiesMeanwhileLandsNothing()
{
var origin = new FakeEntity { Hp = 100 };
var target = new FakeEntity { Hp = 100, VisualType = VisualType.Monster };
SetupLanding(origin, target, MakeSkill(TargetHitType.SingleTargetHit) with { CastTime = 10 });
_castDelay.Setup(d => d.WaitAsync(It.IsAny<NodaTime.Duration>()))
.Callback(() => target.Hp = 0)
.Returns(Task.CompletedTask);

Assert.IsFalse(await _service.Hit(origin, target, new HitArguments { SkillId = 1 }));
_hitQueue.Verify(q => q.EnqueueAsync(It.IsAny<HitRequest>()), Times.Never);
}

[TestMethod]
public async Task ASkillWithoutACastTimeDoesNotWait()
{
var origin = new FakeEntity { Hp = 100 };
var target = new FakeEntity { Hp = 100, VisualType = VisualType.Monster };
SetupLanding(origin, target, MakeSkill(TargetHitType.SingleTargetHit));

await _service.Hit(origin, target, new HitArguments { SkillId = 1 });

_castDelay.Verify(d => d.WaitAsync(It.IsAny<NodaTime.Duration>()), Times.Never);
}

[TestMethod]
public async Task CannotAttackWhenAttackerIsDead()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,43 @@ public async Task AGroupMemberIgnoresAFightBeyondItsNoticeRange()
}

// The shared fixture map declares 8 rows but ships 6, which the pathfinder walks off.
[TestMethod]
public async Task AMonsterWindingUpASkillStandsStillUntilItsHitResolvesWithoutHoldingUpTheLoop()
{
var catalog = new Mock<INpcCombatCatalog>();
catalog.Setup(c => c.GetSkills(1)).Returns(new List<NpcMonsterSkillDto>
{
new() { NpcMonsterVNum = 1, SkillVNum = 50 }
});
var random = new Mock<IRandomProvider>();
random.Setup(r => r.Next(0, 10)).Returns(9);
var ai = new MonsterAi(_battle.Object, _aggro,
World.Create<GameObject.Services.PathfindingService.PathfindingService>(), World.SessionRegistry,
World.DistanceCalculator, catalog.Object, random.Object, World.Clock,
new Dictionary<short, SkillDto> { [50] = new() { SkillVNum = 50, CastId = 3, Range = 2, Cooldown = 100, CastTime = 10 } },
NullLogger<MonsterAi>.Instance);
var cast = new TaskCompletionSource<bool>();
_battle.Setup(b => b.Hit(It.IsAny<IAliveEntity>(), It.IsAny<IAliveEntity>(), It.Is<HitArguments>(a => a.SkillId == 3)))
.Returns(cast.Task);
var monster = SpawnMonster(4, 1);
PlacePlayer(4, 3);

Assert.IsTrue(await ai.TickAsync(monster));
PlacePlayer(4, 6);
await ai.TickAsync(monster);

Assert.AreEqual((short)1, monster.PositionY);
_battle.Verify(b => b.Hit(It.IsAny<IAliveEntity>(), It.IsAny<IAliveEntity>(), It.IsAny<HitArguments>()), Times.Once);

World.Clock.Advance(Duration.FromMilliseconds(1000));
await ai.TickAsync(monster);
Assert.AreEqual((short)1, monster.PositionY, "the hit has not resolved yet");

cast.SetResult(true);
await ai.TickAsync(monster);
Assert.AreNotEqual((short)1, monster.PositionY);
}

private static GameObject.Map.Map TestMap()
{
var data = new List<byte> { 8, 0, 8, 0 };
Expand Down
Loading