ggerganov / imtui

ImTui: Immediate Mode Text-based User Interface C++ Library
https://imtui.ggerganov.com
MIT License
2.94k stars 123 forks source link

Bit confused by emscripten example #16

Closed cvlvxi closed 3 years ago

cvlvxi commented 3 years ago

Hi there,

Great project! I have a dumb question hope you could shed some light on my confusion..

In your example: example-emscripten0

#include "imtui/imtui-impl-emscripten.h"
#include "imtui/imtui.h"

#include "imtui-demo.h"

#include <emscripten.h>

ImTui::TScreen *g_screen = nullptr;

extern "C" {
EMSCRIPTEN_KEEPALIVE

void render_frame() {
  ImTui_ImplText_NewFrame();
  ImTui_ImplEmscripten_NewFrame();

  ImGui::NewFrame();

  ImGui::SetNextWindowPos(ImVec2(8, 28), ImGuiCond_Once);
  ImGui::SetNextWindowSize(ImVec2(50.0, 10.0), ImGuiCond_Once);
  ImGui::Begin("Hello, dog!");

  ImGui::End();

  // bool showDemoWindow = true;
  // ImTui::ShowDemoWindow(&showDemoWindow);

  ImGui::Render();

  ImTui_ImplText_RenderDrawData(ImGui::GetDrawData(), g_screen);
}
}

int main() {
  IMGUI_CHECKVERSION();
  ImGui::CreateContext();

  ImTui_ImplText_Init();
  g_screen = ImTui_ImplEmscripten_Init(true);

  return 0;
}

The example works but I'm not too sure how render_frame is being called.

I'm not too familiar with emscripten so perhaps I could be pointed to something that would explain something that's missing..

I'm assuming that there's something in not calling an infinite while loop like the ncurses example does but doing any slight modification to the above results in lots of problems for me..

I intend to pass into my render_frame some of my custom objects to render, not sure how I would do this...

Any help would be greatly appreciated! :-)

ggerganov commented 3 years ago

The emscripten example builds a WASM module which is then included in the index.html file:

https://github.com/ggerganov/imtui/blob/f60c95f77416e08b9f79f5f9f449957ff82d21e2/examples/emscripten0/index-tmpl.html#L279

We then create an instance of the module here:

https://github.com/ggerganov/imtui/blob/f60c95f77416e08b9f79f5f9f449957ff82d21e2/examples/emscripten0/index-tmpl.html#L176

Finally, in the window.requestAnimationFrame we call the render_frame() method of the module (notice it is prefixed with an underscore):

https://github.com/ggerganov/imtui/blob/f60c95f77416e08b9f79f5f9f449957ff82d21e2/examples/emscripten0/index-tmpl.html#L239

As you probably know, the callback provided to window.requestAnimationFrame is called typically every 16 ms, and this is the loop you are looking for.

I would recommend searching for some basic emscripten examples on the internet and trying to get them to work and modify them. This is how I got started.

cvlvxi commented 3 years ago

Ah ok I see thanks for that feedback :-)