Code cleanup and improvements

This commit is contained in:
Attila Uygun 2022-08-26 01:28:53 +02:00
parent 0bd3a1c607
commit 10e272fee1
14 changed files with 88 additions and 135 deletions

View File

@ -50,7 +50,6 @@ set(CMAKE_SHARED_LINKER_FLAGS
add_library(kaliber SHARED
../../../src/base/collusion_test.cc
../../../src/base/log.cc
../../../src/base/random.cc
../../../src/base/sinc_resampler.cc
../../../src/base/task_runner.cc
../../../src/base/thread_pool.cc

View File

@ -77,7 +77,6 @@ objs_from_src_in = $(call objs_from_src, $(shell find $(1) -name "*.cc" -o -name
ENGINE_SRC := \
$(SRC_ROOT)/base/collusion_test.cc \
$(SRC_ROOT)/base/log.cc \
$(SRC_ROOT)/base/random.cc \
$(SRC_ROOT)/base/sinc_resampler.cc \
$(SRC_ROOT)/base/task_runner.cc \
$(SRC_ROOT)/base/thread_pool.cc \

View File

@ -10,7 +10,6 @@ source_set("base") {
"log.h",
"mem.h",
"misc.h",
"random.cc",
"random.h",
"sinc_resampler.cc",
"sinc_resampler.h",

View File

@ -14,11 +14,6 @@ inline T Lerp(const T& a, const T& b, float t) {
return a + (b - a) * t;
}
template <>
inline int Lerp<int>(const int& a, const int& b, float t) {
return Round(a + (b - a) * t);
}
inline float SmoothStep(float t) {
return t * t * (3 - 2 * t);
}

View File

@ -1,37 +0,0 @@
#include "base/random.h"
#include <limits>
#include "base/interpolation.h"
#include "base/log.h"
namespace base {
Random::Random() {
std::random_device rd;
seed_ = rd();
DLOG << "Random seed: " << seed_;
Initialize();
}
Random::Random(unsigned seed) {
seed_ = seed;
Initialize();
}
Random::~Random() = default;
float Random::GetFloat() {
return real_distribution_(generator_);
}
int Random::Roll(int sides) {
return Lerp(1, sides, GetFloat());
}
void Random::Initialize() {
generator_ = std::mt19937(seed_);
real_distribution_ = std::uniform_real_distribution<float>(0, 1);
}
} // namespace base

View File

@ -3,30 +3,44 @@
#include <random>
#include "base/interpolation.h"
namespace base {
template <typename T>
class Random {
public:
Random();
Random(unsigned seed);
~Random();
Random() {
std::random_device rd;
seed_ = rd();
Initialize();
}
// Returns a random float between 0 and 1.
float GetFloat();
Random(unsigned seed) : seed_(seed) { Initialize(); }
~Random() = default;
// Returns a random between 0 and 1.
T Rand() { return real_distribution_(generator_); }
// Roll dice with the given number of sides.
int Roll(int sides);
int Roll(int sides) { return Lerp(1, sides + 1, Rand()); }
unsigned seed() const { return seed_; }
private:
unsigned seed_ = 0;
std::mt19937 generator_;
std::uniform_real_distribution<float> real_distribution_;
std::uniform_real_distribution<T> real_distribution_;
void Initialize();
void Initialize() {
generator_ = std::mt19937(seed_);
real_distribution_ = std::uniform_real_distribution<T>(0, 1);
}
};
using Randomf = Random<float>;
} // namespace base
#endif // BASE_RANDOM_H

View File

@ -436,7 +436,7 @@ void Demo::StartNextStage(bool boss) {
wave_score_ = 0;
}
Random& rnd = Engine::Get().GetRandomGenerator();
Randomf& rnd = Engine::Get().GetRandomGenerator();
int dominant_channel = rnd.Roll(3) - 1;
if (dominant_channel == last_dominant_channel_)
dominant_channel = (dominant_channel + 1) % 3;
@ -444,12 +444,12 @@ void Demo::StartNextStage(bool boss) {
float weights[3] = {0, 0, 0};
weights[dominant_channel] = 1;
Vector4f c = {Lerp(0.75f, 0.95f, rnd.GetFloat()) * weights[0],
Lerp(0.75f, 0.95f, rnd.GetFloat()) * weights[1],
Lerp(0.75f, 0.95f, rnd.GetFloat()) * weights[2], 1};
c += {Lerp(0.1f, 0.5f, rnd.GetFloat()) * (1 - weights[0]),
Lerp(0.1f, 0.5f, rnd.GetFloat()) * (1 - weights[1]),
Lerp(0.1f, 0.5f, rnd.GetFloat()) * (1 - weights[2]), 1};
Vector4f c = {Lerp(0.75f, 0.95f, rnd.Rand()) * weights[0],
Lerp(0.75f, 0.95f, rnd.Rand()) * weights[1],
Lerp(0.75f, 0.95f, rnd.Rand()) * weights[2], 1};
c += {Lerp(0.1f, 0.5f, rnd.Rand()) * (1 - weights[0]),
Lerp(0.1f, 0.5f, rnd.Rand()) * (1 - weights[1]),
Lerp(0.1f, 0.5f, rnd.Rand()) * (1 - weights[2]), 1};
sky_.SwitchColor(c);
++wave_;

View File

@ -70,7 +70,7 @@ void SetupFadeOutAnim(Animator& animator, float delay) {
float SnapSpawnPosX(int col) {
Vector2f s = eng::Engine::Get().GetScreenSize();
float offset = base::Lerp(s.x * -0.02f, s.x * 0.02f,
eng::Engine::Get().GetRandomGenerator().GetFloat());
eng::Engine::Get().GetRandomGenerator().Rand());
return (s.x / 4) / 2 + (s.x / 4) * col - s.x / 2 + offset;
}
@ -135,7 +135,7 @@ void Enemy::Update(float delta_time) {
UpdateWave(delta_time);
}
Random& rnd = Engine::Get().GetRandomGenerator();
Randomf& rnd = Engine::Get().GetRandomGenerator();
chromatic_aberration_offset_ += 0.8f * delta_time;
@ -449,7 +449,7 @@ void Enemy::KillAllEnemyUnits(bool randomize_order) {
e.enemy_type <= kEnemyType_Unit_Last) {
if (randomize_order) {
e.kill_timer = Lerp(0.0f, engine.GetScreenSize().y * 0.5f * 0.15f,
engine.GetRandomGenerator().GetFloat());
engine.GetRandomGenerator().Rand());
} else {
float dist = e.sprite.GetPosition().y -
game->GetPlayer().GetWeaponPos(kDamageType_Green).y;
@ -924,7 +924,8 @@ void Enemy::TakeDamage(EnemyUnit* target, int damage) {
boss_.SetFrame(11);
});
boss_animator_.SetTimer(1.25f);
boss_animator_.Play(Animator::kFrames | Animator::kTimer, true);
boss_animator_.Play(Animator::kFrames, true);
boss_animator_.Play(Animator::kTimer, false);
}
} else {
Vector2f s = target->health_base.GetSize();
@ -946,8 +947,8 @@ void Enemy::TakeDamage(EnemyUnit* target, int damage) {
target->movement_animator.Pause(Animator::kMovement);
target->sprite_animator.Pause(Animator::kFrames);
Random& rnd = Engine::Get().GetRandomGenerator();
float stealth_timer = Lerp(2.0f, 5.0f, rnd.GetFloat());
Randomf& rnd = Engine::Get().GetRandomGenerator();
float stealth_timer = Lerp(2.0f, 5.0f, rnd.Rand());
target->sprite_animator.SetEndCallback(
Animator::kTimer, [&, target]() -> void {
// No horizontal teleport in boss fight.
@ -960,7 +961,7 @@ void Enemy::TakeDamage(EnemyUnit* target, int damage) {
// Vertical teleport (wave 6+).
float ct = target->movement_animator.GetTime(Animator::kMovement);
if (wave_ >= 6 && ct < 0.6f) {
float t = Lerp(0.0f, 0.5f, rnd.GetFloat());
float t = Lerp(0.0f, 0.5f, rnd.Rand());
float nt = std::min(ct + t, 0.6f);
target->movement_animator.SetTime(Animator::kMovement, nt, true);
}
@ -1005,7 +1006,8 @@ void Enemy::TakeDamage(EnemyUnit* target, int damage) {
boss_animator_.Play(Animator::kFrames, true);
});
boss_animator_.SetTimer(0.2f);
boss_animator_.Play(Animator::kFrames | Animator::kTimer, true);
boss_animator_.Play(Animator::kFrames, true);
boss_animator_.Play(Animator::kTimer, false);
}
}
}
@ -1015,7 +1017,7 @@ void Enemy::UpdateWave(float delta_time) {
seconds_since_last_spawn_[i] += delta_time;
Engine& engine = Engine::Get();
Random& rnd = engine.GetRandomGenerator();
Randomf& rnd = engine.GetRandomGenerator();
EnemyType enemy_type = kEnemyType_Invalid;
@ -1027,7 +1029,7 @@ void Enemy::UpdateWave(float delta_time) {
seconds_since_last_spawn_[i] = 0;
seconds_to_next_spawn_[i] =
Lerp(kSpawnPeriod[i][0] * spawn_factor_,
kSpawnPeriod[i][1] * spawn_factor_, rnd.GetFloat());
kSpawnPeriod[i][1] * spawn_factor_, rnd.Rand());
break;
}
}
@ -1078,8 +1080,7 @@ void Enemy::UpdateWave(float delta_time) {
SpawnUnit(kEnemyType_PowerUp, kDamageType_Any, pos, 6);
}
seconds_since_last_power_up_ = 0;
seconds_to_next_power_up_ =
Lerp(1.3f * 60.0f, 1.8f * 60.0f, rnd.GetFloat());
seconds_to_next_power_up_ = Lerp(1.3f * 60.0f, 1.8f * 60.0f, rnd.Rand());
}
}
@ -1091,7 +1092,7 @@ void Enemy::UpdateBoss(float delta_time) {
for (int i = 0; i < kEnemyType_Unit_Last + 1; ++i)
seconds_since_last_spawn_[i] += delta_time;
Random& rnd = Engine::Get().GetRandomGenerator();
Randomf& rnd = Engine::Get().GetRandomGenerator();
boss_spawn_time_ += delta_time;
float boss_spawn_factor =
@ -1112,13 +1113,13 @@ void Enemy::UpdateBoss(float delta_time) {
seconds_since_last_spawn_[i] = 0;
seconds_to_next_spawn_[i] =
Lerp(kSpawnPeriod[i][0] * boss_spawn_factor,
kSpawnPeriod[i][1] * boss_spawn_factor, rnd.GetFloat());
kSpawnPeriod[i][1] * boss_spawn_factor, rnd.Rand());
break;
} else if (seconds_to_next_spawn_[i] >
kSpawnPeriod[i][1] * boss_spawn_factor) {
seconds_to_next_spawn_[i] =
Lerp(kSpawnPeriod[i][0] * boss_spawn_factor,
kSpawnPeriod[i][1] * boss_spawn_factor, rnd.GetFloat());
kSpawnPeriod[i][1] * boss_spawn_factor, rnd.Rand());
}
}
@ -1140,8 +1141,8 @@ void Enemy::UpdateBoss(float delta_time) {
: (DamageType)(rnd.Roll(2) - 1);
int col = (last_spawn_col_++) % 2;
float offset = Lerp(boss_.GetSize().x * -0.12f, boss_.GetSize().x * 0.12f,
rnd.GetFloat());
float offset =
Lerp(boss_.GetSize().x * -0.12f, boss_.GetSize().x * 0.12f, rnd.Rand());
float x = (boss_.GetSize().x / 3) * (col ? 1 : -1) + offset;
Vector2f pos = {x, boss_.GetPosition().y - boss_.GetSize().y / 2};

View File

@ -109,8 +109,9 @@ bool Menu::Initialize() {
logo_[1].SetFrame(0);
logo_animator_[1].SetFrames(12, 20);
logo_animator_[1].SetTimer(
Lerp(3.0f, 8.0f, Engine::Get().GetRandomGenerator().GetFloat()));
logo_animator_[1].Play(Animator::kFrames | Animator::kTimer, true);
Lerp(3.0f, 8.0f, Engine::Get().GetRandomGenerator().Rand()));
logo_animator_[1].Play(Animator::kFrames, true);
logo_animator_[1].Play(Animator::kTimer, false);
});
logo_animator_[1].Attach(&logo_[1]);
@ -119,7 +120,7 @@ bool Menu::Initialize() {
logo_[1].SetFrame(12);
logo_animator_[1].SetFrames(9, 30);
logo_animator_[1].SetTimer(
Lerp(3.0f, 8.0f, Engine::Get().GetRandomGenerator().GetFloat()));
Lerp(3.0f, 8.0f, Engine::Get().GetRandomGenerator().Rand()));
logo_animator_[1].Play(Animator::kFrames | Animator::kTimer, false);
});
logo_animator_[1].SetEndCallback(Animator::kFrames, [&]() -> void {
@ -308,7 +309,8 @@ void Menu::Show() {
high_score_animator_.SetEndCallback(Animator::kBlending, [&]() -> void {
high_score_animator_.SetBlending(kColorFadeOut, 0.3f);
high_score_animator_.SetTimer(5);
high_score_animator_.Play(Animator::kBlending | Animator::kTimer, true);
high_score_animator_.Play(Animator::kBlending, true);
high_score_animator_.Play(Animator::kTimer, false);
});
high_score_animator_.SetEndCallback(Animator::kTimer, [&]() -> void {
high_score_animator_.Play(Animator::kBlending | Animator::kTimer, false);

View File

@ -14,7 +14,7 @@ using namespace eng;
SkyQuad::SkyQuad()
: shader_(Engine::Get().CreateRenderResource<Shader>()),
sky_offset_{
0, Lerp(0.0f, 10.0f, Engine::Get().GetRandomGenerator().GetFloat())} {
0, Lerp(0.0f, 10.0f, Engine::Get().GetRandomGenerator().Rand())} {
last_sky_offset_ = sky_offset_;
}

View File

@ -31,8 +31,6 @@ void Animator::Play(int animation, bool loop) {
loop_flags_ |= animation;
else
loop_flags_ &= ~animation;
if ((loop_flags_ & kTimer) != 0)
loop_flags_ &= ~kTimer;
}
void Animator::Pause(int animation) {
@ -52,7 +50,6 @@ void Animator::Stop(int animation) {
timer_time_ = 0;
play_flags_ |= animation;
Update(0);
Evaluate(0);
play_flags_ &= ~animation;
loop_flags_ &= ~animation;
@ -97,7 +94,6 @@ void Animator::SetTime(int animation, float time, bool force_update) {
if (force_update) {
unsigned play_flags = play_flags_;
play_flags_ = animation;
Update(0);
Evaluate(0);
play_flags_ = play_flags;
}
@ -107,16 +103,15 @@ void Animator::SetEndCallback(int animation, base::Closure cb) {
if ((inside_cb_ & animation) != 0) {
has_pending_cb_ = true;
pending_cb_ = std::move(cb);
}
if ((animation & kMovement) != 0 && inside_cb_ != kMovement)
} else if ((animation & kMovement) != 0)
movement_cb_ = std::move(cb);
if ((animation & kRotation) != 0 && inside_cb_ != kRotation)
else if ((animation & kRotation) != 0)
rotation_cb_ = std::move(cb);
if ((animation & kBlending) != 0 && inside_cb_ != kBlending)
else if ((animation & kBlending) != 0)
blending_cb_ = std::move(cb);
if ((animation & kFrames) != 0 && inside_cb_ != kFrames)
else if ((animation & kFrames) != 0)
frame_cb_ = std::move(cb);
if ((animation & kTimer) != 0 && inside_cb_ != kTimer)
else if ((animation & kTimer) != 0)
timer_cb_ = std::move(cb);
}
@ -248,7 +243,11 @@ void Animator::UpdateAnimTime(float delta_time,
float anim_speed,
float& anim_time,
base::Closure& cb) {
if ((loop_flags_ & anim) == 0 && anim_time == 1.0f) {
anim_time += anim_speed * delta_time;
if (anim_time > 1.0f) {
if (loop_flags_ & anim) {
anim_time = fmod(anim_time, 1.0f);
} else {
anim_time = 0;
play_flags_ &= ~anim;
if (cb) {
@ -260,18 +259,8 @@ void Animator::UpdateAnimTime(float delta_time,
cb = std::move(pending_cb_);
}
}
return;
} else if ((anim & kFrames) != 0 && (loop_flags_ & kFrames) != 0 &&
anim_time == 1.0f) {
anim_time = 0;
}
anim_time += anim_speed * delta_time;
if (anim_time > 1)
anim_time = (anim & kFrames) != 0 || (anim & kTimer) != 0 ||
(loop_flags_ & anim) == 0
? 1
: fmod(anim_time, 1.0f);
}
}
} // namespace eng

View File

@ -354,7 +354,7 @@ std::unique_ptr<InputEvent> Engine::GetNextInputEvent() {
void Engine::StartRecording(const Json::Value& payload) {
if (!replaying_ && !recording_) {
recording_ = true;
random_ = Random();
random_ = Randomf();
replay_data_.root()["seed"] = random_.seed();
replay_data_.root()["payload"] = payload;
tick_ = 0;
@ -375,7 +375,7 @@ bool Engine::Replay(const std::string file_name, Json::Value& payload) {
if (!replaying_ && !recording_ &&
replay_data_.Load(file_name, PersistentData::kShared)) {
replaying_ = true;
random_ = Random(replay_data_.root()["seed"].asUInt());
random_ = Randomf(replay_data_.root()["seed"].asUInt());
payload = replay_data_.root()["payload"];
tick_ = 0;
replay_index_ = 0;

View File

@ -111,7 +111,7 @@ class Engine {
const Font* GetSystemFont() { return system_font_.get(); }
base::Random& GetRandomGenerator() { return random_; }
base::Randomf& GetRandomGenerator() { return random_; }
TextureCompressor* GetTextureCompressor(bool opacity);
@ -208,7 +208,7 @@ class Engine {
bool replaying_ = false;
int replay_index_ = 0;
base::Random random_;
base::Randomf random_;
void ContextLost();

View File

@ -904,23 +904,7 @@ void RendererVulkan::BeginFrame() {
context_.AppendCommandBuffer(frames_[current_frame_].setup_command_buffer);
context_.AppendCommandBuffer(frames_[current_frame_].draw_command_buffer);
task_runner_.PostTask(HERE, [&]() {
vkResetCommandPool(device_, frames_[current_frame_].setup_command_pool, 0);
VkCommandBufferBeginInfo cmdbuf_begin;
cmdbuf_begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
cmdbuf_begin.pNext = nullptr;
cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
cmdbuf_begin.pInheritanceInfo = nullptr;
VkResult err = vkBeginCommandBuffer(
frames_[current_frame_].setup_command_buffer, &cmdbuf_begin);
if (err) {
DLOG << "vkBeginCommandBuffer failed with error " << std::to_string(err);
return;
}
});
semaphore_.Release();
vkResetCommandPool(device_, frames_[current_frame_].draw_command_pool, 0);
VkCommandBufferBeginInfo cmdbuf_begin;
@ -928,8 +912,16 @@ void RendererVulkan::BeginFrame() {
cmdbuf_begin.pNext = nullptr;
cmdbuf_begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
cmdbuf_begin.pInheritanceInfo = nullptr;
VkResult err = vkBeginCommandBuffer(
frames_[current_frame_].draw_command_buffer, &cmdbuf_begin);
frames_[current_frame_].setup_command_buffer, &cmdbuf_begin);
if (err) {
DLOG << "vkBeginCommandBuffer failed with error " << std::to_string(err);
return;
}
err = vkBeginCommandBuffer(frames_[current_frame_].draw_command_buffer,
&cmdbuf_begin);
if (err) {
DLOG << "vkBeginCommandBuffer failed with error " << std::to_string(err);
return;