-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathexample.cpp
281 lines (235 loc) · 9.39 KB
/
example.cpp
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
#include <imgui.h>
#include <le/core/fixed_string.hpp>
#include <le/core/logger.hpp>
#include <le/imcpp/engine_stats.hpp>
#include <le/importer/importer.hpp>
#include <le/input/receiver.hpp>
#include <le/resources/mesh_asset.hpp>
#include <le/resources/pcm_asset.hpp>
#include <le/scene/freecam_controller.hpp>
#include <le/scene/imcpp/scene_graph.hpp>
#include <le/scene/mesh_animator.hpp>
#include <le/scene/mesh_renderer.hpp>
#include <le/scene/runtime.hpp>
#include <le/scene/ui/text.hpp>
#include <le/vfs/file_reader.hpp>
#include <le/vfs/vfs.hpp>
namespace example {
using namespace le;
namespace {
auto const g_log = le::logger::Logger{"Example"};
// using Scene requires linking to le::le-scene.
class BrainStem : public Scene {
public:
// store imported mesh Uri to later load and render.
BrainStem(Uri mesh_uri) : m_mesh_uri(std::move(mesh_uri)) {}
private:
auto setup() -> void final {
Scene::setup();
setup_camera();
spawn_brain_stem();
spawn_free_cam();
set_title_text();
}
auto tick(Duration dt) -> void final {
Scene::tick(dt);
update_futures();
handle_drops();
update_editor();
// check the current input state: this is fast but too coarse for say text input,
// which should use input::Receiver (like 'App' does below, or 'ui::InputText').
if (Engine::self().input_state().keyboard[GLFW_KEY_R] == input::Action::eRelease) {
// reload this scene (or load some oher scene).
// the actual switching is deferred to the next tick, so 'this' is still valid.
SceneSwitcher::self().switch_scene(std::make_unique<BrainStem>(m_mesh_uri));
}
}
auto setup_camera() -> void {
// offset the camera to roughly centre the expected mesh.
main_camera.transform.set_position({0.0f, 1.0f, 3.0f});
// set a non-black clear colour.
main_camera.clear_colour = graphics::Rgba{.channels = {0x20, 0x15, 0x10, 0xff}};
// reduce shadow frustum to increase sharpness. (small scene.)
graphics::Renderer::self().shadow_frustum = glm::vec3{15.0f};
}
auto spawn_brain_stem() -> void {
// load mesh and its assets (materials, textures, skeleton, etc).
// load_async() can be used to obtain a std::future.
auto const* mesh_asset = Resources::self().load<MeshAsset>(m_mesh_uri);
// hard exit if the mesh failed to load, for the purpose of this example.
if (mesh_asset == nullptr) { throw Error{std::format("failed to load MeshAsset [{}]", m_mesh_uri.value())}; }
m_mesh_entity = spawn_mesh(&mesh_asset->mesh, m_mesh_uri.value());
auto& mesh_entity = get_entity(*m_mesh_entity);
// create a child entity to attach an offset AABB collider.
auto& collider_entity = spawn("collider", &mesh_entity);
auto& collider = collider_entity.attach<ColliderAabb>();
// offset the collider.
collider.aabb_size = {0.5f, 1.5f, 0.5f};
collider_entity.get_transform().set_position({0.0f, 0.5f * collider.aabb_size.y, 0.0f});
}
auto spawn_free_cam() -> void {
// spawn a FreeCam entity.
// hold right click to engage.
auto& free_cam = spawn("freecam");
m_freecam_entity = free_cam.id();
free_cam.attach<FreecamController>();
}
auto set_title_text() -> void {
// setup some UI title text.
ui::Text::default_font_uri = font_uri;
auto& title_text = get_ui_root().push_element<ui::Text>();
title_text.set_text("BrainStem");
// anchor to top of parent view (the whole screen, as it will be pushed to the root view).
title_text.transform.anchor.y = 0.5f;
// offset y downwards by 100 pixels.
title_text.transform.position.y = -100.0f;
}
auto update_editor() -> void {
ImGui::SetNextWindowSize({300.0f, 200.0f}, ImGuiCond_Once);
ImGui::SetNextWindowPos({100.0f, 100.0f}, ImGuiCond_Once);
if (auto w = imcpp::Window{"editor"}) {
ImGui::Checkbox("Engine Stats", &m_show_stats);
ImGui::Separator();
m_scene_graph.draw_to(w, *this);
}
if (m_show_stats) {
ImGui::SetNextWindowSize({300.0f, 200.0f}, ImGuiCond_Once);
ImGui::SetNextWindowPos({100.0f, 400.0f}, ImGuiCond_Once);
if (auto w = imcpp::Window{"Engine Stats", &m_show_stats}) { m_engine_stats.draw_to(w); }
}
// loading modal.
if (auto loading = imcpp::Modal{"loading"}) {
ImGui::Text("%s", FixedString{"loading [{}]...", m_loading_uri.value()}.c_str());
if (m_loading_uri.is_empty()) { imcpp::Modal::close_current(); }
}
}
auto spawn_mesh(NotNull<graphics::Mesh const*> mesh, std::string_view const name) -> Id<Entity> {
// spawn an entity and attach a mesh renderer (and animator).
auto& mesh_entity = spawn(std::format("mesh_{}", name));
auto ret = mesh_entity.id();
mesh_entity.attach<MeshRenderer>().set_mesh(mesh);
// allow users to "override" the GLTF data with a static mesh.
if (mesh->skeleton != nullptr) { mesh_entity.attach<MeshAnimator>().set_skeleton(mesh->skeleton); }
return ret;
}
auto handle_drop(std::string_view const path) -> bool {
// make path relative to mount point (data directory).
auto uri = dynamic_cast<FileReader const&>(vfs::get_reader()).to_uri(path);
if (uri.is_empty()) { return false; }
auto const extension = uri.extension();
// check if drop is a music file.
if (extension == ".mp3" || extension == ".ogg" || extension == ".wav") {
// start loading PcmAsset.
m_pcm_future = Resources::self().load_async<PcmAsset>(uri);
// set loading text.
m_loading_uri = std::move(uri);
// open modal.
imcpp::Modal::open("loading");
return true;
}
// check if drop is a MeshAsset.
if (extension == ".json" && Asset::get_asset_type(uri) == MeshAsset::type_name_v) {
// start loading MeshAsset.
m_mesh_future = Resources::self().load_async<MeshAsset>(uri);
// set loading text.
m_loading_uri = std::move(uri);
// open modal.
imcpp::Modal::open("loading");
return true;
}
return false;
}
auto handle_drops() -> void {
if (!m_loading_uri.is_empty()) {
// already busy loading.
return;
}
for (auto const& drop : Engine::self().input_state().drops) {
// break if loading started.
if (handle_drop(drop)) { break; }
}
}
auto update_futures() -> void {
// check if MeshAsset future is valid and ready.
if (Resources::is_ready(m_mesh_future)) {
if (auto const* mesh_asset = m_mesh_future.get()) { spawn_mesh(&mesh_asset->mesh, m_loading_uri); }
// reset loading modal.
m_loading_uri = {};
}
// check if PcmAsset future is valid and ready.
if (Resources::is_ready(m_pcm_future)) {
if (auto const* pcm = m_pcm_future.get()) {
auto& audio_device = audio::Device::self();
audio_device.set_track(&pcm->pcm);
audio_device.play_music();
}
// reset loading modal.
m_loading_uri = {};
}
}
// hard coded Uri, unpacked from data.zip at CMake configure time.
inline static Uri const font_uri{"font.ttf"};
Uri m_mesh_uri{};
std::optional<EntityId> m_mesh_entity{};
std::optional<EntityId> m_freecam_entity{};
std::future<Ptr<MeshAsset>> m_mesh_future{};
std::future<Ptr<PcmAsset>> m_pcm_future{};
Uri m_loading_uri{};
imcpp::SceneGraph m_scene_graph{};
imcpp::EngineStats m_engine_stats{};
bool m_show_stats{};
};
// 'input::Receiver's allow fine-grained reaction to keyboard and mouse input events.
// it adds 'this' to a stack in its constructor, which is walked backwards during event dispatch.
// a receiver that returns 'true' in its callbacks blocks the stack from being walked further.
// using Runtime requires linking to le::le-scene.
class App : public Runtime, public input::Receiver {
public:
explicit App(std::string_view const exe_path) {
auto data_path = le::FileReader::find_super_directory("data/", exe_path);
if (data_path.empty()) { throw Error{"failed to locate data"}; }
g_log.info("mounting data at [{}]", data_path);
le::vfs::set_reader(std::make_unique<le::FileReader>(data_path));
// import GLTF into engine Mesh.
// this would usually be done offline, and using le-importer (exe) directly.
// using Importer requires linking to le::le-importer-lib.
auto importer = importer::Importer{};
auto input = importer::Input{};
input.data_root = std::move(data_path);
input.gltf_path = input.data_root / gltf_uri.value();
input.force = true;
if (!importer.setup(std::move(input))) { throw Error{"failed to setup le-importer"}; }
auto uri = importer.import_mesh(0);
// hard exit if the mesh failed to load, for the purpose of this example.
if (!uri) { throw Error{std::format("failed to import mesh from [{}]", gltf_uri.value())}; }
m_mesh_uri = std::move(*uri);
}
private:
auto setup() -> void final {
Runtime::setup();
SceneSwitcher::self().switch_scene(std::make_unique<BrainStem>(m_mesh_uri));
}
// input::Receiver callback
auto on_key(int key, int action, int mods) -> bool final {
if (action == GLFW_RELEASE && key == GLFW_KEY_W && mods == GLFW_MOD_CONTROL) { Engine::self().shutdown(); }
if (action == GLFW_PRESS && key == GLFW_KEY_ESCAPE && mods == 0) { Engine::self().shutdown(); }
// this is the only receiver on the stack in this example so it doesn't matter,
// but we wouldn't want to block input from going further down the stack if it wasn't.
// a 'ui::InputText' instance in comparison WILL block if it's enabled.
return false;
}
// hard coded Uri, unpacked from data.zip at CMake configure time.
inline static Uri const gltf_uri{"BrainStem.gltf"};
Uri m_mesh_uri{};
};
} // namespace
} // namespace example
auto main(int argc, char** argv) -> int {
if (argc < 1) { return EXIT_FAILURE; }
try {
example::App{*argv}.run();
} catch (std::exception const& e) {
example::g_log.error("fatal error: {}", e.what());
return EXIT_FAILURE;
}
}