CText.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314
  1. #include "CText.h"
  2. #include <algorithm>
  3. #include <array>
  4. #include <cstdio>
  5. #include <filesystem>
  6. #include <sstream>
  7. #include <strings.h>
  8. #include <unordered_map>
  9. #include <vector>
  10. #include <glm/gtc/matrix_transform.hpp>
  11. #include <glm/gtc/type_ptr.hpp>
  12. #include "WallpaperEngine/Assets/AssetLocator.h"
  13. #include "WallpaperEngine/Data/Model/DynamicValue.h"
  14. #include "WallpaperEngine/Data/Model/Material.h"
  15. #include "WallpaperEngine/Data/Model/Object.h"
  16. #include "WallpaperEngine/Data/Model/UserSetting.h"
  17. #include "WallpaperEngine/Data/Parsers/MaterialParser.h"
  18. #include "WallpaperEngine/Logging/Log.h"
  19. #include "WallpaperEngine/Render/CFBO.h"
  20. #include "WallpaperEngine/Render/Camera.h"
  21. #include "WallpaperEngine/Render/TextureProvider.h"
  22. #include "WallpaperEngine/Render/Wallpapers/CScene.h"
  23. #include "WallpaperEngine/Scripting/ScriptEngine.h"
  24. using namespace WallpaperEngine::Render::Objects;
  25. using namespace WallpaperEngine::Render::Objects::Effects;
  26. using WallpaperEngine::Data::Parsers::MaterialParser;
  27. namespace {
  28. // Fallback fonts, used only when fontconfig finds nothing at all
  29. const std::vector<std::string> kFontCandidates = {
  30. "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
  31. "/usr/share/fonts/TTF/DejaVuSans.ttf",
  32. "/usr/share/fonts/dejavu/DejaVuSans.ttf",
  33. "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
  34. };
  35. // WE's "systemfont_*" names are Windows fonts, ask fontconfig for the closest installed match
  36. std::string fontconfigMatch (const std::string& font) {
  37. static const std::vector<std::pair<std::string, std::string>> families = {
  38. { "systemfont_arial", "Arial,Liberation Sans,Arimo" },
  39. { "systemfont_calibri", "Calibri,Carlito" },
  40. { "systemfont_cambria", "Cambria,Caladea" },
  41. { "systemfont_comicsans", "Comic Sans MS,Comic Neue,Comic Relief" },
  42. { "systemfont_consolas", "Consolas,Inconsolata,DejaVu Sans Mono" },
  43. { "systemfont_sansserif", "sans-serif" },
  44. { "systemfont_segoe", "Segoe UI,Noto Sans,Open Sans" },
  45. { "systemfont_verdana", "Verdana,DejaVu Sans" },
  46. };
  47. std::string family = "sans-serif";
  48. for (const auto& [name, list] : families) {
  49. if (font == name) {
  50. family = list;
  51. break;
  52. }
  53. }
  54. const std::string command = "fc-match -f '%{file}' '" + family + "' 2>/dev/null";
  55. FILE* pipe = popen (command.c_str (), "r");
  56. if (pipe == nullptr) {
  57. return {};
  58. }
  59. std::string path;
  60. char buffer[512];
  61. while (fgets (buffer, sizeof (buffer), pipe) != nullptr) {
  62. path += buffer;
  63. }
  64. pclose (pipe);
  65. return !path.empty () && std::filesystem::exists (path) ? path : std::string ();
  66. }
  67. // The first of these families fontconfig has installed under that very name (fc-match always answers with something)
  68. std::string installedFamily (const std::vector<std::string>& families) {
  69. static std::unordered_map<std::string, std::string> cache;
  70. for (const auto& family : families) {
  71. if (const auto it = cache.find (family); it != cache.end ()) {
  72. if (!it->second.empty ()) {
  73. return it->second;
  74. }
  75. continue;
  76. }
  77. const std::string command = "fc-match -f '%{family}\\n%{file}' '" + family + "' 2>/dev/null";
  78. FILE* pipe = popen (command.c_str (), "r");
  79. std::string output;
  80. if (pipe != nullptr) {
  81. char buffer[512];
  82. while (fgets (buffer, sizeof (buffer), pipe) != nullptr) {
  83. output += buffer;
  84. }
  85. pclose (pipe);
  86. }
  87. std::string path;
  88. const size_t newline = output.find ('\n');
  89. if (newline != std::string::npos) {
  90. std::stringstream names (output.substr (0, newline));
  91. std::string name;
  92. while (std::getline (names, name, ',')) {
  93. if (strcasecmp (name.c_str (), family.c_str ()) == 0) {
  94. path = output.substr (newline + 1);
  95. break;
  96. }
  97. }
  98. }
  99. if (!path.empty () && !std::filesystem::exists (path)) {
  100. path.clear ();
  101. }
  102. cache.emplace (family, path);
  103. if (!path.empty ()) {
  104. return path;
  105. }
  106. }
  107. return {};
  108. }
  109. // wallpaper64.exe's fallback fonts (off_140484C40, tried per character by sub_1401AD670): Windows fonts from the
  110. // system font folder and the assets' Twemoji. Here the Windows fonts count when they are installed under their own
  111. // family, arial.ttf also through its metric compatible clones like the systemfont_arial match, and the CJK ones
  112. // through the usual Linux CJK families since Windows always has YaHei/Malgun but Linux never does
  113. std::vector<TextFontSource> weFallbackFonts (const WallpaperEngine::Assets::AssetLocator& assets) {
  114. static std::shared_ptr<const std::vector<uint8_t>> twemoji;
  115. static bool twemojiRead = false;
  116. if (!twemojiRead) {
  117. twemojiRead = true;
  118. try {
  119. auto stream = assets.read ("fonts/TwemojiMozilla.ttf");
  120. stream->seekg (0, std::ios::end);
  121. const auto size = stream->tellg ();
  122. stream->seekg (0, std::ios::beg);
  123. std::vector<uint8_t> data (static_cast<size_t> (size));
  124. stream->read (reinterpret_cast<char*> (data.data ()), size);
  125. twemoji = std::make_shared<const std::vector<uint8_t>> (std::move (data));
  126. } catch (const std::exception& e) {
  127. sLog.error ("CText: cannot read fonts/TwemojiMozilla.ttf: ", e.what ());
  128. }
  129. }
  130. const std::vector<std::vector<std::string>> before = {
  131. { "Arial", "Liberation Sans", "Arimo" },
  132. { "Segoe UI Emoji" },
  133. { "Arial Unicode MS" },
  134. { "Segoe UI" },
  135. };
  136. const std::vector<std::vector<std::string>> after = {
  137. { "Segoe UI Symbol" },
  138. { "Microsoft YaHei", "Noto Sans CJK SC", "Source Han Sans SC", "WenQuanYi Zen Hei", "Droid Sans Fallback" },
  139. { "Malgun Gothic", "Noto Sans CJK KR", "Source Han Sans KR" },
  140. };
  141. std::vector<TextFontSource> fonts;
  142. for (const auto& families : before) {
  143. if (std::string path = installedFamily (families); !path.empty ()) {
  144. fonts.push_back ({ nullptr, std::move (path) });
  145. }
  146. }
  147. if (twemoji != nullptr) {
  148. fonts.push_back ({ twemoji, "fonts/TwemojiMozilla.ttf" });
  149. }
  150. for (const auto& families : after) {
  151. if (std::string path = installedFamily (families); !path.empty ()) {
  152. fonts.push_back ({ nullptr, std::move (path) });
  153. }
  154. }
  155. return fonts;
  156. }
  157. // The glyph atlas as a TextureProvider: R8 coverage for plain glyphs, RGBA for MSDF ones
  158. class TextAtlasTexture final : public WallpaperEngine::Render::TextureProvider {
  159. public:
  160. TextAtlasTexture () {
  161. glGenTextures (1, &m_textureID);
  162. glBindTexture (GL_TEXTURE_2D, m_textureID);
  163. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  164. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  165. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  166. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  167. }
  168. ~TextAtlasTexture () override { glDeleteTextures (1, &m_textureID); }
  169. void upload (int size, int channels, const uint8_t* pixels) {
  170. m_size = static_cast<uint32_t> (size);
  171. m_channels = channels;
  172. m_resolution = glm::vec4 (static_cast<float> (size));
  173. glBindTexture (GL_TEXTURE_2D, m_textureID);
  174. glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
  175. if (channels == 4) {
  176. glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, size, size, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  177. } else {
  178. glTexImage2D (GL_TEXTURE_2D, 0, GL_R8, size, size, 0, GL_RED, GL_UNSIGNED_BYTE, pixels);
  179. }
  180. }
  181. [[nodiscard]] GLuint getTextureID (uint32_t) const override { return m_textureID; }
  182. [[nodiscard]] uint32_t getTextureWidth (uint32_t) const override { return m_size; }
  183. [[nodiscard]] uint32_t getTextureHeight (uint32_t) const override { return m_size; }
  184. [[nodiscard]] uint32_t getRealWidth () const override { return m_size; }
  185. [[nodiscard]] uint32_t getRealHeight () const override { return m_size; }
  186. [[nodiscard]] TextureFormat getFormat () const override {
  187. return m_channels == 4 ? TextureFormat_ARGB8888 : TextureFormat_R8;
  188. }
  189. [[nodiscard]] uint32_t getFlags () const override { return TextureFlags_ClampUVs; }
  190. [[nodiscard]] const std::vector<FrameSharedPtr>& getFrames () const override { return m_frames; }
  191. [[nodiscard]] const glm::vec4* getResolution () const override { return &m_resolution; }
  192. [[nodiscard]] bool isAnimated () const override { return false; }
  193. void incrementUsageCount () const override { }
  194. void decrementUsageCount () const override { }
  195. void update () const override { }
  196. [[nodiscard]] bool isReady () const override { return m_size > 0; }
  197. private:
  198. std::vector<FrameSharedPtr> m_frames;
  199. glm::vec4 m_resolution = { 0.0f, 0.0f, 0.0f, 0.0f };
  200. uint32_t m_size = 0;
  201. int m_channels = 1;
  202. GLuint m_textureID = GL_NONE;
  203. };
  204. // Final pass: blits the effect-processed buffer onto the actual scene
  205. MaterialUniquePtr buildCompositeMaterial () {
  206. auto pass = std::make_unique<MaterialPass> (MaterialPass {
  207. .blending = BlendingMode_Translucent,
  208. .cullmode = CullingMode_Disable,
  209. .depthtest = DepthtestMode_Disabled,
  210. .depthwrite = DepthwriteMode_Disabled,
  211. .shader = "genericimage",
  212. .textures = {},
  213. .usertextures = {},
  214. .combos = {},
  215. .constants = {},
  216. });
  217. auto material = std::make_unique<Material> ();
  218. material->filename = "<text/composite>";
  219. material->passes.push_back (std::move (pass));
  220. return material;
  221. }
  222. const Material& compositeMaterial () {
  223. static const MaterialUniquePtr material = buildCompositeMaterial ();
  224. return *material;
  225. }
  226. // Mirrors CImage.cpp's clampParallaxAxis: keeps an edge pair from sliding into the on-screen part
  227. // of the canvas once `offset` is added to both; a box too small to cover it on this axis has no
  228. // ground to uncover and moves freely.
  229. float clampParallaxAxis (float offset, float edgeA, float edgeB, float visibleLow, float visibleHigh) {
  230. const float low = std::min (edgeA, edgeB);
  231. const float high = std::max (edgeA, edgeB);
  232. const float maxOffset = visibleLow - low;
  233. const float minOffset = visibleHigh - high;
  234. if (minOffset > maxOffset) {
  235. return offset;
  236. }
  237. // a layer that doesn't cover the screen at rest stays where the scene puts it (3621923790's hair), the clamp
  238. // only keeps the parallax from uncovering more
  239. return std::clamp (offset, std::min (minOffset, 0.0f), std::max (maxOffset, 0.0f));
  240. }
  241. TextAlign parseAlign (const std::string& align) {
  242. if (align == "left") {
  243. return TextAlign::Left;
  244. }
  245. if (align == "right") {
  246. return TextAlign::Right;
  247. }
  248. return TextAlign::Center;
  249. }
  250. } // namespace
  251. CText::CText (Wallpapers::CScene& scene, const Text& text) :
  252. CObject (scene, text), CRenderable (scene, text, compositeMaterial ()), ScriptableObject (scene, text),
  253. m_text (text), m_font (text.font), m_loadedFont (text.font) {
  254. this->registerProperty ("color", *text.color->value);
  255. this->registerProperty ("alpha", *text.alpha->value);
  256. this->registerProperty ("origin", *text.origin->value);
  257. this->registerProperty ("scale", *text.scale->value);
  258. this->registerProperty ("visible", *text.visible->value);
  259. this->registerProperty ("text", *text.text->value);
  260. this->registerProperty ("font", m_font);
  261. this->registerProperty ("parallaxDepth", *text.parallaxDepth->value);
  262. // the text object's property table in wallpaper64.exe 2.8.42 (sub_140258CA0), same names as ITextLayer
  263. const std::pair<const char*, const UserSettingUniquePtr&> properties[] = {
  264. { "pointsize", text.pointSize },
  265. { "padding", text.padding },
  266. { "spacing", text.spacing },
  267. { "horizontalalign", text.horizontalAlign },
  268. { "verticalalign", text.verticalAlign },
  269. { "anchor", text.anchor },
  270. { "limitwidth", text.limitWidth },
  271. { "maxwidth", text.maxWidth },
  272. { "limitrows", text.limitRows },
  273. { "maxrows", text.maxRows },
  274. { "limituseellipsis", text.limitUseEllipsis },
  275. { "blockalign", text.blockAlign },
  276. { "opaquebackground", text.opaqueBackground },
  277. { "backgroundcolor", text.backgroundColor },
  278. { "backgroundbrightness", text.backgroundBrightness },
  279. { "msdf", text.msdf },
  280. { "outline", text.outline },
  281. { "outlinethickness", text.outlineThickness },
  282. { "outlinecolor", text.outlineColor },
  283. { "blur", text.blur },
  284. { "blursize", text.blurSize },
  285. { "dropshadow", text.dropShadow },
  286. { "dropshadowsize", text.dropShadowSize },
  287. { "dropshadowopacity", text.dropShadowOpacity },
  288. { "dropshadowoffset", text.dropShadowOffset },
  289. { "dropshadowcolor", text.dropShadowColor },
  290. { "depthtest", text.depthTest },
  291. };
  292. for (const auto& [name, setting] : properties) {
  293. this->registerProperty (name, *setting->value);
  294. }
  295. this->registerEffectConstants (text.effects);
  296. }
  297. CText::~CText () {
  298. if (m_layerHandle != Scripting::kInvalidLayerHandle) {
  299. this->getScene ().getScriptEngine ().destroyLayer (m_layerHandle);
  300. m_layerHandle = Scripting::kInvalidLayerHandle;
  301. }
  302. this->destroyPasses ();
  303. for (GLuint* buffer :
  304. { &m_glyphPositions, &m_glyphTexcoords, &m_colorGlyphPositions, &m_colorGlyphTexcoords, &m_backgroundPositions,
  305. &m_passSpacePosition, &m_compositePosition, &m_quadTexcoords, &m_compositeTexcoords }) {
  306. if (*buffer != 0) {
  307. glDeleteBuffers (1, buffer);
  308. }
  309. }
  310. }
  311. void CText::destroyPasses () {
  312. for (auto* pass : m_passes) {
  313. delete pass;
  314. }
  315. m_passes.clear ();
  316. m_mainFBO = nullptr;
  317. m_subFBO = nullptr;
  318. m_currentMainFBO = nullptr;
  319. m_currentSubFBO = nullptr;
  320. }
  321. void CText::setup () {
  322. const bool scripted = m_text.text->value->getScriptSource ().has_value ();
  323. const auto& text = m_text.text->value->getString ();
  324. if (text.empty () && !scripted) {
  325. return;
  326. }
  327. // sub_140186C90 flags a text (object type 4) that another object lists in its dependencies once every object
  328. // exists, before the first frame
  329. m_isDependency = std::ranges::any_of (this->getScene ().getScene ().objects, [this] (const auto& object) {
  330. return object->id != m_text.id
  331. && std::ranges::find (object->dependencies, m_text.id) != object->dependencies.end ();
  332. });
  333. m_layout.setFallbackFonts (weFallbackFonts (this->getAssetLocator ()));
  334. if (!loadFont ()) {
  335. return;
  336. }
  337. m_atlas = std::make_shared<TextAtlasTexture> ();
  338. m_colorAtlas = std::make_shared<TextAtlasTexture> ();
  339. m_colorTexture = std::make_shared<TextAtlasTexture> ();
  340. this->m_texture = m_atlas;
  341. for (GLuint* buffer :
  342. { &m_glyphPositions, &m_glyphTexcoords, &m_colorGlyphPositions, &m_colorGlyphTexcoords, &m_backgroundPositions,
  343. &m_passSpacePosition, &m_compositePosition, &m_quadTexcoords, &m_compositeTexcoords }) {
  344. glGenBuffers (1, buffer);
  345. }
  346. const GLfloat passSpacePosition[] = { -1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
  347. 1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f };
  348. const GLfloat quadTexcoords[] = { 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f };
  349. glBindBuffer (GL_ARRAY_BUFFER, m_passSpacePosition);
  350. glBufferData (GL_ARRAY_BUFFER, sizeof (passSpacePosition), passSpacePosition, GL_STATIC_DRAW);
  351. glBindBuffer (GL_ARRAY_BUFFER, m_quadTexcoords);
  352. glBufferData (GL_ARRAY_BUFFER, sizeof (quadTexcoords), quadTexcoords, GL_STATIC_DRAW);
  353. // the text buffer's rows run top down like WE's (v 0 at the top of the box), the composite quad's y runs down
  354. const GLfloat compositeTexcoords[] = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f };
  355. glBindBuffer (GL_ARRAY_BUFFER, m_compositeTexcoords);
  356. glBufferData (GL_ARRAY_BUFFER, sizeof (compositeTexcoords), compositeTexcoords, GL_STATIC_DRAW);
  357. // scripted text may start out empty, a space keeps the layout alive until the script produces a value
  358. this->relayout (text.empty () ? std::string (" ") : text);
  359. if (scripted) {
  360. initScriptLayer ();
  361. }
  362. CRenderable::setup ();
  363. m_passLayout = this->currentPassLayout ();
  364. this->uploadGeometry ();
  365. buildPasses ();
  366. m_initialized = true;
  367. }
  368. bool CText::loadFont () {
  369. // wallpapers packed in .pkg don't expose physical paths, so the font is read into memory
  370. if (!m_loadedFont.empty () && m_loadedFont.rfind ("systemfont_", 0) != 0) {
  371. try {
  372. auto stream = getAssetLocator ().read (m_loadedFont);
  373. stream->seekg (0, std::ios::end);
  374. const auto size = stream->tellg ();
  375. stream->seekg (0, std::ios::beg);
  376. std::vector<uint8_t> data (static_cast<size_t> (size));
  377. stream->read (reinterpret_cast<char*> (data.data ()), size);
  378. if (m_layout.setPrimaryFont (std::move (data), m_loadedFont)) {
  379. return true;
  380. }
  381. } catch (const std::exception& e) {
  382. sLog.error ("CText: cannot read font '", m_loadedFont, "': ", e.what ());
  383. }
  384. }
  385. // a font WE can't load falls back to arial.ttf
  386. const bool systemFont = m_loadedFont.rfind ("systemfont_", 0) == 0;
  387. std::string fontPath = fontconfigMatch (systemFont ? m_loadedFont : std::string ("systemfont_arial"));
  388. if (fontPath.empty ()) {
  389. for (const auto& candidate : kFontCandidates) {
  390. if (std::filesystem::exists (candidate)) {
  391. fontPath = candidate;
  392. break;
  393. }
  394. }
  395. }
  396. if (fontPath.empty () || !m_layout.setPrimaryFont ({}, fontPath)) {
  397. sLog.error ("CText: no usable font found for ", m_text.name);
  398. return false;
  399. }
  400. return true;
  401. }
  402. void CText::initScriptLayer () {
  403. const auto& script = m_text.text->value->getScriptSource ();
  404. if (!script.has_value ()) {
  405. return;
  406. }
  407. // a script already running as a regular property module drives the value itself
  408. if (this->getScene ().getScriptEngine ().hasScript (*m_text.text->value)) {
  409. return;
  410. }
  411. m_layerHandle = this->getScene ().getScriptEngine ().createLayerScript (
  412. *script, m_text.text->value->getProperties (), m_text.text->value->getString ()
  413. );
  414. if (m_layerHandle == Scripting::kInvalidLayerHandle) {
  415. sLog.error ("CText: createLayerScript failed for '", m_text.name, "'");
  416. }
  417. }
  418. TextLayoutParams CText::currentParams () const {
  419. // sub_140256F20: any of the glyph effects switches the whole text to MSDF glyphs
  420. const bool msdf = m_text.msdf->value->getBool () || m_text.outline->value->getBool ()
  421. || m_text.blur->value->getBool () || m_text.dropShadow->value->getBool ();
  422. return {
  423. .size = std::clamp (m_text.pointSize->value->getFloat (), 1.0f, 256.0f),
  424. .spacing = m_text.spacing->value->getVec2 (),
  425. .msdf = msdf,
  426. .align = parseAlign (m_text.horizontalAlign->value->getString ()),
  427. .maxWidth = m_text.limitWidth->value->getBool () ? m_text.maxWidth->value->getFloat () : 0.0f,
  428. .maxRows = m_text.limitRows->value->getBool () ? m_text.maxRows->value->getInt () : 0,
  429. .ellipsis = m_text.limitUseEllipsis->value->getBool (),
  430. .blockAlign = m_text.blockAlign->value->getBool (),
  431. };
  432. }
  433. glm::vec2 CText::currentPadding () const {
  434. const glm::vec2 padding = m_text.padding->value->getVec2 ();
  435. return { std::min (padding.x, 512.0f), std::min (padding.y, 512.0f) };
  436. }
  437. // sub_1402585C0 with the margins sub_140183A70 computes: how much of the scene the output crops off each edge (negative
  438. // when it letterboxes), so a text anchored to an edge or corner keeps its distance to what is actually visible there
  439. glm::vec2 CText::screenAnchorOffset () const {
  440. static const std::vector<std::pair<std::string, glm::ivec2>> anchors = {
  441. { "center", { 0, 0 } }, { "top", { 0, 1 } }, { "topright", { 1, 1 } },
  442. { "right", { 1, 0 } }, { "bottomright", { 1, -1 } }, { "bottom", { 0, -1 } },
  443. { "bottomleft", { -1, -1 } }, { "left", { -1, 0 } }, { "topleft", { -1, 1 } },
  444. };
  445. const std::string& name = m_text.anchor->value->getString ();
  446. const auto it = std::ranges::find_if (anchors, [&name] (const auto& anchor) { return anchor.first == name; });
  447. const auto& state = this->getScene ().getState ();
  448. if (it == anchors.end () || state.getViewportWidth () <= 0 || state.getViewportHeight () <= 0) {
  449. return { 0.0f, 0.0f };
  450. }
  451. const auto& camera = this->getScene ().getCamera ();
  452. const glm::vec4 margins = this->getScene ().getVisibleMargins ();
  453. // --expand-canvas grows the canvas evenly around the scene
  454. const float overhangX = (camera.getCanvasWidth () - camera.getWidth ()) * 0.5f;
  455. const float overhangY = (camera.getCanvasHeight () - camera.getHeight ()) * 0.5f;
  456. const float left = margins.x - overhangX;
  457. const float right = margins.y - overhangX;
  458. const float bottom = margins.z - overhangY;
  459. const float top = margins.w - overhangY;
  460. const auto axis = [] (int side, float low, float high) {
  461. // low is the left/bottom margin, high the right/top one; y is up
  462. return side < 0 ? low : side > 0 ? -high : (low - high) * 0.5f;
  463. };
  464. return { axis (it->second.x, left, right), axis (it->second.y, bottom, top) };
  465. }
  466. CText::PassLayout CText::currentPassLayout () const {
  467. const auto& debug = this->getScene ().getContext ().getApp ().getContext ().settings.render.debug;
  468. const bool dropShadow = m_text.dropShadow->value->getBool ();
  469. PassLayout layout {
  470. .msdf = m_params.msdf,
  471. .outline = m_params.msdf && m_text.outline->value->getBool (),
  472. .blur = m_params.msdf && m_text.blur->value->getBool (),
  473. .dropShadow = m_params.msdf && dropShadow,
  474. .background = m_text.opaqueBackground->value->getBool (),
  475. .color = !m_result.colorQuads.empty (),
  476. // the _depth materials outside orthographic scenes (renderer flag 0x400) unless depthtest is "disabled" (+1440,
  477. // enum table "disabled" 1 / "enabled" 0, any other string is the first entry)
  478. .depth = this->getScene ().getCamera ().isPerspective () && m_text.depthTest->value->getString () == "enabled",
  479. .blendMode = m_text.colorBlendMode->value->getInt (),
  480. };
  481. // sub_1401E6F50: a blend mode other than 0 and 31 (additive) makes the text composite through
  482. // effectpassthrough, like having effects, and so does fog (renderer flags 0x1800000 = scene fog flags 0x4000
  483. // and 0x8000, sub_140186440). Its other trigger, image flag 0x100, is never set in 2.8.42. The scene loader adds
  484. // 0x1010 to a text another object lists in its dependencies (sub_140186C90), the buffer is what it reads
  485. const bool fog = this->getScene ().hasDistanceFog () || this->getScene ().hasHeightFog ();
  486. layout.buffered
  487. = (!m_text.effects.empty () || (layout.blendMode != 0 && layout.blendMode != 31) || fog || m_isDependency)
  488. && !debug.baseOnly;
  489. // sub_140258900: text with effects renders into a buffer of its box plus padding on every side
  490. if (layout.buffered && m_result.valid) {
  491. const glm::vec2 padding = this->currentPadding ();
  492. layout.bufferSize = {
  493. std::max (1, static_cast<int> (padding.x * 2.0f + (m_result.maxX - m_result.minX))),
  494. std::max (1, static_cast<int> (padding.y * 2.0f + (m_result.top - m_result.bottom))),
  495. };
  496. }
  497. return layout;
  498. }
  499. void CText::relayout (const std::string& text) {
  500. m_params = this->currentParams ();
  501. m_result = m_layout.layout (text, m_params);
  502. m_lastRenderedText = text;
  503. if (m_layout.takeAtlasChanged ()) {
  504. static_cast<TextAtlasTexture*> (m_atlas.get ())
  505. ->upload (m_layout.getAtlasSize (), m_layout.getAtlasChannels (), m_layout.getAtlasPixels ().data ());
  506. }
  507. if (m_layout.takeColorAtlasChanged ()) {
  508. static_cast<TextAtlasTexture*> (m_colorAtlas.get ())
  509. ->upload (m_layout.getColorAtlasSize (), 4, m_layout.getColorAtlasPixels ().data ());
  510. if (m_layout.getColorScale () > 0) {
  511. static_cast<TextAtlasTexture*> (m_colorTexture.get ())
  512. ->upload (
  513. m_layout.getColorAtlasSize () * m_layout.getColorScale (), 4,
  514. m_layout.getColorTexturePixels ().data ()
  515. );
  516. }
  517. }
  518. this->uploadGeometry ();
  519. }
  520. void CText::uploadGeometry () {
  521. const auto upload = [] (const std::vector<TextGlyphQuad>& quads, GLuint positionBuffer, GLuint texcoordBuffer) {
  522. std::vector<GLfloat> positions;
  523. std::vector<GLfloat> texcoords;
  524. positions.reserve (quads.size () * 18);
  525. texcoords.reserve (quads.size () * 12);
  526. // two triangles per glyph, WE's index order 0 2 1 / 1 2 3 over top left, top right, bottom left, bottom right
  527. for (const auto& quad : quads) {
  528. const auto [x0, y0, x1, y1] = std::array { quad.rect.x, quad.rect.y, quad.rect.z, quad.rect.w };
  529. const auto [u0, v0, u1, v1] = std::array { quad.uv.x, quad.uv.y, quad.uv.z, quad.uv.w };
  530. positions.insert (
  531. positions.end (), { x0, y1, 0.0f, x0, y0, 0.0f, x1, y1, 0.0f, x1, y1, 0.0f, x0, y0, 0.0f, x1, y0, 0.0f }
  532. );
  533. texcoords.insert (texcoords.end (), { u0, v0, u0, v1, u1, v0, u1, v0, u0, v1, u1, v1 });
  534. }
  535. glBindBuffer (GL_ARRAY_BUFFER, positionBuffer);
  536. glBufferData (
  537. GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (positions.size () * sizeof (GLfloat)), positions.data (),
  538. GL_DYNAMIC_DRAW
  539. );
  540. glBindBuffer (GL_ARRAY_BUFFER, texcoordBuffer);
  541. glBufferData (
  542. GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (texcoords.size () * sizeof (GLfloat)), texcoords.data (),
  543. GL_DYNAMIC_DRAW
  544. );
  545. return static_cast<GLsizei> (quads.size () * 6);
  546. };
  547. m_glyphVertexCount = upload (m_result.quads, m_glyphPositions, m_glyphTexcoords);
  548. m_colorGlyphVertexCount = upload (m_result.colorQuads, m_colorGlyphPositions, m_colorGlyphTexcoords);
  549. // the opaque background covers the text box plus padding (sub_140258050)
  550. const glm::vec2 padding = this->currentPadding ();
  551. const float bx0 = m_result.minX - padding.x;
  552. const float by0 = m_result.bottom - padding.y;
  553. const float bx1 = m_result.maxX + padding.x;
  554. const float by1 = m_result.top + padding.y;
  555. const GLfloat background[]
  556. = { bx0, by1, 0.0f, bx0, by0, 0.0f, bx1, by1, 0.0f, bx1, by1, 0.0f, bx0, by0, 0.0f, bx1, by0, 0.0f };
  557. glBindBuffer (GL_ARRAY_BUFFER, m_backgroundPositions);
  558. glBufferData (GL_ARRAY_BUFFER, sizeof (background), background, GL_DYNAMIC_DRAW);
  559. // the effect buffer's composite quad, centered like the text box it holds
  560. const float hx = std::max (1.0f, static_cast<float> (m_passLayout.bufferSize.x)) * 0.5f;
  561. const float hy = std::max (1.0f, static_cast<float> (m_passLayout.bufferSize.y)) * 0.5f;
  562. const GLfloat composite[]
  563. = { -hx, -hy, 0.0f, -hx, hy, 0.0f, hx, -hy, 0.0f, hx, -hy, 0.0f, -hx, hy, 0.0f, hx, hy, 0.0f };
  564. glBindBuffer (GL_ARRAY_BUFFER, m_compositePosition);
  565. glBufferData (GL_ARRAY_BUFFER, sizeof (composite), composite, GL_DYNAMIC_DRAW);
  566. }
  567. // sub_1401B3B60: g_RenderVar0..3 of materials/fonts/font.frag in atlas pixels (32 per em), clamped like WE
  568. void CText::updateRenderVars () {
  569. const bool outline = m_text.outline->value->getBool ();
  570. const bool blur = m_text.blur->value->getBool ();
  571. const bool dropShadow = m_text.dropShadow->value->getBool ();
  572. const float thickness = m_text.outlineThickness->value->getFloat ();
  573. const float outlineWidth = outline ? (thickness <= 1.0f ? 1.0f : thickness) : 0.0f;
  574. const float blurRadius = blur ? std::max (m_text.blurSize->value->getFloat (), 0.01f) : 0.0f;
  575. const float shadowRadius = dropShadow ? std::max (m_text.dropShadowSize->value->getFloat (), 0.01f) : 0.0f;
  576. const glm::vec2 shadowOffset = dropShadow ? m_text.dropShadowOffset->value->getVec2 () : glm::vec2 (0.0f);
  577. const float toAtlas = 32.0f / m_params.size * 0.24f;
  578. constexpr float kMaxOutlineAndBlur = 5.1000004f;
  579. m_renderVars[0] = {
  580. 24.0f,
  581. std::min (kMaxOutlineAndBlur, toAtlas * outlineWidth),
  582. std::min (6.0f, toAtlas * blurRadius),
  583. std::min (6.0f, toAtlas * shadowRadius),
  584. };
  585. m_renderVars[1] = glm::vec4 (m_text.outlineColor->value->getVec3 (), std::min (6.0f, toAtlas * shadowOffset.x));
  586. m_renderVars[2] = glm::vec4 (m_text.dropShadowColor->value->getVec3 (), std::min (6.0f, toAtlas * shadowOffset.y));
  587. m_renderVars[3] = { m_text.dropShadowOpacity->value->getFloat (), 0.0f, 0.0f, 0.0f };
  588. if (m_renderVars[0].z + m_renderVars[0].y > kMaxOutlineAndBlur) {
  589. m_renderVars[0].y = std::max (kMaxOutlineAndBlur - m_renderVars[0].z, 0.0f);
  590. }
  591. }
  592. CPass* CText::createFontPass (const std::shared_ptr<const CFBO>& destination, const glm::mat4* mvp, bool color) {
  593. const Material& material = color ? *m_colorFontMaterial : *m_fontMaterial;
  594. auto* pass = new CPass (
  595. *this, std::make_shared<FBOProvider> (this), **material.passes.begin (), m_fontOverride, std::nullopt,
  596. std::nullopt
  597. );
  598. pass->setDestination (destination);
  599. pass->setInput (color ? m_colorAtlas : m_atlas);
  600. pass->setPosition (color ? m_colorGlyphPositions : m_glyphPositions);
  601. pass->setTexCoord (color ? m_colorGlyphTexcoords : m_glyphTexcoords);
  602. pass->setModelMatrix (&m_modelMatrix);
  603. pass->setViewProjectionMatrix (&m_viewProjectionMatrix);
  604. pass->setModelViewProjectionMatrix (mvp);
  605. pass->setModelViewProjectionMatrixInverse (mvp);
  606. if (color) {
  607. // sub_1401B3430: the MSDF colour material samples the colours from g_Texture1 (the atlas' +48 texture)
  608. if (m_passLayout.msdf) {
  609. pass->setTexture (1, m_colorTexture);
  610. }
  611. pass->setGeometryCallback (
  612. nullptr, [this] () { glDrawArrays (GL_TRIANGLES, 0, m_colorGlyphVertexCount); }, nullptr
  613. );
  614. } else {
  615. pass->setGeometryCallback (nullptr, [this] () { glDrawArrays (GL_TRIANGLES, 0, m_glyphVertexCount); }, nullptr);
  616. }
  617. for (int i = 0; i < 4; i++) {
  618. pass->addUniform ("g_RenderVar" + std::to_string (i), &m_renderVars[i]);
  619. }
  620. return pass;
  621. }
  622. void CText::buildPasses () {
  623. this->destroyPasses ();
  624. const auto& project = this->getScene ().getScene ().project;
  625. const PassLayout& layout = m_passLayout;
  626. // sub_1401B3430 picks the material by atlas kind and the depth flag (params +25), colour glyphs get the rgba
  627. // variants; the effect combos come from sub_1401B3B60
  628. const std::string depthSuffix = layout.depth ? "_depth" : "";
  629. const std::string msdfSuffix = layout.msdf ? "_msdf" : "";
  630. try {
  631. m_fontMaterial
  632. = MaterialParser::load (project, "materials/fonts/basefont" + msdfSuffix + depthSuffix + ".json");
  633. m_colorFontMaterial = layout.color
  634. ? MaterialParser::load (project, "materials/fonts/basefontrgba" + msdfSuffix + depthSuffix + ".json")
  635. : nullptr;
  636. m_backgroundMaterial = layout.background
  637. ? MaterialParser::load (project, "materials/fonts/fontbackground" + depthSuffix + ".json")
  638. : nullptr;
  639. m_clearAlphaMaterial = layout.buffered && !layout.background
  640. ? MaterialParser::load (project, "materials/util/composelayer_clearalpha.json")
  641. : nullptr;
  642. // scenes from version 3 on composite with genericimage4, the one with fog (sub_140257840)
  643. m_passthroughMaterial = layout.buffered
  644. && ((layout.blendMode != 0 && layout.blendMode != 31) || this->getScene ().hasDistanceFog ()
  645. || this->getScene ().hasHeightFog ())
  646. ? MaterialParser::load (
  647. project,
  648. project.sceneVersion >= 3 ? "materials/util/effectpassthrough_4.json"
  649. : "materials/util/effectpassthrough.json"
  650. )
  651. : nullptr;
  652. } catch (const std::exception& e) {
  653. sLog.error ("CText: cannot load the font materials for ", m_text.name, ": ", e.what ());
  654. return;
  655. }
  656. // sub_140257840: in 3D scenes the composite's material gets depthtest "enabled" unless the text disables it
  657. if (m_passthroughMaterial != nullptr && layout.depth) {
  658. for (const auto& pass : m_passthroughMaterial->passes) {
  659. pass->depthtest = DepthtestMode_Enabled;
  660. }
  661. }
  662. m_compositePassCount = 0;
  663. m_fontOverride.combos.clear ();
  664. if (layout.outline) {
  665. m_fontOverride.combos.emplace ("OUTLINE_ENABLED", 1);
  666. }
  667. if (layout.blur) {
  668. m_fontOverride.combos.emplace ("BLUR_ENABLED", 1);
  669. }
  670. if (layout.dropShadow) {
  671. m_fontOverride.combos.emplace ("DROP_SHADOW_ENABLED", 1);
  672. }
  673. if (!layout.buffered) {
  674. // no effects: background and glyphs go straight into the scene like sub_140258050
  675. if (m_backgroundMaterial != nullptr) {
  676. auto* background = new CPass (
  677. *this, std::make_shared<FBOProvider> (this), **m_backgroundMaterial->passes.begin (), std::nullopt,
  678. std::nullopt, std::nullopt
  679. );
  680. background->setDestination (this->getScene ().getFBO ());
  681. // the flat shader samples nothing, but passes without an input are skipped
  682. background->setInput (m_atlas);
  683. background->setPosition (m_backgroundPositions);
  684. background->setTexCoord (m_quadTexcoords);
  685. background->setModelMatrix (&m_modelMatrix);
  686. background->setViewProjectionMatrix (&m_viewProjectionMatrix);
  687. background->setModelViewProjectionMatrix (&m_glyphSceneMatrix);
  688. background->setModelViewProjectionMatrixInverse (&m_glyphSceneMatrixInverse);
  689. background->addUniform ("g_Color", &m_backgroundColor);
  690. background->addUniform ("g_Alpha", &m_backgroundAlpha);
  691. background->addUniform ("g_Color4", &m_backgroundColor4);
  692. // colorBlendMode 31 draws the text and its background additively (sub_140258050)
  693. if (layout.blendMode == 31) {
  694. background->setBlendingMode (BlendingMode_Additive);
  695. }
  696. m_passes.push_back (background);
  697. }
  698. auto* glyphs = this->createFontPass (this->getScene ().getFBO (), &m_glyphSceneMatrix, false);
  699. if (layout.blendMode == 31) {
  700. glyphs->setBlendingMode (BlendingMode_Additive);
  701. }
  702. m_passes.push_back (glyphs);
  703. // sub_1401B3430 draws the colour glyphs' buffer after the others
  704. if (layout.color) {
  705. auto* colorGlyphs = this->createFontPass (this->getScene ().getFBO (), &m_glyphSceneMatrix, true);
  706. if (layout.blendMode == 31) {
  707. colorGlyphs->setBlendingMode (BlendingMode_Additive);
  708. }
  709. m_passes.push_back (colorGlyphs);
  710. }
  711. return;
  712. }
  713. if (layout.bufferSize.x <= 0 || layout.bufferSize.y <= 0) {
  714. return;
  715. }
  716. const glm::vec2 fboSize = { static_cast<float> (layout.bufferSize.x), static_cast<float> (layout.bufferSize.y) };
  717. // the same buffer setup as image layers (text and image vtables share slot 23, sub_1401EA500): scene buffers named
  718. // _rt_imageLayerComposite_<id>_a/_b, which layers depending on the text sample, 16 bit float in HDR scene
  719. // rendering. They keep their identity when the text box changes size, whoever resolved them keeps a working buffer
  720. const TextureFormat format = this->getScene ().isHDR () ? TextureFormat_RGBA16161616f : TextureFormat_ARGB8888;
  721. const auto sceneBuffer = [this, format, fboSize] (const std::string& suffix) {
  722. auto& scene = this->getScene ();
  723. const std::string name = "_rt_imageLayerComposite_" + std::to_string (this->getId ()) + suffix;
  724. if (auto existing = scene.find (name); existing != nullptr && existing->getFormat () == format) {
  725. existing->resize (static_cast<uint32_t> (fboSize.x), static_cast<uint32_t> (fboSize.y));
  726. return existing;
  727. }
  728. return scene.create (name, format, TextureFlags_ClampUVs, 1.0f, fboSize, fboSize);
  729. };
  730. this->m_currentMainFBO = this->m_mainFBO = sceneBuffer ("_a");
  731. this->m_currentSubFBO = this->m_subFBO = sceneBuffer ("_b");
  732. // sub_140257C30: the buffer starts out as the opaque background, or as the scene behind the text with alpha 0
  733. // (composelayer_clearalpha), so the glyphs' translucent edges blend towards what they will be drawn over
  734. auto* base = this->createFontPass (m_currentMainFBO, &m_glyphBufferMatrix, false);
  735. if (layout.background) {
  736. base->setClearColor (&m_backgroundColor4);
  737. } else if (m_clearAlphaMaterial != nullptr) {
  738. auto* clear = new CPass (
  739. *this, std::make_shared<FBOProvider> (this), **m_clearAlphaMaterial->passes.begin (), std::nullopt,
  740. std::nullopt, std::nullopt
  741. );
  742. clear->setDestination (m_currentMainFBO);
  743. clear->setInput (this->getScene ().getFBO ());
  744. clear->setPosition (m_compositePosition);
  745. clear->setTexCoord (m_compositeTexcoords);
  746. clear->setModelMatrix (&m_modelMatrix);
  747. clear->setViewProjectionMatrix (&m_viewProjectionMatrix);
  748. clear->setModelViewProjectionMatrix (&m_compositeMatrix);
  749. clear->setModelViewProjectionMatrixInverse (&m_compositeMatrixInverse);
  750. // under a passthrough layer WE samples its scene copy through the layer's matrices, at the text's place in
  751. // the layer buffer
  752. clear->setFollowLayerTarget (true);
  753. m_passes.push_back (clear);
  754. base->setKeepDestination (true);
  755. }
  756. m_passes.push_back (base);
  757. if (layout.color) {
  758. auto* colorGlyphs = this->createFontPass (m_currentMainFBO, &m_glyphBufferMatrix, true);
  759. colorGlyphs->setKeepDestination (true);
  760. m_passes.push_back (colorGlyphs);
  761. }
  762. std::shared_ptr<const TextureProvider> asInput = m_currentMainFBO;
  763. for (const auto& effect : m_text.effects) {
  764. if (!effect->visible->value->getBool ()) {
  765. continue;
  766. }
  767. const auto fboProvider = std::make_shared<FBOProvider> (this);
  768. std::vector<std::shared_ptr<CFBO>> buffers;
  769. for (const auto& fbo : effect->effect->fbos) {
  770. buffers.push_back (fboProvider->create (*fbo, TextureFlags_ClampUVs, fboSize));
  771. }
  772. this->registerEffectBuffers (*effect, std::move (buffers));
  773. auto curOverride = effect->passOverrides.begin ();
  774. const auto endOverride = effect->passOverrides.end ();
  775. // same target/previous bookkeeping as CImage::setupPasses
  776. bool inTargetSequence = false;
  777. std::shared_ptr<const TextureProvider> sequenceInput = nullptr;
  778. for (const auto& effectPass : effect->effect->passes) {
  779. if (!effectPass->material.has_value ()) {
  780. // command-only passes (e.g. plain FBO copies) aren't supported for text
  781. continue;
  782. }
  783. for (auto& matPass : effectPass->material.value ()->passes) {
  784. const auto override = curOverride != endOverride
  785. ? **curOverride
  786. : std::optional<std::reference_wrapper<const ImageEffectPassOverride>> (std::nullopt);
  787. const auto target = effectPass->target.has_value ()
  788. ? *effectPass->target
  789. : std::optional<std::reference_wrapper<std::string>> (std::nullopt);
  790. auto* cpass = new CPass (*this, fboProvider, *matPass, override, effectPass->binds, target);
  791. std::shared_ptr<const CFBO> drawTo = this->m_currentSubFBO;
  792. bool writesToTarget = false;
  793. if (target.has_value ()) {
  794. std::shared_ptr<const CFBO> resolved = fboProvider->find (target->get ());
  795. if (resolved == nullptr) {
  796. resolved = this->getScene ().findFBO (target->get ());
  797. }
  798. if (resolved != nullptr) {
  799. if (!inTargetSequence) {
  800. sequenceInput = asInput;
  801. inTargetSequence = true;
  802. }
  803. drawTo = resolved;
  804. writesToTarget = true;
  805. } else {
  806. sLog.error (
  807. "Text pass target FBO '", target->get (), "' could not be resolved for ", m_text.name
  808. );
  809. }
  810. }
  811. cpass->setDestination (drawTo);
  812. cpass->setInput (asInput);
  813. cpass->setPreviousInput (inTargetSequence ? sequenceInput : nullptr);
  814. cpass->setPosition (m_passSpacePosition);
  815. cpass->setTexCoord (m_quadTexcoords);
  816. cpass->setModelMatrix (&m_modelMatrix);
  817. cpass->setViewProjectionMatrix (&m_viewProjectionMatrix);
  818. cpass->setModelViewProjectionMatrix (&m_modelViewProjectionPass);
  819. cpass->setModelViewProjectionMatrixInverse (&m_modelViewProjectionPass);
  820. m_passes.push_back (cpass);
  821. asInput = drawTo;
  822. if (!writesToTarget) {
  823. std::swap (this->m_currentMainFBO, this->m_currentSubFBO);
  824. inTargetSequence = false;
  825. sequenceInput = nullptr;
  826. }
  827. }
  828. if (curOverride != endOverride) {
  829. ++curOverride;
  830. }
  831. }
  832. }
  833. // final pass: composite the accumulated result onto the actual scene. With a blend mode that is WE's
  834. // effectpassthrough material with BLENDMODE (sub_140257840), drawn translucent in white at full alpha
  835. // (sub_1401E8AA0); colorBlendMode 31 is a plain additive composite
  836. m_passthroughOverride.combos.clear ();
  837. if (m_passthroughMaterial != nullptr) {
  838. m_passthroughOverride.combos.emplace ("BLENDMODE", layout.blendMode == 31 ? 0 : layout.blendMode);
  839. m_passthroughOverride.combos.emplace ("FOG_COMPUTED", 1);
  840. }
  841. const Material& finalMaterial = m_passthroughMaterial != nullptr ? *m_passthroughMaterial : compositeMaterial ();
  842. for (const auto& pass : finalMaterial.passes) {
  843. auto* cpass = m_passthroughMaterial != nullptr
  844. ? new CPass (
  845. *this, std::make_shared<FBOProvider> (this), *pass, m_passthroughOverride, std::nullopt, std::nullopt
  846. )
  847. : new CPass (*this, std::make_shared<FBOProvider> (this), *pass, std::nullopt, std::nullopt, std::nullopt);
  848. if (m_passthroughMaterial != nullptr) {
  849. cpass->setBlendingMode (BlendingMode_Translucent);
  850. cpass->addUniform ("g_Color4", &m_white);
  851. cpass->addUniform ("g_EyePosition", &this->getScene ().getFog ().eyeLocal);
  852. } else if (layout.blendMode == 31) {
  853. cpass->setBlendingMode (BlendingMode_Additive);
  854. }
  855. cpass->setDestination (this->getScene ().getFBO ());
  856. cpass->setInput (asInput);
  857. cpass->setPosition (m_compositePosition);
  858. cpass->setTexCoord (m_compositeTexcoords);
  859. // the fog of the composite measures where the text is in the scene
  860. cpass->setModelMatrix (m_passthroughMaterial != nullptr ? &m_compositeModel : &m_modelMatrix);
  861. cpass->setViewProjectionMatrix (&m_viewProjectionMatrix);
  862. cpass->setModelViewProjectionMatrix (&m_compositeMatrix);
  863. cpass->setModelViewProjectionMatrixInverse (&m_compositeMatrixInverse);
  864. m_passes.push_back (cpass);
  865. m_compositePassCount++;
  866. }
  867. }
  868. void CText::render () {
  869. if (!m_initialized) {
  870. return;
  871. }
  872. const auto& appContext = this->getScene ().getContext ().getApp ().getContext ();
  873. const auto visibility = appContext.resolveObjectVisibility (this->getId (), this->getObject ().name);
  874. const bool visible = visibility.value_or (m_text.visible->value->getBool ());
  875. // like images, a hidden text other layers depend on still fills its buffer, only the composite is left out
  876. if (!visible && (visibility.has_value () || !m_isDependency)) {
  877. return;
  878. }
  879. std::string renderedText = m_lastRenderedText;
  880. if (m_layerHandle != Scripting::kInvalidLayerHandle) {
  881. auto& se = this->getScene ().getScriptEngine ();
  882. se.tickLayer (
  883. m_layerHandle, static_cast<double> (getScene ().getTime ()),
  884. static_cast<double> (getScene ().getDeltaTime ()), static_cast<double> (getScene ().getFps ())
  885. );
  886. const std::string current = se.layerText (m_layerHandle);
  887. renderedText = current.empty () ? std::string (" ") : current;
  888. } else {
  889. // other scripts can write layer.text too
  890. const std::string current = m_text.text->value->getString ();
  891. renderedText = current.empty () ? std::string (" ") : current;
  892. }
  893. const std::string& requestedFont = m_font.getString ().empty () ? m_text.font : m_font.getString ();
  894. bool fontChanged = false;
  895. if (requestedFont != m_loadedFont) {
  896. m_loadedFont = requestedFont;
  897. fontChanged = true;
  898. if (!loadFont ()) {
  899. return;
  900. }
  901. }
  902. if (!m_layout.hasFont ()) {
  903. return;
  904. }
  905. // pointsize, spacing, wrapping and the glyph effects can all be bound to user properties or scripts
  906. if (fontChanged || renderedText != m_lastRenderedText || this->currentParams () != m_params) {
  907. this->relayout (renderedText);
  908. }
  909. const PassLayout passLayout = this->currentPassLayout ();
  910. if (passLayout != m_passLayout) {
  911. m_passLayout = passLayout;
  912. this->uploadGeometry ();
  913. this->buildPasses ();
  914. }
  915. if (!m_result.valid || m_passes.empty ()) {
  916. return;
  917. }
  918. this->updateRenderVars ();
  919. const float alpha = m_text.alpha->value->getFloat ();
  920. // backgroundbrightness only counts in WE's HDR scene rendering
  921. m_backgroundColor = m_text.backgroundColor->value->getVec3 ()
  922. * (this->getScene ().isHDR () ? m_text.backgroundBrightness->value->getFloat () : 1.0f);
  923. m_backgroundAlpha = alpha;
  924. m_backgroundColor4 = glm::vec4 (m_backgroundColor, alpha);
  925. this->updateTransform ();
  926. glColorMask (true, true, true, true);
  927. glDisable (GL_DEPTH_TEST);
  928. #if !NDEBUG
  929. std::string str = "Text " + this->getObject ().name + " (" + std::to_string (this->getId ()) + ")";
  930. glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, str.c_str ());
  931. #endif /* DEBUG */
  932. const size_t passCount
  933. = visible ? m_passes.size () : m_passes.size () - std::min (m_passes.size (), m_compositePassCount);
  934. for (size_t i = 0; i < passCount; i++) {
  935. m_passes[i]->render ();
  936. }
  937. #if !NDEBUG
  938. glPopDebugGroup ();
  939. #endif /* DEBUG */
  940. }
  941. glm::vec2 CText::alignmentAnchor () const {
  942. // sub_140256F20: the box is centered on the object, then moved by an anchor offset from the alignment
  943. // (y up): left/right put that edge on the origin, top puts the first line's ascender there, bottom the last
  944. // line's descender, center the middle between the first ascender and the last baseline
  945. const float boxWidth = m_result.maxX - m_result.minX;
  946. const float boxHeight = m_result.top - m_result.bottom;
  947. const float boxCenter = m_result.top - boxHeight * 0.5f;
  948. const float extraLines = static_cast<float> (m_result.lines - 1) * m_result.pitch;
  949. glm::vec2 anchor (0.0f);
  950. if (m_params.align == TextAlign::Left) {
  951. anchor.x = boxWidth * 0.5f;
  952. } else if (m_params.align == TextAlign::Right) {
  953. anchor.x = -boxWidth * 0.5f;
  954. }
  955. const std::string& verticalAlign = m_text.verticalAlign->value->getString ();
  956. if (verticalAlign == "bottom") {
  957. anchor.y = boxCenter - (m_result.descender - extraLines);
  958. } else if (verticalAlign == "top") {
  959. anchor.y = boxCenter - m_result.ascender;
  960. } else {
  961. anchor.y = boxCenter - (m_result.ascender - extraLines) * 0.5f;
  962. }
  963. return anchor;
  964. }
  965. glm::mat4 CText::worldMatrix () const {
  966. return glm::translate (getScene ().objectWorldMatrix (m_text), glm::vec3 (this->alignmentAnchor (), 0.0f));
  967. }
  968. void CText::updateTransform () {
  969. const glm::vec3 scale = m_text.scale->value->getVec3 ();
  970. // sub_140256E10: the text's world matrix is the object's full one (parents, all three angles) moved by the
  971. // alignment anchor in its own scaled and rotated space. The screen anchor goes on the matrix stack in front of it
  972. // (sub_1401E8AA0), in scene units
  973. const glm::vec2 screenAnchor = this->screenAnchorOffset ();
  974. const glm::mat4 world = glm::translate (glm::mat4 (1.0f), glm::vec3 (screenAnchor, 0.0f)) * this->worldMatrix ();
  975. const float boxWidth = m_result.maxX - m_result.minX;
  976. const float boxHeight = m_result.top - m_result.bottom;
  977. const auto& camera = getScene ().getCamera ();
  978. // layout space is y up, first baseline at 0; sub_140258050 centers the box: x - w/2 - min(minX, 0), y + h/2 - top
  979. const glm::vec3 center
  980. = { -boxWidth * 0.5f - std::min (m_result.minX, 0.0f), boxHeight * 0.5f - m_result.top, 0.0f };
  981. const glm::mat4 flipY = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f));
  982. // 3D scenes: the world matrix goes through the scene camera like models and image layers (sub_1401E8AA0),
  983. // "perspective" texts through the perspective layer camera. WE's camera parallax only exists in orthographic scenes
  984. if (camera.isPerspective ()) {
  985. const glm::mat4 viewProjection = m_text.perspective->value->getBool ()
  986. ? camera.getPerspectiveLayerViewProjection ()
  987. : getScene ().getWorldViewProjection ();
  988. m_glyphSceneMatrix = viewProjection * glm::translate (world, center);
  989. m_glyphSceneMatrixInverse = glm::inverse (m_glyphSceneMatrix);
  990. // the composite quad runs y down like in 2D
  991. m_compositeModel = world * flipY;
  992. m_compositeMatrix = viewProjection * m_compositeModel;
  993. m_compositeMatrixInverse = glm::inverse (m_compositeMatrix);
  994. this->updateBufferMatrix ();
  995. return;
  996. }
  997. // WE's world is y up from the bottom left, this space is centered and y down; the layout below is y up too
  998. const float scene_w = camera.getWidth ();
  999. const float scene_h = camera.getHeight ();
  1000. glm::mat4 model
  1001. = flipY * glm::translate (glm::mat4 (1.0f), glm::vec3 (-scene_w * 0.5f, -scene_h * 0.5f, 0.0f)) * world * flipY;
  1002. // Matches CImage's parallax handling (CImage.cpp:updateScreenSpacePosition): WE moves the view, so the offset
  1003. // lands outside the text's own rotation and scale
  1004. // CScene::renderFrame() already folds disableparallax into getParallaxDisplacement()
  1005. if (this->getScene ().getScene ().camera.parallax.enabled->value->getBool ()) {
  1006. glm::vec2 parallaxOffset = this->getScene ().getParallaxOffset (m_text);
  1007. // mirrors CImage's parallax clamp, or a text layer drifts past its edges while a same-depth
  1008. // CImage backing panel freezes, visibly separating the two
  1009. if (this->getScene ().getContext ().getApp ().getContext ().settings.mouse.clampParallaxToImageSize) {
  1010. const float scaledHalfWidth = boxWidth * 0.5f * scale.x;
  1011. const float scaledHalfHeight = boxHeight * 0.5f * scale.y;
  1012. const float baseX = model[3].x;
  1013. const float baseY = model[3].y;
  1014. const glm::vec4 visible = getScene ().getVisibleCanvasRegion ();
  1015. parallaxOffset.x = clampParallaxAxis (
  1016. parallaxOffset.x, baseX - scaledHalfWidth, baseX + scaledHalfWidth, visible.x, visible.y
  1017. );
  1018. parallaxOffset.y = clampParallaxAxis (
  1019. parallaxOffset.y, baseY - scaledHalfHeight, baseY + scaledHalfHeight, visible.z, visible.w
  1020. );
  1021. }
  1022. model = glm::translate (glm::mat4 (1.0f), glm::vec3 (parallaxOffset, 0.0f)) * model;
  1023. }
  1024. // "perspective" text gets the perspective layer camera (sub_14025FAF0 -> sub_1401E5B60)
  1025. const glm::mat4 viewProjection = m_text.perspective->value->getBool ()
  1026. ? camera.getPerspectiveLayerViewProjection ()
  1027. : camera.getProjection () * camera.getLookAt ();
  1028. m_glyphSceneMatrix = viewProjection * glm::translate (glm::scale (model, glm::vec3 (1.0f, -1.0f, 1.0f)), center);
  1029. m_glyphSceneMatrixInverse = glm::inverse (m_glyphSceneMatrix);
  1030. m_compositeMatrix = viewProjection * model;
  1031. m_compositeModel = model;
  1032. m_compositeMatrixInverse = glm::inverse (m_compositeMatrix);
  1033. this->updateBufferMatrix ();
  1034. }
  1035. void CText::updateBufferMatrix () {
  1036. if (m_passLayout.buffered) {
  1037. // sub_140257D70: inside the buffer the box starts at the padding, its top on the buffer's first row like any
  1038. // layer buffer (what dependent layers and orientation dependent effects sample)
  1039. const glm::vec2 padding = this->currentPadding ();
  1040. const glm::vec2 size = m_passLayout.bufferSize;
  1041. m_glyphBufferMatrix = glm::translate (
  1042. glm::ortho<float> (0.0f, size.x, size.y, 0.0f),
  1043. glm::vec3 (padding.x - std::min (m_result.minX, 0.0f), padding.y - m_result.bottom, 0.0f)
  1044. );
  1045. m_glyphBufferMatrixInverse = glm::inverse (m_glyphBufferMatrix);
  1046. }
  1047. }
  1048. bool CText::hitTest (const glm::vec2& ndc) {
  1049. if (!m_result.valid) {
  1050. return false;
  1051. }
  1052. this->updateTransform ();
  1053. // sub_14019DBB0 over the text's world matrix, size +752 (sub_140258900): the layout box, plus the padding on every
  1054. // side when the text goes through its buffer
  1055. glm::vec2 half = { (m_result.maxX - m_result.minX) * 0.5f, (m_result.top - m_result.bottom) * 0.5f };
  1056. if (m_passLayout.buffered) {
  1057. half += this->currentPadding ();
  1058. }
  1059. return Wallpapers::CScene::quadContainsPoint (m_compositeMatrix, half, ndc);
  1060. }
  1061. glm::vec2 CText::cursorLocalPosition (const glm::vec2& ndc) {
  1062. if (!m_result.valid) {
  1063. return glm::vec2 (0.0f);
  1064. }
  1065. this->updateTransform ();
  1066. glm::vec2 half = { (m_result.maxX - m_result.minX) * 0.5f, (m_result.top - m_result.bottom) * 0.5f };
  1067. if (m_passLayout.buffered) {
  1068. half += this->currentPadding ();
  1069. }
  1070. const auto point = Wallpapers::CScene::quadPlanePoint (m_compositeMatrix, ndc);
  1071. // the composite quad's y runs down, like the local position
  1072. return point.has_value () ? point.value () + half : glm::vec2 (0.0f);
  1073. }
  1074. const float& CText::getBrightness () const {
  1075. static constexpr float kUnitBrightness = 1.0f;
  1076. return kUnitBrightness;
  1077. }
  1078. const float& CText::getUserAlpha () const { return m_text.alpha->value->getFloat (); }
  1079. const float& CText::getAlpha () const { return m_text.alpha->value->getFloat (); }
  1080. const glm::vec3& CText::getColor () const {
  1081. // brightness only scales the color in HDR scene rendering (renderer flag 0x2000)
  1082. m_colorCache
  1083. = m_text.color->value->getVec3 () * (this->getScene ().isHDR () ? m_text.brightness->value->getFloat () : 1.0f);
  1084. return m_colorCache;
  1085. }
  1086. const glm::vec4& CText::getColor4 () const {
  1087. m_color4Cache = glm::vec4 (this->getColor (), m_text.alpha->value->getFloat ());
  1088. return m_color4Cache;
  1089. }
  1090. const glm::vec3& CText::getCompositeColor () const { return m_text.color->value->getVec3 (); }