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
3 changes: 3 additions & 0 deletions documentation/manual-test-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,9 @@ values from its race, level and equipment levels, then adds the flat modifiers o
- [ ] Kill a Spider Egg (1921): a Strong Magmaros (1918) appears where it died. A Soft Pii Pod
(45) summons two Soft Piis (36) the same way. Monsters with a "chance of summoning upon
death" card, such as the Lava Pit (2014), summon only that often
- [ ] Stand next to a Tired Chief Miner (111) until it uses its skill (407): two Happy Miners
(105) and a Weak Expy Miner (108) appear on its cell. Between skills its hits are plain
basic attacks, not that skill

---

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,16 @@
// |_|\__|\__/ |___/ \__/\__/|_|_\___|
//

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JetBrains.Annotations;
using NosCore.Data.Enumerations.Buff;
using NosCore.Data.StaticEntities;
using NosCore.GameObject.Ecs;
using NosCore.GameObject.Ecs.Extensions;
using NosCore.GameObject.Messaging.Events;
using NosCore.GameObject.Services.BattleService;
using NosCore.Networking;

namespace NosCore.GameObject.Messaging.Handlers.Battle
{
[UsedImplicitly]
public sealed class SummonOnDeathHandler(INpcCombatCatalog catalog, List<NpcMonsterDto> npcMonsters, IRandomProvider random)
public sealed class SummonOnDeathHandler(INpcCombatCatalog catalog, ISummonService summonService)
{
[UsedImplicitly]
public Task Handle(EntityDiedEvent evt)
Expand All @@ -29,37 +23,7 @@ public Task Handle(EntityDiedEvent evt)
return Task.CompletedTask;
}

var summons = new List<NpcMonsterDto>();
foreach (var bcard in catalog.GetDeathBCards(victim.NpcMonster.NpcMonsterVNum))
{
var count = bcard.Effect() switch
{
BCardEffect.SummonsSummonUponDeath => bcard.FirstData,
BCardEffect.SummonsSummonUponDeathChance => random.Next(0, 100) < bcard.FirstData ? 1 : 0,
_ => 0,
};
if (count <= 0 || npcMonsters.Find(m => m.NpcMonsterVNum == bcard.SecondData) is not { } summoned)
{
continue;
}

summons.AddRange(Enumerable.Repeat(summoned, count));
}

if (summons.Count == 0)
{
return Task.CompletedTask;
}

return victim.OnMapAsync(async () =>
{
var map = victim.MapInstance;
foreach (var npcMonster in summons)
{
var monster = map.SpawnMonster(npcMonster, victim.PositionX, victim.PositionY, true);
await map.SendPacketAsync(monster.GenerateIn());
}
});
return summonService.SummonAsync(victim, catalog.GetDeathBCards(victim.NpcMonster.NpcMonsterVNum));
}
}
}
11 changes: 10 additions & 1 deletion src/NosCore.GameObject/Services/BattleService/BattleService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public sealed class BattleService(
IBuffService buffService,
ISkillCastService skillCastService,
ISkillComboService skillComboService,
ISummonService summonService,
ILogger<BattleService> logger, ILogLanguageLocalizer<LogLanguageKey> logLanguage) : IBattleService, ISingletonService
{
public async Task<bool> Hit(IAliveEntity origin, IAliveEntity target, HitArguments arguments)
Expand Down Expand Up @@ -118,6 +119,8 @@ public async Task<bool> Hit(IAliveEntity origin, IAliveEntity target, HitArgumen
await TryProcessHitAsync(origin, targets[i], skill, i == 0, presentation);
}

// After the hits, so a cast never lands on the adds it calls.
await summonService.SummonAsync(origin, skill.BCards);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
ScheduleCooldownReset(origin, skill);
return true;
}
Expand Down Expand Up @@ -162,6 +165,8 @@ await mapInstance.SendPacketAsync(new BsPacket
await TryProcessHitAsync(origin, targets[i], skill, i == 0, presentation);
}

// After the hits, so a cast never lands on the adds it calls.
await summonService.SummonAsync(origin, skill.BCards);
ScheduleCooldownReset(origin, skill);
return true;
}
Expand Down Expand Up @@ -225,6 +230,8 @@ await mapInstance.SendPacketAsync(new SuPacket
}
}

// After the hits, so a cast never lands on the adds it calls.
await summonService.SummonAsync(origin, skill.BCards);
ScheduleCooldownReset(origin, skill);
return true;
}
Expand Down Expand Up @@ -386,7 +393,9 @@ private static Task BroadcastHitAsync(IAliveEntity origin, IAliveEntity target,
// ct starts the cast animation, and the hit resolves once the cast time has passed and
// both sides can still fight.
private SkillInfo? Resolve(IAliveEntity origin, HitArguments arguments) =>
arguments.Skill is { } skill ? skillResolver.Describe(skill) : skillResolver.Resolve(origin, arguments.SkillId);
arguments.Skill is { } skill ? skillResolver.Describe(skill)
: arguments.BasicAttack ? skillResolver.ResolveBasic(origin)
: skillResolver.Resolve(origin, arguments.SkillId);

// A cast at a cell is always announced with ct_n, cast time or not; a cast at an entity
// only needs ct when there is a wind-up to show.
Expand Down
3 changes: 3 additions & 0 deletions src/NosCore.GameObject/Services/BattleService/HitArguments.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,8 @@ public record HitArguments()
// A skill the caller has already checked the caster may use, cast instead of the one SkillId resolves to.
public SkillDto? Skill { get; set; }

// A non-player's basic attack, which a skill of its own sharing cast id 0 must not stand in for.
public bool BasicAttack { get; set; }

public IReadOnlyList<IAliveEntity>? ListedTargets { get; set; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,7 @@ public interface ISkillResolver
{
SkillInfo? Resolve(IAliveEntity caster, long castId);

SkillInfo? ResolveBasic(IAliveEntity caster);

SkillInfo Describe(SkillDto skill);
}
12 changes: 8 additions & 4 deletions src/NosCore.GameObject/Services/BattleService/MonsterAi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,8 @@ private static bool SameGroup(NpcMonsterDto entity, NpcMonsterDto? other)
CastId: dto.CastId,
SkillRange: Math.Max(1, (int)dto.Range),
CooldownMs: Math.Max(200, dto.Cooldown * 100),
CastTimeMs: dto.CastTime * 100);
CastTimeMs: dto.CastTime * 100,
Skill: dto);
}
return null;
}
Expand Down Expand Up @@ -414,7 +415,7 @@ private async Task AttackAsync(INonPlayableEntity entity, IAliveEntity target, C
return;
}

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

if (accepted && cooldowns != null)
{
Expand All @@ -426,7 +427,7 @@ private async Task HitAfterCastAsync(INonPlayableEntity entity, IAliveEntity tar
{
try
{
await battleService.Hit(entity, target, new HitArguments { SkillId = skill.CastId });
await battleService.Hit(entity, target, Arguments(skill));
}
catch (Exception ex)
{
Expand Down Expand Up @@ -493,5 +494,8 @@ private async Task<bool> StepAlongPathAsync(INonPlayableEntity entity, short goa
return true;
}

private sealed record ChosenSkill(short SkillVnum, long CastId, int SkillRange, int CooldownMs, int CastTimeMs = 0);
private static HitArguments Arguments(ChosenSkill skill) =>
new() { SkillId = skill.CastId, Skill = skill.Skill, BasicAttack = skill.Skill == null };

private sealed record ChosenSkill(short SkillVnum, long CastId, int SkillRange, int CooldownMs, int CastTimeMs = 0, SkillDto? Skill = null);
}
16 changes: 14 additions & 2 deletions src/NosCore.GameObject/Services/BattleService/SkillResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,23 @@ public SkillResolver(IReadOnlyDictionary<short, SkillDto> skillsByVnum, INpcComb
if (mob == null) return null;

var resolvedSkill = ResolveNpcSkill(mob, castId);
if (resolvedSkill != null)
return resolvedSkill != null ? BuildInfo(resolvedSkill, null, castId) : BasicAttack(mob);
}

public SkillInfo? ResolveBasic(IAliveEntity caster)
{
if (caster is not INonPlayableEntity { NpcMonster: { } mob })
{
return BuildInfo(resolvedSkill, null, castId);
return null;
}

return mob.BasicSkill > 0 && _skillsByVnum.TryGetValue(mob.BasicSkill, out var basic)
? BuildInfo(basic, null, 0)
: BasicAttack(mob);
}

private static SkillInfo BasicAttack(NpcMonsterDto mob)
{
// No skill in the catalog and no BasicSkill vnum — but the monster still
// needs to hit. The overwhelming majority of low-level mobs fall here
// (melee wolf, rat, etc.) so we synthesise a minimal basic-attack SkillInfo
Expand Down
62 changes: 62 additions & 0 deletions src/NosCore.GameObject/Services/BattleService/SummonService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// __ _ __ __ ___ __ ___ ___
// | \| |/__\ /' _/ / _//__\| _ \ __|
// | | ' | \/ |`._`.| \_| \/ | v / _|
// |_|\__|\__/ |___/ \__/\__/|_|_\___|
//

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NosCore.Data.Enumerations.Buff;
using NosCore.Data.StaticEntities;
using NosCore.GameObject.Ecs.Extensions;
using NosCore.GameObject.Ecs.Interfaces;
using NosCore.GameObject.Infastructure;
using NosCore.Networking;

namespace NosCore.GameObject.Services.BattleService;

public interface ISummonService
{
// Spawns, on the source's cell, every monster its summon cards call for.
Task SummonAsync(IAliveEntity source, IEnumerable<BCardDto> cards);
}

public sealed class SummonService(List<NpcMonsterDto> npcMonsters, IRandomProvider random) : ISummonService, ISingletonService
{
public Task SummonAsync(IAliveEntity source, IEnumerable<BCardDto> cards)
{
var summons = new List<NpcMonsterDto>();
foreach (var card in cards)
{
var count = card.Effect() switch
{
BCardEffect.SummonsSummonUponDeath or BCardEffect.SummonsSummons => card.FirstData,
BCardEffect.SummonsSummonUponDeathChance or BCardEffect.SummonsSummonningChance
=> random.Next(0, 100) < card.FirstData ? 1 : 0,
_ => 0,
};
if (count <= 0 || npcMonsters.Find(m => m.NpcMonsterVNum == card.SecondData) is not { } summoned)
{
continue;
}

summons.AddRange(Enumerable.Repeat(summoned, count));
}

if (summons.Count == 0 || source.MapInstance == null)
{
return Task.CompletedTask;
}

return source.OnMapAsync(async () =>
{
var map = source.MapInstance;
foreach (var npcMonster in summons)
{
var monster = map.SpawnMonster(npcMonster, source.PositionX, source.PositionY, true);
await map.SendPacketAsync(monster.GenerateIn());
}
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,17 @@ public async Task AChanceSummonOnlySpawnsWhenTheRollIsUnderTheChance()
Assert.AreEqual(2, _map.EnumerateMonsters().Count());
}

[TestMethod]
public async Task ASkillSummonCardSpawnsItsMonstersOnTheCaster()
{
await new SummonService(_npcMonsters, _random.Object).SummonAsync(Pod(),
new[] { new BCardDto { Type = (byte)BCardType.CardType.Summons, SubType = 21, FirstData = 3, SecondData = PiiVnum } });

var summoned = _map.EnumerateMonsters().Where(m => m.NpcMonster?.NpcMonsterVNum == PiiVnum).ToList();
Assert.AreEqual(3, summoned.Count);
Assert.IsTrue(summoned.All(m => m.PositionX == 4 && m.PositionY == 2));
}

[TestMethod]
public async Task OtherDeathCardsSummonNothing()
{
Expand All @@ -83,7 +94,7 @@ public async Task OtherDeathCardsSummonNothing()
Assert.AreEqual(1, _map.EnumerateMonsters().Count());
}

private SummonOnDeathHandler Handler() => new(_catalog.Object, _npcMonsters, _random.Object);
private SummonOnDeathHandler Handler() => new(_catalog.Object, new SummonService(_npcMonsters, _random.Object));

private MonsterComponentBundle Pod() => _map.EnumerateMonsters().Single(m => m.NpcMonster?.NpcMonsterVNum == PodVnum);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ public async Task SetupAsync()
new Mock<NosCore.GameObject.Services.BattleService.IBuffService>().Object,
new NosCore.GameObject.Services.BattleService.SkillCastService(NodaTime.SystemClock.Instance, new Mock<NosCore.GameObject.Services.EquipmentService.IEquipmentStatsService>().Object, new Mock<NosCore.GameObject.Services.BattleService.IBuffService>().Object),
new Mock<NosCore.GameObject.Services.BattleService.ISkillComboService>().Object,
new Mock<ISummonService>().Object,
NullLogger<GameObject.Services.BattleService.BattleService>.Instance, new Mock<ILogLanguageLocalizer<LogLanguageKey>>().Object);
_origin = new FakeEntity { Hp = 100, VisualId = 1 };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ public async Task ACastSkillIsReadyAgainOnceItsCooldownHasRunOut()
new Mock<NosCore.GameObject.Services.BattleService.IBuffService>().Object,
new NosCore.GameObject.Services.BattleService.SkillCastService(clock, new Mock<NosCore.GameObject.Services.EquipmentService.IEquipmentStatsService>().Object, World.Create<BuffService>()),
new Mock<NosCore.GameObject.Services.BattleService.ISkillComboService>().Object,
new Mock<ISummonService>().Object,
NullLogger<GameObject.Services.BattleService.BattleService>.Instance, new Mock<ILogLanguageLocalizer<LogLanguageKey>>().Object);

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 @@ -38,6 +38,7 @@ public class BattleServiceTests
private Mock<IMessageBus> _bus;
private Mock<ICastDelayService> _castDelay;
private Mock<IBuffService> _buffs;
private Mock<ISummonService> _summons;
private GameObject.Services.BattleService.BattleService _service;

[TestInitialize]
Expand All @@ -50,6 +51,7 @@ public void Setup()
_castDelay = new Mock<ICastDelayService>();
_castDelay.Setup(d => d.WaitAsync(It.IsAny<NodaTime.Duration>())).Returns(Task.CompletedTask);
_buffs = new Mock<IBuffService>();
_summons = new Mock<ISummonService>();
_service = new GameObject.Services.BattleService.BattleService(
_skillResolver.Object,
_targetResolver.Object,
Expand All @@ -62,6 +64,7 @@ public void Setup()
_buffs.Object,
new NosCore.GameObject.Services.BattleService.SkillCastService(NodaTime.SystemClock.Instance, new Mock<NosCore.GameObject.Services.EquipmentService.IEquipmentStatsService>().Object, new Mock<NosCore.GameObject.Services.BattleService.IBuffService>().Object),
new Mock<NosCore.GameObject.Services.BattleService.ISkillComboService>().Object,
_summons.Object,
NullLogger<NosCore.GameObject.Services.BattleService.BattleService>.Instance, new Mock<ILogLanguageLocalizer<LogLanguageKey>>().Object);
}

Expand All @@ -82,6 +85,23 @@ public async Task ASkillWithACastTimeHitsOnlyOnceTheCastEnds()
_hitQueue.Verify(q => q.EnqueueAsync(It.IsAny<HitRequest>()), Times.Once);
}

[TestMethod]
public async Task ACastSummonsItsAddsOnlyAfterItsHitsLanded()
{
var origin = new FakeEntity { Hp = 100 };
var target = new FakeEntity { Hp = 100, VisualType = VisualType.Monster };
var skill = MakeSkill(TargetHitType.SingleTargetHit);
SetupLanding(origin, target, skill);
var order = new List<string>();
_hitQueue.Setup(q => q.EnqueueAsync(It.IsAny<HitRequest>())).Callback(() => order.Add("hit"))
.ReturnsAsync(new HitOutcome(HitStatus.Landed, 50, SuPacketHitMode.SuccessAttack, false));
_summons.Setup(s => s.SummonAsync(origin, skill.BCards)).Callback(() => order.Add("summon")).Returns(Task.CompletedTask);

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

CollectionAssert.AreEqual(new[] { "hit", "summon" }, order);
}

[TestMethod]
public async Task ACastWhoseTargetDiesMeanwhileLandsNothing()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ public async Task SetupAsync()
_buffService.Object,
new SkillCastService(NodaTime.SystemClock.Instance, new Mock<GameObject.Services.EquipmentService.IEquipmentStatsService> { DefaultValue = DefaultValue.Empty }.Object, _buffService.Object),
new Mock<NosCore.GameObject.Services.BattleService.ISkillComboService>().Object,
new Mock<ISummonService>().Object,
NullLogger<GameObject.Services.BattleService.BattleService>.Instance, new Mock<ILogLanguageLocalizer<LogLanguageKey>>().Object);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ public async Task SetupAsync()
buffService.Object,
new SkillCastService(NodaTime.SystemClock.Instance, new Mock<GameObject.Services.EquipmentService.IEquipmentStatsService> { DefaultValue = DefaultValue.Empty }.Object, buffService.Object),
new SkillComboService(Combos),
new Mock<ISummonService>().Object,
NullLogger<GameObject.Services.BattleService.BattleService>.Instance, new Mock<ILogLanguageLocalizer<LogLanguageKey>>().Object);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,19 @@ public void Setup()
private static async Task<PlayerComponentBundle> NewCharacterAsync() =>
(await (await TestWorld.CreateAsync()).CreateSessionAsync()).Character;

[TestMethod]
public void AMonstersBasicAttackIsNotItsSkillThatSharesCastIdZero()
{
var skills = new Dictionary<short, SkillDto>(_skills) { [300] = new SkillDto { SkillVNum = 300, CastId = 0, Cooldown = 400, SkillType = 1 } };
var catalog = new NpcCombatCatalog(new() { new NpcMonsterSkillDto { NpcMonsterVNum = 111, SkillVNum = 300, Rate = 100 } }, new(), new());
var monster = new Mock<INonPlayableEntity>();
monster.Setup(m => m.NpcMonster).Returns(new NpcMonsterDto { NpcMonsterVNum = 111, BasicCooldown = 20 });
var resolver = new SkillResolver(skills, catalog);

Assert.AreEqual((short?)300, resolver.Resolve(monster.Object, 0)?.SkillVnum);
Assert.AreEqual((short?)0, resolver.ResolveBasic(monster.Object)?.SkillVnum);
}

[TestMethod]
public void UnknownCasterReturnsNull()
{
Expand Down
Loading