main.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. #include <iostream>
  2. #include <getopt.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <SDL_mixer.h>
  6. #include <SDL.h>
  7. #include <FreeImage.h>
  8. #include <sys/stat.h>
  9. #include <GL/glew.h>
  10. #include <csignal>
  11. #include <GLFW/glfw3.h>
  12. #include <libgen.h>
  13. #include "WallpaperEngine/Core/CProject.h"
  14. #include "WallpaperEngine/Render/CWallpaper.h"
  15. #include "WallpaperEngine/Render/CContext.h"
  16. #include "WallpaperEngine/Render/CVideo.h"
  17. #include "WallpaperEngine/Assets/CPackage.h"
  18. #include "WallpaperEngine/Assets/CDirectory.h"
  19. #include "WallpaperEngine/Assets/CVirtualContainer.h"
  20. #include "WallpaperEngine/Assets/CCombinedContainer.h"
  21. #include "WallpaperEngine/Assets/CPackageLoadException.h"
  22. float g_Time;
  23. bool g_KeepRunning = true;
  24. int g_AudioVolume = 15;
  25. using namespace WallpaperEngine::Core::Types;
  26. const char* assets_default_paths [] = {
  27. ".steam/steam/steamapps/common/wallpaper_engine/assets",
  28. ".local/share/Steam/steamapps/common/wallpaper_engine/assets",
  29. nullptr
  30. };
  31. const char* backgrounds_default_paths [] = {
  32. ".local/share/Steam/steamapps/workshop/content/431960",
  33. nullptr
  34. };
  35. void print_help (const char* route)
  36. {
  37. std::cout
  38. << "Usage: " << route << " [options] background_path/background_id" << std::endl
  39. << std::endl
  40. << "where background_path/background_id can be:" << std::endl
  41. << "\tthe ID of the background (for autodetection on your steam installation)" << std::endl
  42. << "\ta full path to the background's folder" << std::endl
  43. << std::endl
  44. << "options:" << std::endl
  45. << " --silent\t\tMutes all the sound the wallpaper might produce" << std::endl
  46. << " --volume <amount>\tSets the volume for all the sounds in the background" << std::endl
  47. << " --screen-root <screen name>\tDisplay as screen's background" << std::endl
  48. << " --fps <maximum-fps>\tLimits the FPS to the given number, useful to keep battery consumption low" << std::endl
  49. << " --assets-dir <path>\tFolder where the assets are stored" << std::endl;
  50. }
  51. std::string stringPathFixes(const std::string& s)
  52. {
  53. if (s.empty () == true)
  54. return s;
  55. std::string str (s);
  56. // remove single-quotes from the arguments
  57. if (str [0] == '\'' && str [str.size() - 1] == '\'')
  58. str
  59. .erase (str.size() - 1, 1)
  60. .erase (0, 1);
  61. return std::move (str);
  62. }
  63. void signalhandler(int sig)
  64. {
  65. g_KeepRunning = false;
  66. }
  67. int validatePath(const char* path, std::string& final)
  68. {
  69. char finalPath [PATH_MAX];
  70. char* pointer = realpath (path, finalPath);
  71. if (finalPath == nullptr)
  72. return errno;
  73. // ensure the path points to a folder
  74. struct stat pathinfo;
  75. if (stat (finalPath, &pathinfo) != 0)
  76. return errno;
  77. if (!S_ISDIR (pathinfo.st_mode))
  78. return ENOTDIR;
  79. final = finalPath;
  80. return 0;
  81. }
  82. std::string getHomePath ()
  83. {
  84. char* home = getenv ("HOME");
  85. if (home == nullptr)
  86. throw std::runtime_error ("$HOME doesn't exist");
  87. std::string homepath;
  88. int error = validatePath (home, homepath);
  89. if (error == ENOTDIR)
  90. throw std::runtime_error ("Invalid user home path");
  91. else if (error == ENAMETOOLONG)
  92. throw std::runtime_error ("Cannot get user's home folder, path is too long");
  93. else if (error != 0)
  94. throw std::runtime_error ("Cannot find the home folder for the user");
  95. return homepath;
  96. }
  97. void initGLFW ()
  98. {
  99. // first of all, initialize the window
  100. if (glfwInit () == GLFW_FALSE)
  101. throw std::runtime_error ("Failed to initialize GLFW");
  102. // initialize freeimage
  103. FreeImage_Initialise (TRUE);
  104. // set some window hints (opengl version to be used)
  105. glfwWindowHint (GLFW_SAMPLES, 4);
  106. glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 2);
  107. glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 1);
  108. if (DEBUG)
  109. glfwWindowHint (GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
  110. }
  111. void addPkg (CCombinedContainer* containers, const std::string& path, std::string pkgfile)
  112. {
  113. try
  114. {
  115. std::string scene_path = path + pkgfile;
  116. // add the package to the list
  117. containers->add (new WallpaperEngine::Assets::CPackage (scene_path));
  118. std::cout << "Detected " << pkgfile << " file at " << scene_path << ". Adding to list of searchable paths" << std::endl;
  119. }
  120. catch (CPackageLoadException& ex)
  121. {
  122. // ignore this error, the package file was not found
  123. std::cout << "No " << pkgfile << " file found at " << path << ". Defaulting to normal folder storage" << std::endl;
  124. }
  125. catch (std::runtime_error& ex)
  126. {
  127. // the package was found but there was an error loading it (wrong header or something)
  128. fprintf (stderr, "Failed to load scene.pkg file: %s\n", ex.what());
  129. throw std::runtime_error ("Cannot load package file");
  130. }
  131. }
  132. CVirtualContainer* buildVirtualContainer ()
  133. {
  134. CVirtualContainer* container = new WallpaperEngine::Assets::CVirtualContainer ();
  135. //
  136. // Had to get a little creative with the effects to achieve the same bloom effect without any custom code
  137. // these virtual files are loaded by an image in the scene that takes current _rt_FullFrameBuffer and
  138. // applies the bloom effect to render it out to the screen
  139. //
  140. // add the effect file for screen bloom
  141. container->add (
  142. "effects/wpenginelinux/bloomeffect.json",
  143. "{"
  144. "\t\"name\":\"camerabloom_wpengine_linux\","
  145. "\t\"group\":\"wpengine_linux_camera\","
  146. "\t\"dependencies\":[],"
  147. "\t\"passes\":"
  148. "\t["
  149. "\t\t{"
  150. "\t\t\t\"material\": \"materials/util/downsample_quarter_bloom.json\","
  151. "\t\t\t\"target\": \"_rt_4FrameBuffer\","
  152. "\t\t\t\"bind\":"
  153. "\t\t\t["
  154. "\t\t\t\t{"
  155. "\t\t\t\t\t\"name\": \"_rt_FullFrameBuffer\","
  156. "\t\t\t\t\t\"index\": 0"
  157. "\t\t\t\t}"
  158. "\t\t\t]"
  159. "\t\t},"
  160. "\t\t{"
  161. "\t\t\t\"material\": \"materials/util/downsample_eighth_blur_v.json\","
  162. "\t\t\t\"target\": \"_rt_8FrameBuffer\","
  163. "\t\t\t\"bind\":"
  164. "\t\t\t["
  165. "\t\t\t\t{"
  166. "\t\t\t\t\t\"name\": \"_rt_4FrameBuffer\","
  167. "\t\t\t\t\t\"index\": 0"
  168. "\t\t\t\t}"
  169. "\t\t\t]"
  170. "\t\t},"
  171. "\t\t{"
  172. "\t\t\t\"material\": \"materials/util/blur_h_bloom.json\","
  173. "\t\t\t\"target\": \"_rt_Bloom\","
  174. "\t\t\t\"bind\":"
  175. "\t\t\t["
  176. "\t\t\t\t{"
  177. "\t\t\t\t\t\"name\": \"_rt_8FrameBuffer\","
  178. "\t\t\t\t\t\"index\": 0"
  179. "\t\t\t\t}"
  180. "\t\t\t]"
  181. "\t\t},"
  182. "\t\t{"
  183. "\t\t\t\"material\": \"materials/util/combine.json\","
  184. "\t\t\t\"target\": \"_rt_imageLayerComposite_-1_b\","
  185. "\t\t\t\"bind\":"
  186. "\t\t\t["
  187. "\t\t\t\t{"
  188. "\t\t\t\t\t\"name\": \"_rt_FullFrameBuffer\","
  189. "\t\t\t\t\t\"index\": 0"
  190. "\t\t\t\t},"
  191. "\t\t\t\t{"
  192. "\t\t\t\t\t\"name\": \"_rt_Bloom\","
  193. "\t\t\t\t\t\"index\": 1"
  194. "\t\t\t\t}"
  195. "\t\t\t]"
  196. "\t\t},"
  197. "\t\t{"
  198. "\t\t\t\"material\": \"materials/wpenginelinux.json\","
  199. "\t\t\t\"bind\":"
  200. "\t\t\t["
  201. "\t\t\t\t{"
  202. "\t\t\t\t\t\"name\": \"_rt_imageLayerComposite_-1_b\","
  203. "\t\t\t\t\t\"index\": 0"
  204. "\t\t\t\t}"
  205. "\t\t\t]"
  206. "\t\t}"
  207. "\t]"
  208. "}"
  209. );
  210. // add some model for the image element even if it's going to waste rendering cycles
  211. container->add (
  212. "models/wpenginelinux.json",
  213. "{"
  214. "\t\"material\":\"materials/wpenginelinux.json\""
  215. "}"
  216. );
  217. // models require materials, so add that too
  218. container->add (
  219. "materials/wpenginelinux.json",
  220. "{"
  221. "\t\"passes\":"
  222. "\t\t["
  223. "\t\t\t{"
  224. "\t\t\t\t\"blending\": \"normal\","
  225. "\t\t\t\t\"cullmode\": \"nocull\","
  226. "\t\t\t\t\"depthtest\": \"disabled\","
  227. "\t\t\t\t\"depthwrite\": \"disabled\","
  228. "\t\t\t\t\"shader\": \"genericimage2\","
  229. "\t\t\t\t\"textures\": [\"_rt_FullFrameBuffer\"]"
  230. "\t\t\t}"
  231. "\t\t]"
  232. "}"
  233. );
  234. return container;
  235. }
  236. int main (int argc, char* argv[])
  237. {
  238. std::vector <std::string> screens;
  239. int maximumFPS = 30;
  240. bool shouldEnableAudio = true;
  241. std::string path;
  242. std::string assetsDir;
  243. static struct option long_options [] = {
  244. {"screen-root", required_argument, 0, 'r'},
  245. {"pkg", required_argument, 0, 'p'},
  246. {"dir", required_argument, 0, 'd'},
  247. {"silent", no_argument, 0, 's'},
  248. {"volume", required_argument, 0, 'v'},
  249. {"help", no_argument, 0, 'h'},
  250. {"fps", required_argument, 0, 'f'},
  251. {"assets-dir", required_argument, 0, 'a'},
  252. {nullptr, 0, 0, 0}
  253. };
  254. while (true)
  255. {
  256. int c = getopt_long (argc, argv, "r:p:d:shf:a:", long_options, nullptr);
  257. if (c == -1)
  258. break;
  259. switch (c)
  260. {
  261. case 'r':
  262. screens.emplace_back (optarg);
  263. break;
  264. case 'p':
  265. case 'd':
  266. std::cerr << "--dir/--pkg is deprecated and not used anymore" << std::endl;
  267. path = stringPathFixes (optarg);
  268. break;
  269. case 's':
  270. shouldEnableAudio = false;
  271. break;
  272. case 'h':
  273. print_help (argv [0]);
  274. break;
  275. case 'f':
  276. maximumFPS = atoi (optarg);
  277. break;
  278. case 'a':
  279. assetsDir = optarg;
  280. break;
  281. case 'v':
  282. g_AudioVolume = atoi (optarg);
  283. break;
  284. }
  285. }
  286. if (path.empty () == true)
  287. {
  288. if (optind < argc && strlen (argv [optind]) > 0)
  289. {
  290. path = argv [optind];
  291. }
  292. else
  293. {
  294. print_help (argv [0]);
  295. return 0;
  296. }
  297. }
  298. // attach signals so if a stop is requested the X11 resources are freed and the program shutsdown gracefully
  299. std::signal(SIGINT, signalhandler);
  300. std::signal(SIGTERM, signalhandler);
  301. // initialize glfw
  302. initGLFW ();
  303. std::string homepath = getHomePath ();
  304. auto containers = new WallpaperEngine::Assets::CCombinedContainer ();
  305. // check if the background might be an ID and try to find the right path in the steam installation folder
  306. if (path.find ('/') == std::string::npos)
  307. {
  308. for (const char** current = backgrounds_default_paths; *current != nullptr; current ++)
  309. {
  310. std::string tmppath = homepath + "/" + *current + "/" + path;
  311. int error = validatePath (tmppath.c_str (), tmppath);
  312. if (error != 0)
  313. continue;
  314. path = tmppath;
  315. }
  316. }
  317. int error = validatePath (path.c_str (), path);
  318. if (error == ENOTDIR)
  319. throw std::runtime_error ("The background path is not a folder");
  320. else if (error == ENAMETOOLONG)
  321. throw std::runtime_error ("Cannot get wallpaper's folder, path is too long");
  322. else if (error != 0)
  323. throw std::runtime_error ("Cannot find the specified folder");
  324. // add a trailing slash to the path so the right file can be found
  325. path += "/";
  326. // the background's path is required to load project.json regardless of the type of background we're using
  327. containers->add (new WallpaperEngine::Assets::CDirectory (path));
  328. // add the virtual container for mocked up files
  329. containers->add (buildVirtualContainer ());
  330. // try to add the common packages
  331. addPkg (containers, path, "scene.pkg");
  332. addPkg (containers, path, "gifscene.pkg");
  333. if (assetsDir.empty () == true)
  334. {
  335. for (const char** current = assets_default_paths; *current != nullptr; current ++)
  336. {
  337. std::string tmppath = homepath + "/" + *current;
  338. error = validatePath (tmppath.c_str (), tmppath);
  339. if (error != 0)
  340. continue;
  341. assetsDir = tmppath;
  342. std::cout << "Found wallpaper engine's assets at " << assetsDir << std::endl;
  343. break;
  344. }
  345. if (assetsDir.empty () == true)
  346. {
  347. unsigned long len = strlen (argv [0]) + 1;
  348. char* copy = new char[len];
  349. strncpy (copy, argv [0], len);
  350. // path still not found, try one last thing on the current binary's folder
  351. std::string exepath = dirname (copy);
  352. exepath += "/assets";
  353. error = validatePath (exepath.c_str (), exepath);
  354. if (error == 0)
  355. {
  356. assetsDir = exepath;
  357. std::cout << "Found assets folder alongside the binary: " << assetsDir << std::endl;
  358. }
  359. delete[] copy;
  360. }
  361. }
  362. else
  363. {
  364. error = validatePath (assetsDir.c_str (), assetsDir);
  365. if (error == ENOTDIR)
  366. throw std::runtime_error ("Invalid assets folder");
  367. else if (error == ENAMETOOLONG)
  368. throw std::runtime_error ("Cannot get assets folder, path is too long");
  369. else if (error != 0)
  370. throw std::runtime_error ("Cannot find the specified assets folder");
  371. std::cout << "Found wallpaper engine's assets at " << assetsDir << " based on --assets-dir parameter" << std::endl;
  372. }
  373. if (assetsDir.empty () == true)
  374. throw std::runtime_error ("Cannot determine a valid path for the wallpaper engine assets");
  375. // add containers to the list
  376. containers->add (new WallpaperEngine::Assets::CDirectory (assetsDir + "/"));
  377. // auto projection = project->getWallpaper ()->as <WallpaperEngine::Core::CScene> ()->getOrthogonalProjection ();
  378. // create the window!
  379. // TODO: DO WE NEED TO PASS MONITOR HERE OR ANYTHING?
  380. // TODO: FIGURE OUT HOW TO PUT THIS WINDOW IN THE BACKGROUND
  381. GLFWwindow* window = glfwCreateWindow (1920, 1080, "WallpaperEngine", NULL, NULL);
  382. if (window == nullptr)
  383. {
  384. fprintf (stderr, "Failed to open a GLFW window");
  385. glfwTerminate ();
  386. return 2;
  387. }
  388. glfwMakeContextCurrent (window);
  389. // TODO: FIGURE THESE OUT BASED ON THE SCREEN
  390. int windowWidth = 1920;
  391. int windowHeight = 1080;
  392. // get the real framebuffer size
  393. glfwGetFramebufferSize (window, &windowWidth, &windowHeight);
  394. // initialize glew
  395. if (glewInit () != GLEW_OK)
  396. {
  397. fprintf (stderr, "Failed to initialize GLEW");
  398. glfwTerminate ();
  399. return 3;
  400. }
  401. if (shouldEnableAudio == true && SDL_Init (SDL_INIT_AUDIO) < 0)
  402. {
  403. std::cerr << "Cannot initialize SDL audio system, SDL_GetError: " << SDL_GetError() << std::endl;
  404. std::cerr << "Continuing without audio support" << std::endl;
  405. }
  406. // parse the project.json file
  407. auto project = WallpaperEngine::Core::CProject::fromFile ("project.json", containers);
  408. // go to the right folder so the videos will play
  409. if (project->getWallpaper ()->is <WallpaperEngine::Core::CVideo> () == true)
  410. chdir (path.c_str ());
  411. // initialize custom context class
  412. WallpaperEngine::Render::CContext* context = new WallpaperEngine::Render::CContext (screens, window, containers);
  413. // initialize mouse support
  414. context->setMouse (new CMouseInput (window));
  415. // set the default viewport
  416. context->setDefaultViewport ({0, 0, windowWidth, windowHeight});
  417. // ensure the context knows what wallpaper to render
  418. context->setWallpaper (
  419. WallpaperEngine::Render::CWallpaper::fromWallpaper (project->getWallpaper (), context)
  420. );
  421. // update maximum FPS if it's a video
  422. if (context->getWallpaper ()->is <WallpaperEngine::Render::CVideo> () == true)
  423. maximumFPS = context->getWallpaper ()->as <WallpaperEngine::Render::CVideo> ()->getFPS ();
  424. // TODO: FIGURE OUT THE REQUIRED INPUT MODE, AS SOME WALLPAPERS USE THINGS LIKE MOUSE POSITION
  425. // glfwSetInputMode (window, GLFW_STICKY_KEYS, GL_TRUE);
  426. double startTime, endTime, minimumTime = 1.0 / maximumFPS;
  427. while (glfwWindowShouldClose (window) == 0 && g_KeepRunning == true)
  428. {
  429. // get the real framebuffer size
  430. glfwGetFramebufferSize (window, &windowWidth, &windowHeight);
  431. // set the default viewport
  432. context->setDefaultViewport ({0, 0, windowWidth, windowHeight});
  433. // calculate the current time value
  434. g_Time = (float) glfwGetTime ();
  435. // get the start time of the frame
  436. startTime = glfwGetTime ();
  437. // render the scene
  438. context->render ();
  439. // do buffer swapping
  440. glfwSwapBuffers (window);
  441. // poll for events (like closing the window)
  442. glfwPollEvents ();
  443. // get the end time of the frame
  444. endTime = glfwGetTime ();
  445. // ensure the frame time is correct to not overrun FPS
  446. if ((endTime - startTime) < minimumTime)
  447. usleep ((minimumTime - (endTime - startTime)) * CLOCKS_PER_SEC);
  448. }
  449. // ensure this is updated as sometimes it might not come from a signal
  450. g_KeepRunning = false;
  451. std::cout << "Stop requested" << std::endl;
  452. // terminate gl
  453. glfwTerminate ();
  454. // terminate free image
  455. FreeImage_DeInitialise ();
  456. // terminate SDL
  457. SDL_QuitSubSystem(SDL_INIT_AUDIO);
  458. SDL_Quit ();
  459. // free context
  460. delete context;
  461. return 0;
  462. }