Botcraft 26.3
Loading...
Searching...
No Matches
RenderingManager.cpp
Go to the documentation of this file.
2
3#include <glad/glad.h>
4#include <GLFW/glfw3.h>
5
6#include <glm/glm.hpp>
7#include <glm/gtc/type_ptr.hpp>
8
9#ifdef USE_IMGUI
10#include <imgui.h>
11#include <imgui_impl_glfw.h>
12#include <imgui_impl_opengl3.h>
13#endif
14
15
24
28
32
35
38
39#include <utility>
40
41const std::vector<float> color_day({ 0.6f, 0.85f, 0.9f });
42const std::vector<float> color_night({0.1f, 0.1f, 0.1f});
43
44namespace Botcraft
45{
46 namespace Renderer
47 {
48 std::weak_ptr<RenderingManager> RenderingManager::current_instance;
50
51 std::shared_ptr<RenderingManager> RenderingManager::CreateRenderingManagerIfPossible(
52 std::shared_ptr<World> world_,
53 std::shared_ptr<InventoryManager> inventory_manager_,
54 std::shared_ptr<EntityManager> entity_manager_
55 )
56 {
57 std::lock_guard<std::mutex> lock(instance_mutex);
58
59 std::shared_ptr<RenderingManager> instance = current_instance.lock();
60
61 if (instance == nullptr)
62 {
63 instance.reset(new RenderingManager(world_, inventory_manager_, entity_manager_));
64 current_instance = instance;
65
66 return instance;
67 }
68 return nullptr;
69 }
70
72 std::shared_ptr<World> world_,
73 std::shared_ptr<InventoryManager> inventory_manager_,
74 std::shared_ptr<EntityManager> entity_manager_
75 )
76 {
77 world = world_;
78 inventory_manager = inventory_manager_;
79 entity_manager = entity_manager_;
80 local_player = nullptr;
81 window = nullptr;
82
83 for (int i = 0; i < is_key_pressed.size(); ++i)
84 {
85 is_key_pressed[i] = false;
86 }
87
88 inventory_open = false;
89 behaviour_open = false;
90 behaviour_renderer = std::make_unique<BehaviourRenderer>();
91
92 deltaTime = 0.0f;
93 lastFrameTime = 0.0f;
94
99 has_proj_changed = true;
100
103 first_mouse = true;
104
105 MouseCallback = [](double, double) {};
106 KeyboardCallback = [](std::array<bool, static_cast<int>(KEY_CODE::NUMBER_OF_KEYS)>, double) {};
107
108 world_renderer = std::make_unique<WorldRenderer>();
109
110 day_time = 0.0f;
111
112 running = true;
113 rendering_thread = std::thread(&RenderingManager::Run, this);
114 }
115
117 {
118 {
119 std::lock_guard<std::mutex> lock(mutex_updating);
120 running = false;
121 }
122 condition_update.notify_all();
123
124 if (rendering_thread.joinable())
125 {
126 rendering_thread.join();
127 }
128 // thread_updating_renderable is joined before rendering_thread returns so we don't need to wait for it here
129 }
130
132 {
133 Logger::GetInstance().RegisterThread("RenderingLoop");
134 if (!Init())
135 {
136 LOG_ERROR("Can't init rendering manager");
137 running = false;
138 return;
139 }
140
142
143 my_shader->Use();
144 float real_fps = 1.0f;
145
146 while (running && !glfwWindowShouldClose(window))
147 {
148 const double currentFrame = glfwGetTime();
149 const std::chrono::steady_clock::time_point frame_start = std::chrono::steady_clock::now();
150
151 deltaTime = currentFrame - lastFrameTime;
152 lastFrameTime = currentFrame;
153
155
156 if (Settings::width.load(std::memory_order_relaxed) != current_window_width ||
157 Settings::height.load(std::memory_order_relaxed) != current_window_height
158 )
159 {
160 current_window_width = Settings::width.load(std::memory_order_relaxed);
161 current_window_height = Settings::height.load(std::memory_order_relaxed);
163 }
164
165 if (Settings::headless.load(std::memory_order_relaxed) != current_window_headless)
166 {
167 current_window_headless = Settings::headless.load(std::memory_order_relaxed);
169 {
170 glfwShowWindow(window);
171 }
172 else
173 {
174 glfwHideWindow(window);
175 }
176 }
177
178 if (Settings::vsync.load(std::memory_order_relaxed) != current_vsync)
179 {
180 current_vsync = Settings::vsync.load(std::memory_order_relaxed);
181 glfwSwapInterval(current_vsync ? 1 : 0);
182 }
183
185 {
186 if (local_player == nullptr)
187 {
188 local_player = entity_manager->GetLocalPlayer();
189 }
190 if (local_player != nullptr)
191 {
192 const Vector3<double> pos = local_player->GetPosition();
193 world_renderer->SetPosOrientation(pos.x, pos.y + local_player->GetEyeHeight(), pos.z, local_player->GetYaw(), local_player->GetPitch());
194 }
195#ifdef USE_IMGUI
196 ImGui_ImplOpenGL3_NewFrame();
197 ImGui_ImplGlfw_NewFrame();
198 ImGui::NewFrame();
199
200 {
201 ImGui::SetNextWindowPos(ImVec2(0, 0));
202 ImGui::SetNextWindowSize(ImVec2(290, 70));
203 const Vector3<double> position = local_player == nullptr ? Vector3<double>(0.0) : local_player->GetPosition();
204 ImGui::Begin("Position", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse);
205 ImGui::Text("%f, %f, %f", position.x, position.y, position.z);
206 ImGui::Text("Yaw: %f || ", local_player == nullptr ? 0.0 : local_player->GetYaw());
207 ImGui::SameLine();
208 ImGui::Text("Pitch: %f", local_player == nullptr ? 0.0 : local_player->GetPitch());
209 ImGui::End();
210 }
211 {
212 ImGui::SetNextWindowPos(ImVec2(0, 75));
213 ImGui::SetNextWindowSize(ImVec2(290, 70));
214 ImGui::Begin("Targeted cube", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse);
215 Position raycasted_pos;
216 Position raycasted_normal;
217 const Blockstate* raycasted_blockstate =
218 world->Raycast(Vector3<double>(world_renderer->GetCamera()->GetPosition().x, world_renderer->GetCamera()->GetPosition().y, world_renderer->GetCamera()->GetPosition().z),
219 Vector3<double>(world_renderer->GetCamera()->GetFront().x, world_renderer->GetCamera()->GetFront().y, world_renderer->GetCamera()->GetFront().z),
220 6.0f, raycasted_pos, raycasted_normal);
221 if (raycasted_blockstate != nullptr)
222 {
223 ImGui::Text("Watching block at %i, %i, %i", raycasted_pos.x, raycasted_pos.y, raycasted_pos.z);
224 ImGui::Text("Block: %s", raycasted_blockstate->GetName().c_str());
225 if (ImGui::IsItemHovered(ImGuiHoveredFlags_::ImGuiHoveredFlags_AllowWhenDisabled))
226 {
227 ImGui::BeginTooltip();
228
229 ImGui::Text("Air: "); ImGui::SameLine(); raycasted_blockstate->IsAir() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
230 ImGui::Text("Solid: "); ImGui::SameLine(); raycasted_blockstate->IsSolid() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
231 ImGui::Text("Transparent: "); ImGui::SameLine(); raycasted_blockstate->IsTransparent() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
232 ImGui::Text("Lava: "); ImGui::SameLine(); raycasted_blockstate->IsLava() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
233 ImGui::Text("Water: "); ImGui::SameLine(); raycasted_blockstate->IsWater() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
234 ImGui::Text("Waterlogged: "); ImGui::SameLine(); raycasted_blockstate->IsWaterlogged() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
235 ImGui::Text("Fluid Falling: "); ImGui::SameLine(); raycasted_blockstate->IsFluidFalling() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
236 ImGui::Text("Climbable: "); ImGui::SameLine(); raycasted_blockstate->IsClimbable() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
237 ImGui::Text("Hazardous: "); ImGui::SameLine(); raycasted_blockstate->IsHazardous() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
238 ImGui::Text("Slime: "); ImGui::SameLine(); raycasted_blockstate->IsSlime() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
239 ImGui::Text("Bed: "); ImGui::SameLine(); raycasted_blockstate->IsBed() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
240 ImGui::Text("Soul Sand: "); ImGui::SameLine(); raycasted_blockstate->IsSoulSand() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
241 ImGui::Text("Honey: "); ImGui::SameLine(); raycasted_blockstate->IsHoney() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
242 ImGui::Text("Scaffolding: "); ImGui::SameLine(); raycasted_blockstate->IsScaffolding() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
243 ImGui::Text("Cobweb: "); ImGui::SameLine(); raycasted_blockstate->IsCobweb() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
244 ImGui::Text("UpBubbleColumn: "); ImGui::SameLine(); raycasted_blockstate->IsUpBubbleColumn() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
245 ImGui::Text("DownBubbleColumn: "); ImGui::SameLine(); raycasted_blockstate->IsDownBubbleColumn() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
246 ImGui::Text("Berry Bush: "); ImGui::SameLine(); raycasted_blockstate->IsBerryBush() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
247 ImGui::Text("Powder Snow: "); ImGui::SameLine(); raycasted_blockstate->IsPowderSnow() ? ImGui::TextColored(ImVec4(0.0, 1.0, 0.0, 1.0), "1") : ImGui::TextColored(ImVec4(1.0, 0.0, 0.0, 1.0), "0");
248 ImGui::Text("Fluid Height: "); ImGui::SameLine(); ImGui::TextUnformatted(std::to_string(raycasted_blockstate->GetFluidHeight()).data());
249 ImGui::Text("Hardness: "); ImGui::SameLine(); ImGui::TextUnformatted(std::to_string(raycasted_blockstate->GetHardness()).data());
250 ImGui::Text("Friction: "); ImGui::SameLine(); ImGui::TextUnformatted(std::to_string(raycasted_blockstate->GetFriction()).data());
251
252 ImGui::EndTooltip();
253 }
254 }
255 else
256 {
257 ImGui::Text("Watching block at");
258 ImGui::Text("Block: ");
259 }
260 ImGui::End();
261 }
262#endif
263 const float current_day_time = day_time;
264 std::vector<float> current_color(3);
265 for (int i = 0; i < 3; ++i)
266 {
267 current_color[i] = 2.0f * ((0.5f - std::abs(current_day_time - 0.5f)) * color_day[i] + (0.5f - std::min(std::abs(1.0f - current_day_time), current_day_time)) * color_night[i]);
268 }
269 glClearColor(current_color[0], current_color[1], current_color[2], 1.0f);
270 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
271
272 //Change view matrix
273 world_renderer->UpdateViewMatrix();
274
276 {
277 glm::mat4 projection = glm::perspective(glm::radians(45.0f), current_window_width / static_cast<float>(current_window_height), 0.1f, 200.0f);
278 my_shader->SetMat4("projection", projection);
279 world_renderer->SetCameraProjection(projection);
280 has_proj_changed = false;
281 }
282
283 world_renderer->UpdateFaces();
284
285 my_shader->Use();
286
287 //Draw all faces
288 world_renderer->UseAtlasTextureGL();
289
290#ifdef USE_IMGUI
291 int num_chunks, num_rendered_chunks, num_entities, num_rendered_entities, num_faces, num_rendered_faces;
292 world_renderer->RenderFaces(&num_chunks, &num_rendered_chunks, &num_entities, &num_rendered_entities, &num_faces, &num_rendered_faces);
293 {
294 ImGui::SetNextWindowPos(ImVec2(static_cast<float>(current_window_width), 0.0f), 0, ImVec2(1.0f, 0.0f));
295 ImGui::SetNextWindowSize(ImVec2(180.0f, 170.0f));
296 ImGui::Begin("Rendering", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse);
297 ImGui::Text("Lim. FPS: %.1f (%.2fms)", 1.0 / deltaTime, deltaTime * 1000.0);
298 ImGui::Text("Real FPS: %.1f (%.2fms)", 1.0 / real_fps, real_fps * 1000.0);
299 ImGui::Text("Loaded sections: %i", num_chunks);
300 ImGui::Text("Rendered sections: %i", num_rendered_chunks);
301 ImGui::Text("Num entities: %i", num_entities);
302 ImGui::Text("Rendered entities: %i", num_rendered_entities);
303 ImGui::Text("Loaded faces: %i", num_faces);
304 ImGui::Text("Rendered faces: %i", num_rendered_faces);
305 ImGui::End();
306 }
307#else
308 world_renderer->RenderFaces();
309#endif
310
311 glBindVertexArray(0);
312 glBindTexture(GL_TEXTURE_2D, 0);
313
314#ifdef USE_IMGUI
315 // Draw the behaviour if it's open
316 if (behaviour_open)
317 {
318 const int blackboard_width = static_cast<int>((static_cast<float>(current_window_width) - 30.0f) / 4.0f);
319
320 ImGui::SetNextWindowPos(ImVec2(15.0f, 15.0f), 0, ImVec2(0.0f, 0.0f));
321 ImGui::SetNextWindowSize(ImVec2(blackboard_width, current_window_height - 30.0f));
322 ImGui::Begin("Blackboard", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_NoCollapse);
323 behaviour_renderer->RenderBlackboard();
324 ImGui::End();
325
326 ImGui::SetNextWindowPos(ImVec2(15.0f + blackboard_width, 15.0f), 0, ImVec2(0.0f, 0.0f));
327 ImGui::SetNextWindowSize(ImVec2(current_window_width - blackboard_width - 30.0f, current_window_height - 30.0f));
328 ImGui::Begin("Behaviour", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse);
329 behaviour_renderer->RenderNodes();
330 ImGui::End();
331 }
332
333 // Draw the inventory if it's open
334 if (inventory_open)
335 {
336 ImGui::SetNextWindowPos(ImVec2(static_cast<float>(current_window_width), static_cast<float>(current_window_height)), 0, ImVec2(1.0f, 1.0f));
337 ImGui::SetNextWindowSize(ImVec2(300.0f, current_window_height - 175.0f));
338 ImGui::Begin("Inventory", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse);
339 if (inventory_manager && inventory_manager->GetPlayerInventory())
340 {
341 const std::map<short, ProtocolCraft::Slot>& slots = inventory_manager->GetPlayerInventory()->GetSlots();
342 for (short i = 0; i <= Window::INVENTORY_OFFHAND_INDEX; ++i)
343 {
344 auto it = slots.find(i);
345 if (it == slots.end())
346 {
347 continue;
348 }
350 {
351 ImGui::Text("Crafting output");
352 }
354 {
355 ImGui::Text("Crafting input");
356 }
357 else if (i == Window::INVENTORY_ARMOR_START)
358 {
359 ImGui::Text("Equiped Armor");
360 }
362 {
363 ImGui::Text("Inventory");
364 }
365 else if (i == Window::INVENTORY_HOTBAR_START)
366 {
367 ImGui::Text("Hotbar");
368 }
370 {
371 ImGui::Text("Offhand");
372 }
373 const std::string name = AssetsManager::getInstance().Items().at(it->second.GetItemId())->GetName();
374 if (name != "minecraft:air")
375 {
376 ImGui::Text(std::string(" (%i) " + name + " (x%i)").c_str(), i, it->second.GetItemCount());
377 }
378 }
379 }
380 ImGui::End();
381 }
382
383
384 ImGui::Render();
385
386 // Render ImGui
387 ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
388#endif
389 }
390
391 glfwSwapBuffers(window);
392 glfwPollEvents();
393
394 {
395 std::scoped_lock<std::mutex> lock(Settings::screenshot_mutex);
397 {
398 std::vector<unsigned char> pixels(current_window_height * current_window_width * 3);
399 glReadPixels(0, 0, current_window_width, current_window_height, GL_RGB, GL_UNSIGNED_BYTE, pixels.data());
400
401 if (!Settings::screenhsot_path.empty())
402 {
405 }
407 {
410 }
411 }
412 }
413
414 real_fps = static_cast<float>(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - frame_start).count() / 1e6);
415
416 while (true)
417 {
418 const double current_target_fps = Settings::target_fps.load(std::memory_order_relaxed);
419
420 if (current_target_fps <= 0.0)
421 {
422 Utilities::SleepFor(std::chrono::milliseconds(10));
423 if (!running)
424 {
425 break;
426 }
427 continue;
428 }
429
430 const std::chrono::duration<double> frame_duration(1.0 / current_target_fps);
431 const std::chrono::steady_clock::time_point frame_end = frame_start + std::chrono::duration_cast<std::chrono::steady_clock::duration>(frame_duration);
432
433 const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
434
435 if (now >= frame_end)
436 {
437 break;
438 }
439
440 const std::chrono::nanoseconds wait_time = frame_end - now;
441
442 // Wait for the end of the frame in small chunks (in case we move from 0.001 FPS to 60, we don't want to wait 1000 seconds before updating the framerate)
443 if (wait_time > std::chrono::milliseconds(10))
444 {
445 Utilities::SleepFor(std::chrono::milliseconds(10));
446 }
447 else
448 {
449 Utilities::SleepFor(wait_time);
450 }
451 }
452 }
453
454 {
455 std::lock_guard<std::mutex> lock(mutex_updating);
456 running = false;
457 }
458 condition_update.notify_all();
459 if (thread_updating_renderable.joinable())
460 {
462 }
463
464 world_renderer->ReleaseGL();
465 my_shader.reset();
466
467#ifdef USE_IMGUI
468 behaviour_renderer->CleanUp();
469 // ImGui cleaning
470 ImGui_ImplOpenGL3_Shutdown();
471 ImGui_ImplGlfw_Shutdown();
472 ImGui::DestroyContext();
473#endif
474
475 glfwDestroyWindow(window);
476 window = nullptr;
477 glfwTerminate();
478 }
479
481 {
482 {
483 std::lock_guard<std::mutex> lock(mutex_updating);
484 running = false;
485 }
486 condition_update.notify_all();
487 }
488
489 void RenderingManager::SetMouseCallback(std::function<void(double, double)> callback)
490 {
491 std::lock_guard<std::mutex> lock(callbacks_mutex);
492 MouseCallback = std::move(callback);
493 }
494
495 void RenderingManager::SetKeyboardCallback(std::function<void(std::array<bool, static_cast<int>(KEY_CODE::NUMBER_OF_KEYS)>, double)> callback)
496 {
497 std::lock_guard<std::mutex> lock(callbacks_mutex);
498 KeyboardCallback = std::move(callback);
499 }
500
502 {
503 behaviour_renderer->SetCurrentBehaviourTree(root);
504 }
505
507 {
508 behaviour_renderer->ResetBehaviourState();
509 }
510
512 {
513 behaviour_renderer->BehaviourStartTick();
514 }
515
516 void RenderingManager::BehaviourEndTick(const bool b) const
517 {
518 behaviour_renderer->BehaviourEndTick(b);
519 }
520
521 void RenderingManager::BehaviourTickChild(const size_t i) const
522 {
523 behaviour_renderer->BehaviourTickChild(i);
524 }
525
527 {
528 return behaviour_renderer->IsBehaviourPaused();
529 }
530
532 {
533 behaviour_renderer->ResetBlackboard();
534 }
535
536 void RenderingManager::UpdateBlackboardValue(const std::string& key, const std::any& value) const
537 {
538 behaviour_renderer->UpdateBlackboardValue(key, value);
539 }
540
541 void RenderingManager::RemoveBlackboardValue(const std::string& key) const
542 {
543 behaviour_renderer->RemoveBlackboardValue(key);
544 }
545
547 {
548 glfwInit();
549 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
550 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
551 glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
552#ifdef __APPLE__
553 glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
554#endif
555
556 glfwWindowHint(GLFW_VISIBLE, current_window_headless ? GLFW_FALSE : GLFW_TRUE);
557 glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
558
559 window = glfwCreateWindow(current_window_width, current_window_height, "RenderingManager", NULL, NULL);
560 if (window == NULL)
561 {
562 LOG_ERROR("Failed to create GLFW window");
563 glfwTerminate();
564 return false;
565 }
566 glfwMakeContextCurrent(window);
567 //set the user pointer of the window to this object to pass it to the callbacks
568 glfwSetWindowUserPointer(window, this);
569 glfwSetFramebufferSizeCallback(window, &RenderingManager::ResizeCallback);
570 glfwSetCursorPosCallback(window, &RenderingManager::InternalMouseCallback);
571
572 glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
573
574 glfwSwapInterval(current_vsync ? 1 : 0);
575
576 // glad: load all OpenGL function pointers
577 // ---------------------------------------
578 if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
579 {
580 LOG_ERROR("Failed to initialize GLAD");
581 glfwDestroyWindow(window);
582 window = nullptr;
583 glfwTerminate();
584 return false;
585 }
586
587#ifdef USE_IMGUI
588 // imgui: setup context
589 // ---------------------------------------
590 IMGUI_CHECKVERSION();
591 ImGui::CreateContext();
592
593 behaviour_renderer->Init();
594
595 ImGuiIO& io = ImGui::GetIO();
596 io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
597
598 // Style
599 ImGui::StyleColorsDark();
600
601 // Setup platform/renderer
602 ImGui_ImplGlfw_InitForOpenGL(window, true);
603 ImGui_ImplOpenGL3_Init("#version 330");
604#endif
605
606 my_shader = std::make_unique<Shader>();
607
608 glEnable(GL_DEPTH_TEST);
609 //glEnable(GL_CULL_FACE);
610 glEnable(GL_BLEND);
611 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
612
613 //Set an uniform buffer for view matrix
614 unsigned int uniform_view_block_index = glGetUniformBlockIndex(my_shader->Program(), "MatriceView");
615 glUniformBlockBinding(my_shader->Program(), uniform_view_block_index, 0);
616
617 world_renderer->InitGL();
618
619 return true;
620 }
621
622 void RenderingManager::ResizeCallback(GLFWwindow *window, int width, int height)
623 {
624 RenderingManager *this_object = static_cast<RenderingManager*>(glfwGetWindowUserPointer(window));
625 this_object->current_window_width = width;
626 this_object->current_window_height = height;
627 glViewport(0, 0, width, height);
628 this_object->has_proj_changed = true;
629 Settings::height = height;
630 Settings::width = width;
631 }
632
633 void RenderingManager::InternalMouseCallback(GLFWwindow *window, double xpos, double ypos)
634 {
635 RenderingManager *this_object = static_cast<RenderingManager*>(glfwGetWindowUserPointer(window));
636
637 if (this_object->first_mouse)
638 {
639 this_object->mouse_last_x = xpos;
640 this_object->mouse_last_y = ypos;
641 this_object->first_mouse = false;
642 }
643
644 double xoffset = xpos - this_object->mouse_last_x;
645 double yoffset = this_object->mouse_last_y - ypos;
646
647 this_object->mouse_last_x = xpos;
648 this_object->mouse_last_y = ypos;
649
650 if (this_object->inventory_open || this_object->behaviour_open)
651 {
652 return;
653 }
654
655 // Copy the callback to prevent double locking in the unexpected case where a
656 // user defined callback locks the mutex too
657 std::function<void(double, double)> callback;
658 {
659 std::lock_guard<std::mutex> lock(this_object->callbacks_mutex);
660 callback = this_object->MouseCallback;
661 }
662 if (callback)
663 {
664 callback(xoffset, yoffset);
665 }
666 }
667
669 {
670 is_key_pressed[static_cast<int>(KEY_CODE::FORWARD)] = glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS;
671 is_key_pressed[static_cast<int>(KEY_CODE::BACKWARD)] = glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS;
672 is_key_pressed[static_cast<int>(KEY_CODE::RIGHT)] = glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS;
673 is_key_pressed[static_cast<int>(KEY_CODE::LEFT)] = glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS;
674 is_key_pressed[static_cast<int>(KEY_CODE::SPACE)] = glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS;
675 is_key_pressed[static_cast<int>(KEY_CODE::SHIFT)] = glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS;
676 is_key_pressed[static_cast<int>(KEY_CODE::CTRL)] = glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS;
677 is_key_pressed[static_cast<int>(KEY_CODE::ESC)] = glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS;
678 is_key_pressed[static_cast<int>(KEY_CODE::MOUSE_LEFT)] = glfwGetKey(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS;
679 const bool is_inventory_key_pressed = glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS;
680
681 // Toggle inventory if E was not pressed during previous frame and is during this one
682 const bool toggle_inventory = (!is_key_pressed[static_cast<int>(KEY_CODE::INVENTORY)] && is_inventory_key_pressed);
683 // Save current value just like others
684 is_key_pressed[static_cast<int>(KEY_CODE::INVENTORY)] = is_inventory_key_pressed;
685
686
687 const bool is_behaviour_key_pressed = glfwGetKey(window, GLFW_KEY_B) == GLFW_PRESS;
688
689 // Toggle behaviour if B was not pressed during previous frame and is during this one
690 const bool toggle_behaviour = (!is_key_pressed[static_cast<int>(KEY_CODE::BEHAVIOUR)] && is_behaviour_key_pressed);
691 // Save current value just like others
692 is_key_pressed[static_cast<int>(KEY_CODE::BEHAVIOUR)] = is_behaviour_key_pressed;
693
694#ifdef USE_IMGUI
695 if (toggle_inventory)
696 {
698 }
699
700 if (toggle_behaviour)
701 {
703 }
704
706 {
707 glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
708 }
709 else
710 {
711 glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
712 }
713#endif
714
715 if (glfwGetKey(window, GLFW_KEY_F2) == GLFW_PRESS)
716 {
717 std::scoped_lock<std::mutex> lock(Settings::screenshot_mutex);
718 Settings::screenhsot_path = "screenshot.png";
719 }
720
721 // Copy the callback to prevent double locking in the unexpected case where a
722 // user defined callback locks the mutex too
723 std::function<void(std::array<bool, static_cast<int>(KEY_CODE::NUMBER_OF_KEYS)>, double)> callback;
724 {
725 std::lock_guard<std::mutex> lock(callbacks_mutex);
726 callback = KeyboardCallback;
727 }
728 if (callback)
729 {
730 callback(is_key_pressed, deltaTime);
731 }
732 }
733
734 void RenderingManager::AddChunkToUpdate(const int x, const int z)
735 {
736 const std::vector<Position> chunk_pos = { {Position(x, 0, z), Position(x - 1, 0, z),
737 Position(x + 1, 0 , z), Position(x, 0, z - 1), Position(x, 0, z + 1)} };
738
739 std::lock_guard<std::mutex> guard_rendering(mutex_updating);
740 for (int i = 0; i < chunk_pos.size(); ++i)
741 {
742 chunks_to_udpate.insert(chunk_pos[i]);
743 }
744 condition_update.notify_all();
745 }
746
748 {
749 std::lock_guard<std::mutex> guard_rendering(mutex_updating);
750 entities_to_update.insert(id);
751 condition_update.notify_all();
752 }
753
755 {
756 Logger::GetInstance().RegisterThread("RenderingDataUpdate");
757
758 while (true)
759 {
760 std::unordered_set<Position> chunks;
761 std::unordered_set<int> entities;
762
763 {
764 std::unique_lock<std::mutex> lock(mutex_updating);
765 condition_update.wait(lock, [this]() {
766 return !running || !chunks_to_udpate.empty() || !entities_to_update.empty();
767 });
768 if (!running)
769 {
770 return;
771 }
772 chunks = std::exchange(chunks_to_udpate, {});
773 entities = std::exchange(entities_to_update, {});
774 }
775
776 for (const Position& pos : chunks)
777 {
778 std::optional<Botcraft::Chunk> chunk;
779 // Get the new values in the world
780 const bool has_chunk_been_modified = world->HasChunkBeenModified(pos.x, pos.z);
781 if (has_chunk_been_modified)
782 {
783 chunk = world->ResetChunkModificationState(pos.x, pos.z);
784 world_renderer->UpdateChunk(pos.x, pos.z, chunk);
785 }
786 }
787
788 for (const int entity_id : entities)
789 {
790 std::vector<Face> faces;
791 // Get the new values
792 std::shared_ptr<Botcraft::Entity> entity = entity_manager->GetEntity(entity_id);
793 bool should_update = false;
794 if (entity == nullptr)
795 {
796 should_update = true;
797 }
798 else if (!entity->GetAreRenderedFacesUpToDate())
799 {
800 faces = entity->GetFaces(true);
801 should_update = true;
802 }
803
804 if (should_update)
805 {
806 world_renderer->UpdateEntity(entity_id, faces);
807 }
808 }
809 }
810 }
811
812 /*
813 * Packet handling methods
814 */
815
817 {
818 Position chunk_coords = Botcraft::Chunk::BlockCoordsToChunkCoords(msg.GetPos());
819 AddChunkToUpdate(chunk_coords.x, chunk_coords.z);
820 }
821
823 {
824#if PROTOCOL_VERSION < 737 /* < 1.16.2 */
825 AddChunkToUpdate(msg.GetChunkX(), msg.GetChunkZ());
826#else
827 AddChunkToUpdate(msg.GetSectionPos() >> 42, msg.GetSectionPos() << 22 >> 42);
828#endif
829 }
830
832 {
833#if PROTOCOL_VERSION < 764 /* < 1.20.2 */
834 AddChunkToUpdate(msg.GetX(), msg.GetZ());
835#else
836 AddChunkToUpdate(msg.GetPos().GetX(), msg.GetPos().GetZ());
837#endif
838 }
839
840#if PROTOCOL_VERSION < 757 /* < 1.18 */
841 void RenderingManager::Handle(ProtocolCraft::ClientboundLevelChunkPacket& msg)
842#else
844#endif
845 {
846 AddChunkToUpdate(msg.GetX(), msg.GetZ());
847 }
848
853
854#if PROTOCOL_VERSION < 759 /* < 1.19 */
855 void RenderingManager::Handle(ProtocolCraft::ClientboundAddMobPacket& msg)
856 {
857 AddEntityToUpdate(msg.GetEntityId());
858 }
859#endif
860
861#if PROTOCOL_VERSION < 721 /* < 1.16 */
862 void RenderingManager::Handle(ProtocolCraft::ClientboundAddGlobalEntityPacket& msg)
863 {
864 AddEntityToUpdate(msg.GetEntityId());
865 }
866#endif
867
868#if PROTOCOL_VERSION < 764 /* < 1.20.2 */
869 void RenderingManager::Handle(ProtocolCraft::ClientboundAddPlayerPacket& msg)
870 {
871 AddEntityToUpdate(msg.GetEntityId());
872 }
873#endif
874
879
880#if PROTOCOL_VERSION < 755 /* < 1.17 */
881 void RenderingManager::Handle(ProtocolCraft::ClientboundMoveEntityPacket& msg)
882 {
883 AddEntityToUpdate(msg.GetEntityId());
884 }
885#endif
886
891
896
901
903 {
904 std::shared_ptr<LocalPlayer> local_player = entity_manager->GetLocalPlayer();
905 if (local_player != nullptr && local_player->GetEntityID() == msg.GetEntityId())
906 {
907 return;
908 }
909 AddEntityToUpdate(msg.GetEntityId());
910 }
911
912#if PROTOCOL_VERSION == 755 /* 1.17 */
913 void RenderingManager::Handle(ProtocolCraft::ClientboundRemoveEntityPacket& msg)
914 {
915 AddEntityToUpdate(msg.GetEntityId());
916 }
917#else
919 {
920 for (auto id: msg.GetEntityIds())
921 {
923 }
924 }
925#endif
926
928 {
929#if PROTOCOL_VERSION < 775 /* 26.1 */
930 // abs because the server multiplies by -1 to indicate fixed daytime for versions < 1.21.2
931 day_time = ((std::abs(msg.GetDayTime()) + 6000) % 24000) / 24000.0f;
932#else
933 if (world != nullptr)
934 {
935 // Per dimension updates
936 // TODO: match the dimension to ids using registry?
937 if (world != nullptr)
938 {
939 if (world->GetCurrentDimension() == "minecraft:overworld")
940 {
941 auto it = msg.GetClockUpdates().find(0);
942 if (it != msg.GetClockUpdates().end())
943 {
944 day_time = ((it->second.GetTotalTicks() + 6000) % 24000) / 24000.0f;
945 }
946 }
947 else if (world->GetCurrentDimension() == "minecraft:the_end")
948 {
949 auto it = msg.GetClockUpdates().find(1);
950 if (it != msg.GetClockUpdates().end())
951 {
952 day_time = ((it->second.GetTotalTicks() + 6000) % 24000) / 24000.0f;
953 }
954 }
955 }
956 }
957#endif
958 }
959
964 } // Renderer
965} // Botcraft
#define LOG_ERROR(osstream)
Definition Logger.hpp:45
const std::vector< float > color_day({ 0.6f, 0.85f, 0.9f })
const std::vector< float > color_night({0.1f, 0.1f, 0.1f})
const std::unordered_map< ItemId, std::unique_ptr< Item > > & Items() const
static AssetsManager & getInstance()
bool IsHazardous() const
bool IsBerryBush() const
const std::string & GetName() const
bool IsCobweb() const
bool IsDownBubbleColumn() const
bool IsTransparent() const
bool IsClimbable() const
float GetHardness() const
bool IsFluidFalling() const
bool IsPowderSnow() const
bool IsUpBubbleColumn() const
bool IsWaterlogged() const
float GetFriction() const
float GetFluidHeight() const
Get fluid height for this block.
bool IsScaffolding() const
bool IsSoulSand() const
static Position BlockCoordsToChunkCoords(const Position &pos)
Definition Chunk.cpp:164
void RegisterThread(const std::string &name)
Register the current thread in the map.
Definition Logger.cpp:104
static Logger & GetInstance()
Definition Logger.cpp:36
void BehaviourTickChild(const size_t i) const
static std::shared_ptr< RenderingManager > CreateRenderingManagerIfPossible(std::shared_ptr< World > world_, std::shared_ptr< InventoryManager > inventory_manager_, std::shared_ptr< EntityManager > entity_manager_)
std::unordered_set< int > entities_to_update
std::unique_ptr< BehaviourRenderer > behaviour_renderer
void InternalProcessInput(GLFWwindow *window)
void SetKeyboardCallback(std::function< void(std::array< bool, static_cast< int >(KEY_CODE::NUMBER_OF_KEYS)>, double)> callback)
RenderingManager(std::shared_ptr< World > world_, std::shared_ptr< InventoryManager > inventory_manager_, std::shared_ptr< EntityManager > entity_manager_)
std::function< void(double, double)> MouseCallback
std::shared_ptr< LocalPlayer > local_player
void AddChunkToUpdate(const int x, const int z)
void SetCurrentBehaviourTree(const BaseNode *root) const
static void ResizeCallback(GLFWwindow *window, int width, int height)
std::unique_ptr< WorldRenderer > world_renderer
std::unordered_set< Position > chunks_to_udpate
std::shared_ptr< EntityManager > entity_manager
void RemoveBlackboardValue(const std::string &key) const
static void InternalMouseCallback(GLFWwindow *window, double xpos, double ypos)
void UpdateBlackboardValue(const std::string &key, const std::any &value) const
void SetMouseCallback(std::function< void(double, double)> callback)
void BehaviourEndTick(const bool b) const
virtual void Handle(ProtocolCraft::ClientboundBlockUpdatePacket &msg) override
std::function< void(std::array< bool, static_cast< int >(KEY_CODE::NUMBER_OF_KEYS)>, double)> KeyboardCallback
std::shared_ptr< InventoryManager > inventory_manager
static std::weak_ptr< RenderingManager > current_instance
std::array< bool, static_cast< int >(KEY_CODE::NUMBER_OF_KEYS)> is_key_pressed
static std::string screenhsot_path
Definition Settings.hpp:61
static std::mutex screenshot_mutex
Definition Settings.hpp:60
static std::function< void(const std::vector< unsigned char > &pixels, const int height, const int width)> screenshot_callback
Definition Settings.hpp:62
static std::atomic< int > height
Definition Settings.hpp:55
static std::atomic< bool > vsync
Definition Settings.hpp:58
static std::atomic< int > width
Definition Settings.hpp:56
static std::atomic< bool > headless
Definition Settings.hpp:57
static std::atomic< double > target_fps
Definition Settings.hpp:59
static constexpr short INVENTORY_HOTBAR_START
Definition Window.hpp:28
static constexpr short INVENTORY_CRAFTING_INPUT_START
Definition Window.hpp:21
static constexpr short INVENTORY_ARMOR_START
Definition Window.hpp:22
static constexpr short INVENTORY_CRAFTING_OUTPUT_INDEX
Definition Window.hpp:20
static constexpr short INVENTORY_STORAGE_START
Definition Window.hpp:27
static constexpr short INVENTORY_OFFHAND_INDEX
Definition Window.hpp:29
void WriteImage(const std::string &path, const int height, const int width, const int depth, const unsigned char *data, const bool vertical_revert=true)
void SleepFor(const std::chrono::duration< _Rep, _Period > &time)
Vector3< int > Position
Definition Vector3.hpp:314