4 #include "RandomWalk.hpp"
5 #include "../world/BlockType.hpp"
6 #include "../world/BlockTypeRegistry.hpp"
7 #include "../world/Entity.hpp"
8 #include "../world/World.hpp"
13 Spawner::Spawner(World &world)
17 , despawn_range(128 * 128)
18 , spawn_distance(16 * 16)
22 Spawn(world.Player().ChunkCoords(), { 0.5f, 0.5f, 0.5f });
26 for (auto &ctrl : controllers) {
32 void Spawner::Update(int dt) {
38 for (auto &ctrl : controllers) {
44 void Spawner::CheckDespawn() noexcept {
45 const Entity &reference = world.Player();
46 for (auto iter = controllers.begin(), end = controllers.end(); iter != end;) {
47 Entity &e = (*iter)->Controlled();
48 glm::vec3 diff(reference.AbsoluteDifference(e));
49 if (dot(diff, diff) > despawn_range) {
52 iter = controllers.erase(iter);
59 void Spawner::TrySpawn() {
60 if (controllers.size() >= max_entities) return;
63 (rand() % (chunk_range * 2 + 1)) - chunk_range,
64 (rand() % (chunk_range * 2 + 1)) - chunk_range,
65 (rand() % (chunk_range * 2 + 1)) - chunk_range
69 rand() % Chunk::width,
70 rand() % Chunk::height,
76 glm::vec3 diff(glm::vec3(chunk * Chunk::Extent() - pos) + world.Player().Position());
77 float dist = dot(diff, diff);
78 if (dist > despawn_range || dist < spawn_distance) {
83 // TODO: avoid force load, abort spawn if chunk unavailble
84 Chunk &tgt_chunk = world.Next(world.PlayerChunk(), chunk);
85 // TODO: don't use visibility for spawn check
86 // also, check for more than one block space
87 if (tgt_chunk.Type(tgt_chunk.BlockAt(pos)).visible) {
91 Spawn(world.Player().ChunkCoords() + chunk, glm::vec3(pos) + glm::vec3(0.5f));
94 void Spawner::Spawn(const glm::ivec3 &chunk, const glm::vec3 &pos) {
95 glm::vec3 color(rand() % 6, rand() % 6, rand() % 6);
96 color = color * 0.15f + 0.25f;
98 glm::vec3 rot(0.000001f);
99 rot.x *= (rand() % 1024);
100 rot.y *= (rand() % 1024);
101 rot.z *= (rand() % 1024);
103 Entity &e = world.AddEntity();
105 e.Position(chunk, pos);
106 e.Bounds({ { -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f } });
107 e.WorldCollidable(true);
108 e.SetShape(world.BlockTypes()[1].shape, color, 2);
109 e.AngularVelocity(rot);
112 ctrl = new RandomWalk(e);
114 ctrl = new Chaser(world, e, world.Player());
116 controllers.emplace_back(ctrl);