4 #include "RandomWalk.hpp"
5 #include "../model/CompositeModel.hpp"
6 #include "../model/Skeletons.hpp"
7 #include "../world/BlockLookup.hpp"
8 #include "../world/BlockType.hpp"
9 #include "../world/Entity.hpp"
10 #include "../world/World.hpp"
15 Spawner::Spawner(World &world, Skeletons &skeletons, std::uint64_t seed)
17 , skeletons(skeletons)
21 , despawn_range(128 * 128)
22 , spawn_distance(16 * 16)
29 for (auto &ctrl : controllers) {
35 void Spawner::Update(int dt) {
41 for (auto &ctrl : controllers) {
47 void Spawner::CheckDespawn() noexcept {
48 const auto &refs = world.Players();
49 for (auto iter = controllers.begin(), end = controllers.end(); iter != end;) {
50 Entity &e = (*iter)->Controlled();
53 iter = controllers.erase(iter);
57 for (const Entity *ref : refs) {
58 glm::vec3 diff(ref->AbsoluteDifference(e));
59 if (dot(diff, diff) < despawn_range) {
67 iter = controllers.erase(iter);
74 void Spawner::TrySpawn() {
75 if (controllers.size() >= max_entities) return;
77 // select random player to punish
78 auto &players = world.Players();
79 if (players.size() == 0) return;
80 Entity &player = *players[random.Next<unsigned short>() % players.size()];
83 (random.Next<unsigned char>() % (chunk_range * 2 + 1)) - chunk_range,
84 (random.Next<unsigned char>() % (chunk_range * 2 + 1)) - chunk_range,
85 (random.Next<unsigned char>() % (chunk_range * 2 + 1)) - chunk_range
89 random.Next<unsigned char>() % Chunk::width,
90 random.Next<unsigned char>() % Chunk::height,
91 random.Next<unsigned char>() % Chunk::depth
95 glm::vec3 diff(glm::vec3(chunk * Chunk::Extent() - pos) + player.Position());
96 float dist = dot(diff, diff);
97 if (dist > despawn_range || dist < spawn_distance) {
101 // check if the spawn block and the one above it are loaded and inhabitable
102 BlockLookup spawn_block(
103 world.Loader().Loaded(player.ChunkCoords()),
104 chunk * Chunk::Extent() + pos);
105 if (!spawn_block || spawn_block.GetType().collide_block) {
109 BlockLookup head_block(spawn_block.Next(Block::FACE_UP));
110 if (!head_block || head_block.GetType().collide_block) {
114 Spawn(player, player.ChunkCoords() + chunk, glm::vec3(pos) + glm::vec3(0.5f));
117 void Spawner::Spawn(Entity &reference, const glm::ivec3 &chunk, const glm::vec3 &pos) {
118 glm::vec3 rot(0.000001f);
119 rot.x *= (random.Next<unsigned short>() % 1024);
120 rot.y *= (random.Next<unsigned short>() % 1024);
121 rot.z *= (random.Next<unsigned short>() % 1024);
123 Entity &e = world.AddEntity();
125 e.Position(chunk, pos);
126 e.Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
127 e.WorldCollidable(true);
128 skeletons[random.Next<unsigned char>() % skeletons.Size()].Instantiate(e.GetModel());
129 e.AngularVelocity(rot);
132 ctrl = new RandomWalk(e, random.Next<std::uint64_t>());
134 ctrl = new Chaser(world, e, reference);
136 controllers.emplace_back(ctrl);