Веб-сайт самохостера Lotigara

summaryrefslogtreecommitdiff
path: root/source/game/items/StarTools.cpp
blob: 6c84c1233326466f40088bfd55374a4b86b78f24 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
#include "StarTools.hpp"
#include "StarRoot.hpp"
#include "StarMaterialDatabase.hpp"
#include "StarJsonExtra.hpp"
#include "StarAssets.hpp"
#include "StarWiring.hpp"
#include "StarWorld.hpp"
#include "StarWorldClient.hpp"
#include "StarParticleDatabase.hpp"

namespace Star {

MiningTool::MiningTool(Json const& config, String const& directory, Json const& parameters)
  : Item(config, directory, parameters), SwingableItem(config) {
  auto assets = Root::singleton().assets();

  m_image = AssetPath::relativeTo(directory, instanceValue("image").toString());
  m_frames = instanceValue("frames", 1).toInt();
  m_frameCycle = instanceValue("animationCycle", 1.0f).toFloat();
  m_frameTiming = 0;
  for (size_t i = 0; i < (size_t)m_frames; i++)
    m_animationFrame.append(m_image.replace("{frame}", toString(i)));
  m_idleFrame = m_image.replace("{frame}", "idle");
  m_handPosition = jsonToVec2F(instanceValue("handPosition"));
  m_blockRadius = instanceValue("blockRadius").toFloat();
  m_altBlockRadius = instanceValue("altBlockRadius").toFloat();
  m_strikeSounds = jsonToStringList(instanceValue("strikeSounds"));
  m_breakSound = instanceValue("breakSound", "").toString();
  m_pointable = instanceValue("pointable", false).toBool();

  m_toolVolume = assets->json("/sfx.config:miningToolVolume").toFloat();
  m_blockVolume = assets->json("/sfx.config:miningBlockVolume").toFloat();
}

ItemPtr MiningTool::clone() const {
  return make_shared<MiningTool>(*this);
}

List<Drawable> MiningTool::drawables() const {
  if (m_frameTiming == 0) {
    return {Drawable::makeImage(m_idleFrame, 1.0f / TilePixels, true, -handPosition() / TilePixels)};
  } else {
    int frame = std::max(0, std::min(m_frames - 1, (int)std::floor((m_frameTiming / m_frameCycle) * m_frames)));
    return {Drawable::makeImage(m_animationFrame[frame], 1.0f / TilePixels, true, -handPosition() / TilePixels)};
  }
}

Vec2F MiningTool::handPosition() const {
  return m_handPosition;
}

void MiningTool::fire(FireMode mode, bool shifting, bool edgeTriggered) {
  if (!ready())
    return;

  auto materialDatabase = Root::singleton().materialDatabase();

  if (initialized()) {
    bool used = false;
    int radius = !shifting ? m_blockRadius : m_altBlockRadius;
    String blockSound;
    List<Vec2I> brushArea;

    auto layer = (mode == FireMode::Primary ? TileLayer::Foreground : TileLayer::Background);
    if (owner()->isAdmin() || owner()->inToolRange()) {
      brushArea = tileAreaBrush(radius, owner()->aimPosition(), true);
      for (auto pos : brushArea) {
        blockSound = materialDatabase->miningSound(world()->material(pos, layer), world()->mod(pos, layer));
        if (!blockSound.empty())
          break;
      }
      if (blockSound.empty()) {
        for (auto pos : brushArea) {
          blockSound = materialDatabase->footstepSound(world()->material(pos, layer), world()->mod(pos, layer));
          if (!blockSound.empty()
              && blockSound != Root::singleton().assets()->json("/client.config:defaultFootstepSound").toString())
            break;
        }
      }

      TileDamage damage;
      damage.type = TileDamageTypeNames.getLeft(instanceValue("tileDamageType", "blockish").toString());

      if (durabilityStatus() == 0)
        damage.amount = instanceValue("tileDamageBlunted", 0.1f).toFloat();
      else
        damage.amount = instanceValue("tileDamage", 1.0f).toFloat();

      damage.harvestLevel = instanceValue("harvestLevel", 1).toUInt();

      auto damageResult = world()->damageTiles(brushArea, layer, owner()->position(), damage, owner()->entityId());

      if (damageResult != TileDamageResult::None) {
        used = true;
        if (!owner()->isAdmin())
          changeDurability(instanceValue("durabilityPerUse", 1.0f).toFloat());
      }

      if (damageResult == TileDamageResult::Protected) {
        blockSound = Root::singleton().assets()->json("/client.config:defaultDingSound").toString();
      }
    }

    if (used) {
      owner()->addSound(Random::randValueFrom(m_strikeSounds), m_toolVolume);
      owner()->addSound(blockSound, m_blockVolume);
      List<Particle> miningParticles;
      for (auto pos : brushArea) {
        if (auto miningParticleConfig = materialDatabase->miningParticle(world()->material(pos, layer), world()->mod(pos, layer))) {
          auto miningParticle = miningParticleConfig->instance();
          miningParticle.position += (Vec2F)pos;
          miningParticles.append(miningParticle);
        }
      }
      owner()->addParticles(miningParticles);
      SwingableItem::fire(mode, shifting, edgeTriggered);
    }
  }
}

void MiningTool::update(float dt, FireMode mode, bool shifting, HashSet<MoveControlType> const& moves) {
  SwingableItem::update(dt, mode, shifting, moves);

  if (!ready() && !coolingDown())
    m_frameTiming = std::fmod((m_frameTiming + dt), m_frameCycle);
  else
    m_frameTiming = 0;
}

float MiningTool::durabilityStatus() {
  return clamp(
      1.0f - instanceValue("durabilityHit", 0.0f).toFloat() / instanceValue("durability").toFloat(), 0.0f, 1.0f);
}

float MiningTool::getAngle(float aimAngle) {
  if ((!ready() && !coolingDown()) || !m_pointable)
    return SwingableItem::getAngle(aimAngle);
  return aimAngle;
}

void MiningTool::changeDurability(float amount) {
  setInstanceValue("durabilityHit", clamp(instanceValue("durabilityHit", 0.0f).toFloat() + amount, 0.0f, instanceValue("durability").toFloat()));
  if (durabilityStatus() == 0.0f && !instanceValue("canBeRepaired", false).toBool()) {
    owner()->addSound(m_breakSound);
    consume(1);
  }
}

HarvestingTool::HarvestingTool(Json const& config, String const& directory, Json const& parameters)
  : Item(config, directory, parameters), SwingableItem(config) {
  auto assets = Root::singleton().assets();

  m_image = AssetPath::relativeTo(directory, instanceValue("image").toString());
  m_frames = instanceValue("frames", 1).toInt();
  m_frameCycle = instanceValue("animationCycle", 1.0f).toFloat();
  for (size_t i = 0; i < (size_t)m_frames; i++)
    m_animationFrame.append(m_image.replace("{frame}", toString(i)));
  m_idleFrame = m_image.replace("{frame}", "idle");

  m_handPosition = jsonToVec2F(instanceValue("handPosition"));
  m_strikeSounds = jsonToStringList(instanceValue("strikeSounds"));
  m_toolVolume = assets->json("/sfx.config:harvestToolVolume").toFloat();
  m_harvestPower = instanceValue("harvestPower", 1.0f).toFloat();
  m_frameTiming = 0;
}

ItemPtr HarvestingTool::clone() const {
  return make_shared<HarvestingTool>(*this);
}

List<Drawable> HarvestingTool::drawables() const {
  if (m_frameTiming == 0)
    return {Drawable::makeImage(m_idleFrame, 1.0f / TilePixels, true, -handPosition() / TilePixels)};
  else {
    int frame = std::max(0, std::min(m_frames - 1, (int)std::floor((m_frameTiming / m_frameCycle) * m_frames)));
    return {Drawable::makeImage(m_animationFrame[frame], 1.0f / TilePixels, true, -handPosition() / TilePixels)};
  }
}

Vec2F HarvestingTool::handPosition() const {
  return m_handPosition;
}

void HarvestingTool::fire(FireMode mode, bool shifting, bool edgeTriggered) {
  if (!ready())
    return;

  if (owner()) {
    bool used = false;

    if (owner()->isAdmin() || owner()->inToolRange()) {
      auto layer = (mode == FireMode::Primary ? TileLayer::Foreground : TileLayer::Background);
      used = world()->damageTile(Vec2I::floor(owner()->aimPosition()), layer, owner()->position(), {TileDamageType::Plantish, m_harvestPower}) != TileDamageResult::None;
    }

    if (used) {
      owner()->addSound(Random::randValueFrom(m_strikeSounds), m_toolVolume);
      SwingableItem::fire(mode, shifting, edgeTriggered);
    }
  }
}

void HarvestingTool::update(float dt, FireMode fireMode, bool shifting, HashSet<MoveControlType> const& moves) {
  SwingableItem::update(dt, fireMode, shifting, moves);

  if (!ready() && !coolingDown())
    m_frameTiming = std::fmod((m_frameTiming + dt), m_frameCycle);
  else
    m_frameTiming = 0;
}

float HarvestingTool::getAngle(float aimAngle) {
  if (!ready() && !coolingDown())
    return SwingableItem::getAngle(aimAngle);
  return aimAngle;
}

Flashlight::Flashlight(Json const& config, String const& directory, Json const& parameters)
  : Item(config, directory, parameters) {
  m_image = AssetPath::relativeTo(directory, instanceValue("image").toString());
  m_handPosition = jsonToVec2F(instanceValue("handPosition"));
  m_lightPosition = jsonToVec2F(instanceValue("lightPosition"));
  m_lightColor = jsonToColor(instanceValue("lightColor"));
  m_beamWidth = instanceValue("beamLevel").toFloat();
  m_ambientFactor = instanceValue("beamAmbience").toFloat();
}

ItemPtr Flashlight::clone() const {
  return make_shared<Flashlight>(*this);
}

List<Drawable> Flashlight::drawables() const {
  return {Drawable::makeImage(m_image, 1.0f / TilePixels, true, -m_handPosition / TilePixels)};
}

List<LightSource> Flashlight::lightSources() const {
  if (!initialized())
    return {};

  float angle = world()->geometry().diff(owner()->aimPosition(), owner()->position()).angle();
  LightSource lightSource;
  lightSource.type = LightType::Point;
  lightSource.position = owner()->position() + owner()->handPosition(hand(), (m_lightPosition - m_handPosition) / TilePixels);
  lightSource.color = m_lightColor.toRgbF();
  lightSource.pointBeam = m_beamWidth;
  lightSource.beamAngle = angle;
  lightSource.beamAmbience = m_ambientFactor;
  return {std::move(lightSource)};
}

WireTool::WireTool(Json const& config, String const& directory, Json const& parameters)
  : Item(config, directory, parameters), FireableItem(config), BeamItem(config.setAll(parameters.toObject())) {
  auto assets = Root::singleton().assets();

  m_handPosition = jsonToVec2F(instanceValue("handPosition"));
  m_strikeSounds = jsonToStringList(instanceValue("strikeSounds"));
  m_toolVolume = assets->json("/sfx.config:miningToolVolume").toFloat();
  m_wireConnector = 0;
  m_endType = EndType::Wire;
}

ItemPtr WireTool::clone() const {
  return make_shared<WireTool>(*this);
}

void WireTool::init(ToolUserEntity* owner, ToolHand hand) {
  FireableItem::init(owner, hand);
  BeamItem::init(owner, hand);
  m_wireConnector = 0;
}

void WireTool::update(float dt, FireMode fireMode, bool shifting, HashSet<MoveControlType> const& moves) {
  FireableItem::update(dt, fireMode, shifting, moves);
  BeamItem::update(dt, fireMode, shifting, moves);
}

List<Drawable> WireTool::drawables() const {
  return BeamItem::drawables();
}

List<Drawable> WireTool::nonRotatedDrawables() const {
  if (m_wireConnector && m_wireConnector->connecting())
    return BeamItem::nonRotatedDrawables();
  return {};
}

void WireTool::setEnd(EndType) {
  m_endType = EndType::Wire;
}

Vec2F WireTool::handPosition() const {
  return m_handPosition;
}

void WireTool::fire(FireMode mode, bool shifting, bool edgeTriggered) {
  if (!ready())
    return;

  auto ownerp = owner();
  auto worldp = world();

  if (ownerp && worldp && m_wireConnector) {
    Vec2F pos(ownerp->aimPosition());
    if (ownerp->isAdmin() || ownerp->inToolRange()) {
      auto swingResult = m_wireConnector->swing(worldp->geometry(), pos, mode);
      if (swingResult == WireConnector::Connect) {
        ownerp->addSound(Random::randValueFrom(m_strikeSounds), m_toolVolume);
        FireableItem::fire(mode, shifting, edgeTriggered);
      } else if (swingResult == WireConnector::Mismatch || swingResult == WireConnector::Protected) {
        auto wireErrorSound = Root::singleton().assets()->json("/client.config:wireFailSound").toString();
        ownerp->addSound(wireErrorSound, m_toolVolume);
        FireableItem::fire(mode, shifting, edgeTriggered);
      }
    }
  }
}

float WireTool::getAngle(float aimAngle) {
  return BeamItem::getAngle(aimAngle);
}

void WireTool::setConnector(WireConnector* connector) {
  m_wireConnector = connector;
}

BeamMiningTool::BeamMiningTool(Json const& config, String const& directory, Json const& parameters)
  : Item(config, directory, parameters), FireableItem(config), BeamItem(config.setAll(parameters.toObject())) {
  auto assets = Root::singleton().assets();

  m_blockRadius = instanceValue("blockRadius").toFloat();
  m_altBlockRadius = instanceValue("altBlockRadius").toFloat();
  m_tileDamage = instanceValue("tileDamage", 1.0f).toFloat();
  m_harvestLevel = instanceValue("harvestLevel", 1).toUInt();
  m_canCollectLiquid = instanceValue("canCollectLiquid", false).toBool();
  m_strikeSounds = jsonToStringList(instanceValue("strikeSounds"));
  m_toolVolume = assets->json("/sfx.config:miningToolVolume").toFloat();
  m_blockVolume = assets->json("/sfx.config:miningBlockVolume").toFloat();
  m_endType = EndType::Object;

  if (auto jRate = instanceValue("scaleRate")) {
    if (jRate.canConvert(Json::Type::Float)) {
      float rate = jRate.toFloat();
      m_tileDamage /= rate;
      m_cooldownTime /= rate;
    }
  }

  m_inhandStatusEffects = instanceValue("inhandStatusEffects", JsonArray()).toArray().transformed(jsonToPersistentStatusEffect);
}

ItemPtr BeamMiningTool::clone() const {
  return make_shared<BeamMiningTool>(*this);
}

List<Drawable> BeamMiningTool::drawables() const {
  return BeamItem::drawables();
}

void BeamMiningTool::setEnd(EndType) {
  m_endType = EndType::Object;
}

List<PreviewTile> BeamMiningTool::previewTiles(bool shifting) const {
  List<PreviewTile> result;
  auto ownerp = owner();
  auto worldp = world();

  if (ownerp && worldp) {
    if (ownerp->isAdmin() || ownerp->inToolRange()) {
      Color lightColor = ownerp->favoriteColor();
      if (!ready())
        lightColor *= Color::rgbaf(0.75f, 0.75f, 0.75f, 1.0f);
      Vec3B light = lightColor.toRgb();
      int radius = !shifting ? m_blockRadius : m_altBlockRadius;
      for (auto pos : tileAreaBrush(radius, ownerp->aimPosition(), true)) {
        if (worldp->tileIsOccupied(pos, TileLayer::Foreground, true)) {
          result.append({pos, true, light, true});
        } else if (worldp->tileIsOccupied(pos, TileLayer::Background, true)) {
          result.append({pos, false, light, true});
        }
      }
    }
  }
  return result;
}

void BeamMiningTool::init(ToolUserEntity* owner, ToolHand hand) {
  FireableItem::init(owner, hand);
  BeamItem::init(owner, hand);
}

void BeamMiningTool::update(float dt, FireMode fireMode, bool shifting, HashSet<MoveControlType> const& moves) {
  FireableItem::update(dt, fireMode, shifting, moves);
  BeamItem::update(dt, fireMode, shifting, moves);
}

List<PersistentStatusEffect> BeamMiningTool::statusEffects() const {
  return m_inhandStatusEffects;
}

List<Drawable> BeamMiningTool::nonRotatedDrawables() const {
  if (!ready() && !coolingDown())
    return BeamItem::nonRotatedDrawables();
  return {};
}

void BeamMiningTool::fire(FireMode mode, bool shifting, bool edgeTriggered) {
  if (!ready())
    return;

  auto materialDatabase = Root::singleton().materialDatabase();

  auto worldp = world();
  auto ownerp = owner();
  if (ownerp && worldp) {
    bool used = false;
    int radius = !shifting ? m_blockRadius : m_altBlockRadius;
    String blockSound;
    List<Vec2I> brushArea;

    auto layer = (mode == FireMode::Primary ? TileLayer::Foreground : TileLayer::Background);
    if (ownerp->isAdmin() || ownerp->inToolRange()) {
      brushArea = tileAreaBrush(radius, ownerp->aimPosition(), true);
      auto aimPosition = Vec2I(ownerp->aimPosition());

      for (auto pos : brushArea) {
        blockSound = materialDatabase->miningSound(worldp->material(pos, layer), worldp->mod(pos, layer));
        if (!blockSound.empty())
          break;
      }
      if (blockSound.empty()) {
        for (auto pos : brushArea) {
          blockSound = materialDatabase->footstepSound(worldp->material(pos, layer), worldp->mod(pos, layer));
          if (!blockSound.empty()
              && blockSound != Root::singleton().assets()->json("/client.config:defaultFootstepSound").toString())
            break;
        }
      }

      auto damageResult = worldp->damageTiles(List<Vec2I>{brushArea}, layer, ownerp->position(), {TileDamageType::Beamish, m_tileDamage, m_harvestLevel}, ownerp->entityId());
      used = damageResult != TileDamageResult::None;

      if (damageResult == TileDamageResult::Protected) {
        blockSound = Root::singleton().assets()->json("/client.config:defaultDingSound").toString();
      }

      if (!used && m_canCollectLiquid && layer == TileLayer::Foreground && worldp->material(aimPosition, TileLayer::Foreground) == EmptyMaterialId) {
        auto targetLiquid = worldp->liquidLevel(aimPosition).liquid;
        List<Vec2I> drainTiles;
        float totalLiquid = 0;
        for (auto pos : brushArea) {
          if (worldp->isTileProtected(pos))
            continue;

          auto liquid = worldp->liquidLevel(pos);
          if (liquid.liquid != EmptyLiquidId) {
            if (targetLiquid == EmptyLiquidId)
              targetLiquid = liquid.liquid;

            if (liquid.liquid == targetLiquid) {
              totalLiquid += liquid.level;
              drainTiles.append(pos);
            }
          }
        }

        float bucketSize = Root::singleton().assets()->json("/items/defaultParameters.config:liquidItems.bucketSize").toUInt();
        if (totalLiquid >= bucketSize) {
          if (auto clientWorld = as<WorldClient>(worldp))
            clientWorld->collectLiquid(drainTiles, targetLiquid);

          blockSound = Root::singleton().assets()->json("/items/defaultParameters.config:liquidBlockSound").toString();

          used = true;
        }
      }
    }

    if (used) {
      ownerp->addSound(Random::randValueFrom(m_strikeSounds), m_toolVolume);
      ownerp->addSound(blockSound, m_blockVolume);
      List<Particle> miningParticles;
      for (auto pos : brushArea) {
        if (auto miningParticleConfig = materialDatabase->miningParticle(worldp->material(pos, layer), worldp->mod(pos, layer))) {
          auto miningParticle = miningParticleConfig->instance();
          miningParticle.position += (Vec2F)pos;
          miningParticles.append(miningParticle);
        }
      }
      ownerp->addParticles(miningParticles);
      FireableItem::fire(mode, shifting, edgeTriggered);
    }
  }
}

float BeamMiningTool::getAngle(float angle) {
  return BeamItem::getAngle(angle);
}

TillingTool::TillingTool(Json const& config, String const& directory, Json const& parameters)
  : Item(config, directory, parameters), SwingableItem(config) {
  auto assets = Root::singleton().assets();

  m_image = AssetPath::relativeTo(directory, instanceValue("image").toString());
  m_frames = instanceValue("frames", 1).toInt();
  m_frameCycle = instanceValue("animationCycle", 1.0f).toFloat();
  for (size_t i = 0; i < (size_t)m_frames; i++)
    m_animationFrame.append(m_image.replace("{frame}", toString(i)));
  m_idleFrame = m_image.replace("{frame}", "idle");

  m_handPosition = jsonToVec2F(instanceValue("handPosition"));
  m_strikeSounds = jsonToStringList(instanceValue("strikeSounds"));
  m_toolVolume = assets->json("/sfx.config:harvestToolVolume").toFloat();
  m_frameTiming = 0;
}

ItemPtr TillingTool::clone() const {
  return make_shared<TillingTool>(*this);
}

List<Drawable> TillingTool::drawables() const {
  if (m_frameTiming == 0)
    return {Drawable::makeImage(m_idleFrame, 1.0f / TilePixels, true, -handPosition() / TilePixels)};
  else {
    int frame = std::max(0, std::min(m_frames - 1, (int)std::floor((m_frameTiming / m_frameCycle) * m_frames)));
    return {Drawable::makeImage(m_animationFrame[frame], 1.0f / TilePixels, true, -handPosition() / TilePixels)};
  }
}

Vec2F TillingTool::handPosition() const {
  return m_handPosition;
}

void TillingTool::fire(FireMode mode, bool shifting, bool edgeTriggered) {
  if (!ready())
    return;

  auto strikeSound = Random::randValueFrom(m_strikeSounds);

  if (owner() && world()) {
    auto materialDatabase = Root::singleton().materialDatabase();
    Vec2I pos(owner()->aimPosition().floor());

    if (world()->material(pos + Vec2I(0, 1), TileLayer::Foreground) != EmptyMaterialId)
      return;

    bool used = false;
    for (auto layer : {TileLayer::Foreground, TileLayer::Background}) {
      if (world()->material(pos, layer) == EmptyMaterialId)
        pos = pos - Vec2I(0, 1);

      if ((layer == TileLayer::Background)
          && world()->material(pos + Vec2I(0, 1), TileLayer::Background) != EmptyMaterialId)
        continue;

      if (owner()->isAdmin() || owner()->inToolRange()) {
        auto currentMod = world()->mod(pos, layer);
        auto material = world()->material(pos, layer);
        auto tilledMod = materialDatabase->tilledModFor(material);

        if (tilledMod != NoModId && currentMod == NoModId) {
          if (world()->modifyTile(pos, PlaceMod{layer, tilledMod, MaterialHue()}, true))
            used = true;
        } else if (currentMod != tilledMod) {
          auto damageResult = world()->damageTile(pos, layer, owner()->position(), {TileDamageType::Tilling, 1.0f});
          used = damageResult != TileDamageResult::None;
          if (damageResult == TileDamageResult::Protected) {
            strikeSound = Root::singleton().assets()->json("/client.config:defaultDingSound").toString();
          }
        }
      }
    }

    if (used) {
      owner()->addSound(strikeSound, m_toolVolume);
      SwingableItem::fire(mode, shifting, edgeTriggered);
    }
  }
}

void TillingTool::update(float dt, FireMode fireMode, bool shifting, HashSet<MoveControlType> const& moves) {
  SwingableItem::update(dt, fireMode, shifting, moves);

  if (!ready() && !coolingDown())
    m_frameTiming = std::fmod((m_frameTiming + dt), m_frameCycle);
  else
    m_frameTiming = 0;
}

float TillingTool::getAngle(float aimAngle) {
  if (!ready() && !coolingDown())
    return SwingableItem::getAngle(aimAngle);
  return aimAngle;
}

PaintingBeamTool::PaintingBeamTool(Json const& config, String const& directory, Json const& parameters)
  : Item(config, directory, parameters), FireableItem(config), BeamItem(config) {
  auto assets = Root::singleton().assets();

  m_blockRadius = instanceValue("blockRadius").toFloat();
  m_altBlockRadius = instanceValue("altBlockRadius").toFloat();
  m_strikeSounds = jsonToStringList(instanceValue("strikeSounds"));
  m_toolVolume = assets->json("/sfx.config:miningToolVolume").toFloat();
  m_blockVolume = assets->json("/sfx.config:miningBlockVolume").toFloat();
  m_endType = EndType::Object;

  for (auto& color : instanceValue("colorNumbers").toArray())
    m_colors.append(jsonToColor(color));

  m_colorKeys = jsonToStringList(instanceValue("colorKeys"));

  m_colorIndex = instanceValue("colorIndex", 0).toInt();
  m_color = m_colors[m_colorIndex];
}

ItemPtr PaintingBeamTool::clone() const {
  return make_shared<PaintingBeamTool>(*this);
}

List<Drawable> PaintingBeamTool::drawables() const {
  auto result = BeamItem::drawables();
  for (auto& entry : result) {
    if (entry.isImage()) {
      auto& image = entry.imagePart().image;
      image.subPath = image.subPath.value("0") + m_colorKeys[m_colorIndex];
    }
  }
  return result;
}

void PaintingBeamTool::setEnd(EndType type) {
  _unused(type);
  m_endType = EndType::Object;
}

void PaintingBeamTool::update(float dt, FireMode fireMode, bool shifting, HashSet<MoveControlType> const& moves) {
  BeamItem::update(dt, fireMode, shifting, moves);
  FireableItem::update(dt, fireMode, shifting, moves);
}

List<PreviewTile> PaintingBeamTool::previewTiles(bool shifting) const {
  List<PreviewTile> result;
  auto ownerp = owner();
  auto worldp = world();
  if (ownerp && worldp) {
    Vec3B light = Color::White.toRgb();

    if (ownerp->isAdmin() || ownerp->inToolRange()) {
      int radius = !shifting ? m_blockRadius : m_altBlockRadius;

      for (auto pos : tileAreaBrush(radius, ownerp->aimPosition(), true)) {
        if (worldp->canModifyTile(pos, PlaceMaterialColor{TileLayer::Foreground, (MaterialColorVariant)m_colorIndex}, true)) {
          result.append({pos, true, NullMaterialId, MaterialHue(), false, light, true, (MaterialColorVariant)m_colorIndex});
        } else if (worldp->canModifyTile(pos, PlaceMaterialColor{TileLayer::Background, (MaterialColorVariant)m_colorIndex}, true)) {
          result.append({pos, false, NullMaterialId, MaterialHue(), false, light, true, (MaterialColorVariant)m_colorIndex});
        } else if (worldp->canModifyTile(pos, PlaceMaterialColor{TileLayer::Foreground, DefaultMaterialColorVariant}, true)) {
          result.append({pos, true, NullMaterialId, MaterialHue(), false, light, true, DefaultMaterialColorVariant});
        } else if (worldp->canModifyTile(pos, PlaceMaterialColor{TileLayer::Background, DefaultMaterialColorVariant}, true)) {
          result.append({pos, false, NullMaterialId, MaterialHue(), false, light, true, DefaultMaterialColorVariant});
        }
      }
    }
  }

  return result;
}

void PaintingBeamTool::init(ToolUserEntity* owner, ToolHand hand) {
  FireableItem::init(owner, hand);
  BeamItem::init(owner, hand);
  m_color = m_colors[m_colorIndex];
}

List<Drawable> PaintingBeamTool::nonRotatedDrawables() const {
  if (!coolingDown())
    return BeamItem::nonRotatedDrawables();
  return {};
}

void PaintingBeamTool::fire(FireMode mode, bool shifting, bool edgeTriggered) {
  if (!ready())
    return;

  if (mode == FireMode::Alt && edgeTriggered) {
    m_colorIndex = (m_colorIndex + 1) % m_colors.size();
    m_color = m_colors[m_colorIndex];
    setInstanceValue("colorIndex", m_colorIndex);
    return;
  }

  if (mode == FireMode::Primary) {
    auto worldp = world();
    auto ownerp = owner();
    if (ownerp && worldp) {
      bool used = false;
      int radius = !shifting ? m_blockRadius : m_altBlockRadius;

      if (ownerp->isAdmin() || ownerp->inToolRange()) {
        for (auto pos : tileAreaBrush(radius, ownerp->aimPosition(), true)) {
          TileModificationList modifications = {
            {pos, PlaceMaterialColor{TileLayer::Foreground, (MaterialColorVariant)m_colorIndex}},
            {pos, PlaceMaterialColor{TileLayer::Background, (MaterialColorVariant)m_colorIndex}}
          };
          auto failed = worldp->applyTileModifications(modifications, true);
          if (failed.count() < 2)
            used = true;
        }
      }

      if (used) {
        ownerp->addSound(Random::randValueFrom(m_strikeSounds), m_toolVolume);
        FireableItem::fire(mode, shifting, edgeTriggered);
      }
    }
  }
}

float PaintingBeamTool::getAngle(float angle) {
  return BeamItem::getAngle(angle);
}

}