ObjectParser.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. #include "ObjectParser.h"
  2. #include "EffectParser.h"
  3. #include "MaterialParser.h"
  4. #include "ModelParser.h"
  5. #include "ShaderConstantParser.h"
  6. #include "TextureParser.h"
  7. #include "UserSettingParser.h"
  8. #include "WallpaperEngine/Data/Builders/ColorBuilder.h"
  9. #include "WallpaperEngine/Data/Model/Object.h"
  10. #include "WallpaperEngine/Data/Model/Project.h"
  11. #include "WallpaperEngine/Logging/Log.h"
  12. #include <glm/gtc/constants.hpp>
  13. #include <sstream>
  14. using namespace WallpaperEngine::Data::Parsers;
  15. using namespace WallpaperEngine::Data::Model;
  16. ObjectUniquePtr ObjectParser::parse (const JSON& it, const Project& project) {
  17. const auto imageIt = it.find ("image");
  18. const auto soundIt = it.find ("sound");
  19. const auto particleIt = it.find ("particle");
  20. const auto textIt = it.find ("text");
  21. const auto lightIt = it.find ("light");
  22. // use shape to refer to VolumeLight
  23. const auto shapeIt = it.find ("shape");
  24. // Parse base object data
  25. // Some particle objects have numeric 'name' fields, so handle type mismatches gracefully
  26. ObjectData basedata;
  27. try {
  28. basedata = ObjectData {
  29. .id = it.require<int> ("id", "Object must have an id"),
  30. .name = it.require<std::string> ("name", "Object must have a name"),
  31. .dependencies = parseDependencies (it),
  32. .parent = it.optional<int> ("parent"),
  33. .origin = it.user ("origin", project.properties, glm::vec3 (0.0f)),
  34. .groupScale = it.user ("scale", project.properties, glm::vec3 (1.0f)),
  35. .groupAngles = it.user ("angles", project.properties, glm::vec3 (0.0f)),
  36. .groupVisible = it.user ("visible", project.properties, true),
  37. };
  38. } catch (const std::exception& e) {
  39. sLog.error ("Error parsing object base data: ", e.what ());
  40. const auto idIt = it.find ("id");
  41. const auto nameIt = it.find ("name");
  42. int id = (idIt != it.end () && idIt->is_number ()) ? idIt->get<int> () : -1;
  43. std::string name = "unknown";
  44. if (nameIt != it.end ()) {
  45. if (nameIt->is_string ()) {
  46. name = nameIt->get<std::string> ();
  47. } else if (nameIt->is_number ()) {
  48. name = std::to_string (nameIt->get<int> ());
  49. }
  50. }
  51. basedata = ObjectData {
  52. .id = id,
  53. .name = name,
  54. .dependencies = parseDependencies (it),
  55. .parent = it.optional<int> ("parent"),
  56. .origin = it.user ("origin", project.properties, glm::vec3 (0.0f)),
  57. .groupScale = it.user ("scale", project.properties, glm::vec3 (1.0f)),
  58. .groupAngles = it.user ("angles", project.properties, glm::vec3 (0.0f)),
  59. .groupVisible = it.user ("visible", project.properties, true),
  60. };
  61. }
  62. if (imageIt != it.end () && imageIt->is_string ()) {
  63. return parseImage (it, project, std::move (basedata), *imageIt);
  64. } else if (soundIt != it.end () && soundIt->is_array ()) {
  65. return parseSound (it, std::move (basedata));
  66. } else if (particleIt != it.end () && !particleIt->is_null ()) {
  67. return parseParticle (it, project, std::move (basedata));
  68. } else if (textIt != it.end () && !textIt->is_null ()) {
  69. return parseText (it, project, std::move (basedata));
  70. } else if (lightIt != it.end () && !lightIt->is_null ()) {
  71. sLog.error ("Light objects are not supported yet");
  72. } else if (shapeIt != it.end () && !shapeIt->is_null ()) {
  73. sLog.error ("VolumeLight objects are not supported yet");
  74. } else {
  75. if (!it.optional ("solid", false)) {
  76. // dump the object for now, might want to change later
  77. // TODO: RE-EVALUATE IF THIS MAKES SENSE, THERE'S OBJECTS THAT CONTAIN OTHER OBJECTS AND THUS AREN'T REALLY
  78. // ANYTHING SPECIAL
  79. sLog.error ("Unknown object type found: ", it.dump ());
  80. }
  81. }
  82. return std::make_unique<Object> (std::move (basedata));
  83. }
  84. std::vector<int> ObjectParser::parseDependencies (const JSON& it) {
  85. const auto dependenciesIt = it.find ("dependencies");
  86. if (dependenciesIt == it.end () || !dependenciesIt->is_array ()) {
  87. return {};
  88. }
  89. std::vector<int> result = {};
  90. for (const auto& cur : *dependenciesIt) {
  91. result.push_back (cur);
  92. }
  93. return result;
  94. }
  95. SoundUniquePtr ObjectParser::parseSound (const JSON& it, ObjectData base) {
  96. const auto soundIt = it.require ("sound", "Object must have a sound");
  97. std::vector<std::string> sounds = {};
  98. for (const auto& cur : soundIt) {
  99. sounds.push_back (cur);
  100. }
  101. return std::make_unique<Sound> (
  102. std::move (base),
  103. SoundData {
  104. .playbackmode = it.optional<std::string> ("playbackmode"),
  105. .sounds = sounds,
  106. }
  107. );
  108. }
  109. TextUniquePtr ObjectParser::parseText (const JSON& it, const Project& project, ObjectData base) {
  110. const auto& effects = it.optional ("effects");
  111. return std::make_unique<Text> (
  112. std::move (base),
  113. TextData {
  114. .text = it.user ("text", project.properties),
  115. .font = it.optional ("font", std::string ()),
  116. .pointSize = it.user ("pointsize", project.properties, 32.0f),
  117. .size = it.optional ("size", glm::vec2 (0.0f)),
  118. .scale = it.user ("scale", project.properties, glm::vec3 (1.0f)),
  119. .color = it.color ("color", project.properties, Builders::ColorBuilder::White),
  120. .alpha = it.user ("alpha", project.properties, 1.0f),
  121. .visible = it.user ("visible", project.properties, true),
  122. .alignment = it.optional ("horizontalalign", it.optional ("alignment", std::string ("center"))),
  123. .verticalalign = it.optional ("verticalalign", std::string ("center")),
  124. .padding = it.optional ("padding", 0),
  125. .effects = effects.has_value () ? parseEffects (*effects, project) : std::vector<ImageEffectUniquePtr> {},
  126. }
  127. );
  128. }
  129. ImageUniquePtr
  130. ObjectParser::parseImage (const JSON& it, const Project& project, ObjectData base, const std::string& image) {
  131. const auto& properties = project.properties;
  132. const auto& effects = it.optional ("effects");
  133. const auto& animationLayers = it.optional ("animationlayers");
  134. auto result = std::make_unique<Image> (
  135. std::move (base),
  136. ImageData {
  137. .scale = it.user ("scale", properties, glm::vec3 (1.0f)),
  138. .angles = it.user ("angles", properties, glm::vec3 (0.0f)),
  139. .visible = it.user ("visible", properties, true),
  140. .alpha = it.user ("alpha", properties, 1.0f),
  141. .color = it.color ("color", properties, Builders::ColorBuilder::White),
  142. .alignment = it.optional ("horizontalalign", it.optional ("alignment", std::string ("center"))),
  143. .size = it.user ("size", properties, glm::vec2 (0.0f))->value->getVec2 (),
  144. .parallaxDepth = it.user ("parallaxDepth", properties, glm::vec2 (0.0f)),
  145. .colorBlendMode = it.user ("colorBlendMode", properties, 0),
  146. .brightness = it.user ("brightness", properties, 1.0f),
  147. .model = ModelParser::load (project, image),
  148. .effects = effects.has_value () ? parseEffects (*effects, project) : std::vector<ImageEffectUniquePtr> {},
  149. .animationLayers = animationLayers.has_value () ? parseAnimationLayers (*animationLayers, project)
  150. : std::vector<ImageAnimationLayerUniquePtr> {},
  151. }
  152. );
  153. const auto instance = it.optional ("instance");
  154. if (instance.has_value () && instance->is_object () && !result->model->material->passes.empty ()) {
  155. auto& firstPass = **result->model->material->passes.begin ();
  156. const auto instanceTextures = instance->optional ("textures");
  157. if (instanceTextures.has_value ()) {
  158. const auto parsed = TextureParser::parseTextureMap (*instanceTextures);
  159. firstPass.textures.insert (parsed.begin (), parsed.end ());
  160. }
  161. const auto instanceUserTextures = instance->optional ("usertextures");
  162. if (instanceUserTextures.has_value ()) {
  163. const auto parsed = TextureParser::parseTextureMap (*instanceUserTextures);
  164. firstPass.usertextures.insert (parsed.begin (), parsed.end ());
  165. }
  166. }
  167. return result;
  168. }
  169. std::vector<ImageEffectUniquePtr> ObjectParser::parseEffects (const JSON& it, const Project& project) {
  170. if (!it.is_array ()) {
  171. return {};
  172. }
  173. std::vector<ImageEffectUniquePtr> result = {};
  174. for (const auto& cur : it) {
  175. result.push_back (parseEffect (cur, project));
  176. }
  177. return result;
  178. }
  179. ImageEffectUniquePtr ObjectParser::parseEffect (const JSON& it, const Project& project) {
  180. const auto& passsOverrides = it.optional ("passes");
  181. return std::make_unique<ImageEffect> (ImageEffect {
  182. .id = it.optional<int> ("id", -1),
  183. .name = it.optional<std::string> ("name", "Effect without name"),
  184. .visible = it.user ("visible", project.properties, true),
  185. .passOverrides = passsOverrides.has_value () ? parseEffectPassOverrides (passsOverrides.value (), project)
  186. : std::vector<ImageEffectPassOverrideUniquePtr> {},
  187. .effect = EffectParser::load (project, it.require ("file", "Image effect must have an effect")) });
  188. }
  189. std::vector<ImageEffectPassOverrideUniquePtr>
  190. ObjectParser::parseEffectPassOverrides (const JSON& it, const Project& project) {
  191. if (!it.is_array ()) {
  192. return {};
  193. }
  194. std::vector<ImageEffectPassOverrideUniquePtr> result = {};
  195. for (const auto& cur : it) {
  196. result.push_back (parseEffectPass (cur, project));
  197. }
  198. return result;
  199. }
  200. ImageEffectPassOverrideUniquePtr ObjectParser::parseEffectPass (const JSON& it, const Project& project) {
  201. const auto& combos = it.optional ("combos");
  202. const auto& textures = it.optional ("textures");
  203. const auto& constants = it.optional ("constantshadervalues");
  204. const auto& usertextures = it.optional ("usertextures");
  205. // TODO: PARSE CONSTANT SHADER VALUES AND FIND REFS?
  206. return std::make_unique<ImageEffectPassOverride> (ImageEffectPassOverride {
  207. .id = it.optional<int> ("id", -1),
  208. .combos = combos.has_value () ? parseComboMap (combos.value ()) : ComboMap {},
  209. .constants
  210. = constants.has_value () ? ShaderConstantParser::parse (constants.value (), project) : ShaderConstantMap {},
  211. .textures = textures.has_value () ? TextureParser::parseTextureMap (textures.value ()) : TextureMap {},
  212. .usertextures
  213. = usertextures.has_value () ? TextureParser::parseTextureMap (usertextures.value ()) : TextureMap {},
  214. });
  215. }
  216. ComboMap ObjectParser::parseComboMap (const JSON& it) {
  217. if (!it.is_object ()) {
  218. return {};
  219. }
  220. ComboMap result = {};
  221. for (const auto& cur : it.items ()) {
  222. result.emplace (cur.key (), cur.value ());
  223. }
  224. return result;
  225. }
  226. std::vector<ImageAnimationLayerUniquePtr> ObjectParser::parseAnimationLayers (const JSON& it, const Project& project) {
  227. if (!it.is_array ()) {
  228. return {};
  229. }
  230. std::vector<ImageAnimationLayerUniquePtr> result = {};
  231. for (const auto& cur : it.items ()) {
  232. result.push_back (parseAnimationLayer (cur.value (), project));
  233. }
  234. return result;
  235. }
  236. ImageAnimationLayerUniquePtr ObjectParser::parseAnimationLayer (const JSON& it, const Project& project) {
  237. const auto& properties = project.properties;
  238. return std::make_unique<ImageAnimationLayer> (ImageAnimationLayer {
  239. .id = it.require<int> ("id", "Animation layer must have an id"),
  240. .rate = it.user ("rate", properties, 1.0f),
  241. .visible = it.user ("visible", properties, false),
  242. .blend = it.user ("blend", properties, 1.0f),
  243. .animation = it.user ("animation", properties, 0),
  244. });
  245. }
  246. ParticleUniquePtr ObjectParser::parseParticle (const JSON& it, const Project& project, ObjectData base) {
  247. try {
  248. const auto& properties = project.properties;
  249. const auto particleIt = it.find ("particle");
  250. if (particleIt == it.end ()) {
  251. sLog.error ("Particle object must have a particle definition");
  252. return std::make_unique<Particle> (
  253. std::move (base),
  254. ParticleData {
  255. .scale = it.user ("scale", properties, glm::vec3 (1.0f)),
  256. .angles = it.user ("angles", properties, glm::vec3 (0.0f)),
  257. .visible = it.user ("visible", properties, true),
  258. .parallaxDepth = it.user ("parallaxDepth", properties, glm::vec2 (0.0f)),
  259. .particleFile = "",
  260. .animationMode = "sequence",
  261. .sequenceMultiplier = 1.0f,
  262. .maxCount = 100,
  263. .startTime = 0,
  264. .flags = 0,
  265. .material = nullptr,
  266. .emitters = {},
  267. .initializers = {},
  268. .operators = {},
  269. .renderers = {},
  270. .controlPoints = {},
  271. .children = {},
  272. .instanceOverride = {
  273. .enabled = Builders::UserSettingBuilder::fromValue(false),
  274. .alpha = Builders::UserSettingBuilder::fromValue(1.0f),
  275. .size = Builders::UserSettingBuilder::fromValue(1.0f),
  276. .lifetime = Builders::UserSettingBuilder::fromValue(1.0f),
  277. .rate = Builders::UserSettingBuilder::fromValue(1.0f),
  278. .speed = Builders::UserSettingBuilder::fromValue(1.0f),
  279. .count = Builders::UserSettingBuilder::fromValue(1.0f),
  280. .color = Builders::UserSettingBuilder::fromValue(1.0f),
  281. .colorn = Builders::UserSettingBuilder::fromValue(1.0f),
  282. },
  283. }
  284. );
  285. }
  286. std::string particleFile;
  287. if (particleIt->is_string ()) {
  288. particleFile = particleIt->get<std::string> ();
  289. }
  290. // Load particle definition from file if it's a string reference
  291. JSON particleJson = JSON::object ();
  292. if (!particleFile.empty ()) {
  293. try {
  294. particleJson
  295. = WallpaperEngine::Data::JSON::JSON::parse (project.assetLocator->readString (particleFile));
  296. } catch (std::runtime_error& e) {
  297. sLog.error ("Cannot load particle file: ", particleFile, " - ", e.what ());
  298. }
  299. } else if (particleIt->is_object ()) {
  300. particleJson = *particleIt;
  301. }
  302. // Parse emitters (note: field is named "emitter" not "emitters")
  303. std::vector<ParticleEmitter> emitters;
  304. const auto emittersIt = particleJson.find ("emitter");
  305. if (emittersIt != particleJson.end () && emittersIt->is_array ()) {
  306. for (const auto& emitter : *emittersIt) {
  307. emitters.push_back (parseParticleEmitter (emitter));
  308. }
  309. }
  310. // Parse initializers (note: field is named "initializer" not "initializers")
  311. std::vector<ParticleInitializerUniquePtr> initializers;
  312. const auto initializersIt = particleJson.find ("initializer");
  313. if (initializersIt != particleJson.end () && initializersIt->is_array ()) {
  314. for (const auto& initializer : *initializersIt) {
  315. auto init = parseParticleInitializer (initializer, project.properties);
  316. if (init) {
  317. initializers.push_back (std::move (init));
  318. }
  319. }
  320. }
  321. // Parse operators (note: field is named "operator" not "operators")
  322. std::vector<ParticleOperatorUniquePtr> operators;
  323. const auto operatorsIt = particleJson.find ("operator");
  324. if (operatorsIt != particleJson.end () && operatorsIt->is_array ()) {
  325. for (const auto& op : *operatorsIt) {
  326. auto oper = parseParticleOperator (op, project.properties);
  327. if (oper) {
  328. operators.push_back (std::move (oper));
  329. }
  330. }
  331. }
  332. // Parse renderers (note: field is named "renderer" not "renderers")
  333. std::vector<ParticleRenderer> renderers;
  334. const auto renderersIt = particleJson.find ("renderer");
  335. if (renderersIt != particleJson.end () && renderersIt->is_array ()) {
  336. for (const auto& renderer : *renderersIt) {
  337. renderers.push_back (parseParticleRenderer (renderer));
  338. }
  339. }
  340. // Add default sprite renderer if none specified
  341. if (renderers.empty ()) {
  342. renderers.push_back (
  343. ParticleRenderer {
  344. .name = "sprite",
  345. .length = 0.05f,
  346. .maxLength = 10.0f,
  347. .minLength = 0.0f,
  348. .subdivision = 1.0f,
  349. .segments = 4.0f,
  350. .uvScale = 1.0f,
  351. .uvScrolling = false,
  352. .uvSmoothing = true,
  353. .fadeAlpha = false,
  354. .fadeSize = false,
  355. }
  356. );
  357. }
  358. // Parse control points (note: field is named "controlpoint" not "controlpoints")
  359. std::vector<ParticleControlPoint> controlPoints;
  360. const auto controlPointsIt = particleJson.find ("controlpoint");
  361. if (controlPointsIt != particleJson.end () && controlPointsIt->is_array ()) {
  362. for (const auto& cp : *controlPointsIt) {
  363. controlPoints.push_back (parseParticleControlPoint (cp));
  364. }
  365. }
  366. // Parse children
  367. std::vector<ParticleChild> children;
  368. const auto childrenIt = particleJson.optional ("children");
  369. if (childrenIt.has_value () && childrenIt->is_array ()) {
  370. for (const auto& child : *childrenIt) {
  371. children.push_back (parseParticleChild (child, project));
  372. }
  373. }
  374. // Parse instance override
  375. ParticleInstanceOverride instanceOverride = {
  376. .enabled = Builders::UserSettingBuilder::fromValue (false),
  377. .alpha = Builders::UserSettingBuilder::fromValue (1.0f),
  378. .size = Builders::UserSettingBuilder::fromValue (1.0f),
  379. .lifetime = Builders::UserSettingBuilder::fromValue (1.0f),
  380. .rate = Builders::UserSettingBuilder::fromValue (1.0f),
  381. .speed = Builders::UserSettingBuilder::fromValue (1.0f),
  382. .count = Builders::UserSettingBuilder::fromValue (1.0f),
  383. .color = Builders::UserSettingBuilder::fromValue (1.0f),
  384. .colorn = Builders::UserSettingBuilder::fromValue (1.0f),
  385. };
  386. const auto instanceOverrideIt = it.optional ("instanceoverride");
  387. if (instanceOverrideIt.has_value ()) {
  388. instanceOverride = parseParticleInstanceOverride (*instanceOverrideIt, project.properties);
  389. }
  390. // Parse material - particles reference materials directly, not models
  391. ModelUniquePtr material = nullptr;
  392. const auto materialIt = particleJson.find ("material");
  393. if (materialIt != particleJson.end () && materialIt->is_string ()) {
  394. try {
  395. std::string materialPath = materialIt->get<std::string> ();
  396. // Particle materials are stored as just material definitions, not model files
  397. // So we need to wrap them in a model structure
  398. auto mat = MaterialParser::load (project, materialPath);
  399. material = std::make_unique<ModelStruct> (ModelStruct {
  400. .filename = materialPath,
  401. .material = std::move (mat),
  402. .solidlayer = false,
  403. .fullscreen = false,
  404. .passthrough = false,
  405. .autosize = false,
  406. .nopadding = false,
  407. .width = std::nullopt,
  408. .height = std::nullopt,
  409. .puppet = std::nullopt,
  410. });
  411. } catch (std::runtime_error& e) {
  412. sLog.error ("Cannot load particle material: ", materialIt->get<std::string> (), " - ", e.what ());
  413. }
  414. }
  415. // Parse string fields safely
  416. std::string animationMode = "sequence";
  417. const auto animModeIt = particleJson.find ("animationmode");
  418. if (animModeIt != particleJson.end () && animModeIt->is_string ()) {
  419. animationMode = animModeIt->get<std::string> ();
  420. }
  421. // Parse numeric fields safely
  422. float sequenceMultiplier = 1.0f;
  423. uint32_t maxCount = 100;
  424. uint32_t startTime = 0;
  425. uint32_t flags = 0;
  426. const auto seqMultIt = particleJson.find ("sequencemultiplier");
  427. if (seqMultIt != particleJson.end () && seqMultIt->is_number ()) {
  428. sequenceMultiplier = seqMultIt->get<float> ();
  429. }
  430. const auto maxCountIt = particleJson.find ("maxcount");
  431. if (maxCountIt != particleJson.end () && maxCountIt->is_number ()) {
  432. maxCount = maxCountIt->get<uint32_t> ();
  433. }
  434. const auto startTimeIt = particleJson.find ("starttime");
  435. if (startTimeIt != particleJson.end () && startTimeIt->is_number ()) {
  436. startTime = startTimeIt->get<uint32_t> ();
  437. }
  438. const auto flagsIt = particleJson.find ("flags");
  439. if (flagsIt != particleJson.end () && flagsIt->is_number ()) {
  440. flags = flagsIt->get<uint32_t> ();
  441. }
  442. return std::make_unique<Particle> (
  443. std::move (base),
  444. ParticleData {
  445. .scale = it.user ("scale", properties, glm::vec3 (1.0f)),
  446. .angles = it.user ("angles", properties, glm::vec3 (0.0f)),
  447. .visible = it.user ("visible", properties, true),
  448. .parallaxDepth = it.user ("parallaxDepth", properties, glm::vec2 (0.0f)),
  449. .particleFile = particleFile,
  450. .animationMode = animationMode,
  451. .sequenceMultiplier = sequenceMultiplier,
  452. .maxCount = maxCount,
  453. .startTime = startTime,
  454. .flags = flags,
  455. .material = std::move (material),
  456. .emitters = std::move (emitters),
  457. .initializers = std::move (initializers),
  458. .operators = std::move (operators),
  459. .renderers = std::move (renderers),
  460. .controlPoints = std::move (controlPoints),
  461. .children = std::move (children),
  462. .instanceOverride = std::move (instanceOverride),
  463. }
  464. );
  465. } catch (nlohmann::json::exception& e) {
  466. sLog.error ("Error parsing particle '", base.name, "': ", e.what ());
  467. sLog.error ("Particle JSON: ", it.dump ());
  468. throw;
  469. }
  470. }
  471. ParticleEmitter ObjectParser::parseParticleEmitter (const JSON& it) {
  472. // Parse string name safely
  473. std::string name;
  474. const auto nameIt = it.find ("name");
  475. if (nameIt != it.end () && nameIt->is_string ()) {
  476. name = nameIt->get<std::string> ();
  477. }
  478. // Helper lambda to parse vec3 fields that might be strings, arrays, single numbers, or missing
  479. auto parseVec3 = [&] (const char* fieldName, const glm::vec3& defaultValue) -> glm::vec3 {
  480. const auto fieldIt = it.find (fieldName);
  481. if (fieldIt == it.end ()) {
  482. return defaultValue;
  483. }
  484. if (fieldIt->is_string ()) {
  485. return it.optional (fieldName, defaultValue);
  486. }
  487. if (fieldIt->is_number ()) {
  488. // Single number - use for all components (common for distancemax/distancemin)
  489. float val = fieldIt->get<float> ();
  490. return glm::vec3 (val, val, val);
  491. }
  492. if (fieldIt->is_array () && fieldIt->size () >= 3) {
  493. return glm::vec3 ((*fieldIt)[0].get<float> (), (*fieldIt)[1].get<float> (), (*fieldIt)[2].get<float> ());
  494. }
  495. return defaultValue;
  496. };
  497. auto parseIVec3 = [&] (const char* fieldName, const glm::ivec3& defaultValue) -> glm::ivec3 {
  498. const auto fieldIt = it.find (fieldName);
  499. if (fieldIt == it.end ()) {
  500. return defaultValue;
  501. }
  502. if (fieldIt->is_array () && fieldIt->size () >= 3) {
  503. return glm::ivec3 ((*fieldIt)[0].get<int> (), (*fieldIt)[1].get<int> (), (*fieldIt)[2].get<int> ());
  504. }
  505. return defaultValue;
  506. };
  507. auto parseVec2 = [&] (const char* fieldName, const glm::vec2& defaultValue) -> glm::vec2 {
  508. const auto fieldIt = it.find (fieldName);
  509. if (fieldIt == it.end ()) {
  510. return defaultValue;
  511. }
  512. if (fieldIt->is_string ()) {
  513. return it.optional (fieldName, defaultValue);
  514. }
  515. if (fieldIt->is_array () && fieldIt->size () >= 2) {
  516. return glm::vec2 ((*fieldIt)[0].get<float> (), (*fieldIt)[1].get<float> ());
  517. }
  518. return defaultValue;
  519. };
  520. try {
  521. return ParticleEmitter {
  522. .id = it.optional ("id", -1),
  523. .name = name,
  524. .directions = parseVec3 ("directions", glm::vec3 (1.0f, 1.0f, 0.0f)),
  525. .distanceMin = parseVec3 ("distancemin", glm::vec3 (0.0f, 0.0f, 0.0f)),
  526. .distanceMax = parseVec3 ("distancemax", glm::vec3 (256.0f, 256.0f, 0.0f)),
  527. .origin = parseVec3 ("origin", glm::vec3 (0.0f)),
  528. .sign = parseIVec3 ("sign", glm::ivec3 (0)),
  529. .instantaneous = it.optional ("instantaneous", 0u),
  530. .speedMin = it.optional ("speedmin", 0.0f),
  531. .speedMax = it.optional ("speedmax", 0.0f),
  532. .rate = it.optional ("rate", 10.0f),
  533. .controlPoint = it.optional ("controlpoint", 0),
  534. .flags = it.optional ("flags", 0u),
  535. .cone = it.optional ("cone", 0.0f),
  536. .delay = it.optional ("delay", 0.0f),
  537. .duration = it.optional ("duration", 0.0f),
  538. .audioProcessingBounds = parseVec2 ("audioprocessingbounds", glm::vec2 (0.8f, 1.0f)),
  539. .audioProcessingExponent = it.optional ("audioprocessingexponent", 2),
  540. .audioProcessingFrequencyStart = it.optional ("audioprocessingfrequencystart", 0),
  541. .audioProcessingFrequencyEnd = it.optional ("audioprocessingfrequencyend", 1),
  542. .audioProcessingMode = it.optional ("audioprocessingmode", 0),
  543. .minPeriodicDelay = it.optional ("minperiodicdelay", 1.0f),
  544. .maxPeriodicDelay = it.optional ("maxperiodicdelay", 2.0f),
  545. .minPeriodicDuration = it.optional ("minperiodicduration", 2.0f),
  546. .maxPeriodicDuration = it.optional ("maxperiodicduration", 3.0f),
  547. };
  548. } catch (nlohmann::json::exception& e) {
  549. sLog.error ("Error parsing emitter: ", e.what ());
  550. sLog.error ("Emitter JSON: ", it.dump ());
  551. throw;
  552. }
  553. }
  554. ParticleInitializerUniquePtr ObjectParser::parseParticleInitializer (const JSON& it, const Properties& properties) {
  555. std::string name = it.optional<std::string> ("name", "");
  556. if (name == "colorrandom") {
  557. return std::make_unique<ColorRandomInitializer> (
  558. it.color ("min", properties, Builders::ColorBuilder::Black),
  559. it.color ("max", properties, Builders::ColorBuilder::White)
  560. );
  561. } else if (name == "sizerandom") {
  562. return std::make_unique<SizeRandomInitializer> (
  563. it.user ("min", properties, 0.0f), it.user ("max", properties, 20.0f),
  564. it.user ("exponent", properties, 1.0f)
  565. );
  566. } else if (name == "alpharandom") {
  567. return std::make_unique<AlphaRandomInitializer> (
  568. it.user ("min", properties, 0.05f), it.user ("max", properties, 1.0f)
  569. );
  570. } else if (name == "lifetimerandom") {
  571. return std::make_unique<LifetimeRandomInitializer> (
  572. it.user ("min", properties, 0.0f), it.user ("max", properties, 1.0f)
  573. );
  574. } else if (name == "velocityrandom") {
  575. return std::make_unique<VelocityRandomInitializer> (
  576. it.user ("min", properties, glm::vec3 (-32.0f)), it.user ("max", properties, glm::vec3 (32.0f))
  577. );
  578. } else if (name == "rotationrandom") {
  579. return std::make_unique<RotationRandomInitializer> (
  580. it.user ("min", properties, glm::vec3 (0.0f)),
  581. it.user ("max", properties, glm::vec3 (0.0f, 0.0f, glm::two_pi<float> ()))
  582. );
  583. } else if (name == "angularvelocityrandom") {
  584. return std::make_unique<AngularVelocityRandomInitializer> (
  585. it.user ("min", properties, glm::vec3 (0.0f, 0.0f, -5.0f)),
  586. it.user ("max", properties, glm::vec3 (0.0f, 0.0f, 5.0f)), it.user ("exponent", properties, 1.0f)
  587. );
  588. } else if (name == "turbulentvelocityrandom") {
  589. return std::make_unique<TurbulentVelocityRandomInitializer> (
  590. it.user ("speedmin", properties, 100.0f), it.user ("speedmax", properties, 250.0f),
  591. it.user ("scale", properties, 1.0f), it.user ("offset", properties, 0.0f),
  592. it.user ("forward", properties, glm::vec3 (0.0f, 1.0f, 0.0f)), it.user ("timescale", properties, 1.0f),
  593. it.user ("phasemin", properties, 0.0f), it.user ("phasemax", properties, 0.1f),
  594. it.user ("right", properties, glm::vec3 (0.0f, 0.0f, 1.0f))
  595. );
  596. } else if (name == "mapsequencearoundcontrolpoint") {
  597. return std::make_unique<MapSequenceAroundControlPointInitializer> (
  598. it.user ("controlpoint", properties, 0), it.user ("count", properties, 1),
  599. it.user ("speedmin", properties, glm::vec3 (0.0f)), it.user ("speedmax", properties, glm::vec3 (100.0f))
  600. );
  601. }
  602. return nullptr;
  603. }
  604. ParticleOperatorUniquePtr ObjectParser::parseParticleOperator (const JSON& it, const Properties& properties) {
  605. std::string name = it.optional<std::string> ("name", "");
  606. if (name == "movement") {
  607. return std::make_unique<MovementOperator> (
  608. it.user ("drag", properties, 0.0f), it.user ("gravity", properties, glm::vec3 (0.0f))
  609. );
  610. } else if (name == "angularmovement") {
  611. return std::make_unique<AngularMovementOperator> (
  612. it.user ("drag", properties, 0.0f), it.user ("force", properties, glm::vec3 (0.0f))
  613. );
  614. } else if (name == "alphafade") {
  615. return std::make_unique<AlphaFadeOperator> (
  616. it.user ("fadeintime", properties, 0.5f), it.user ("fadeouttime", properties, 0.5f)
  617. );
  618. } else if (name == "sizechange") {
  619. return std::make_unique<SizeChangeOperator> (
  620. it.user ("starttime", properties, 0.0f), it.user ("endtime", properties, 1.0f),
  621. it.user ("startvalue", properties, 1.0f), it.user ("endvalue", properties, 0.0f)
  622. );
  623. } else if (name == "alphachange") {
  624. return std::make_unique<AlphaChangeOperator> (
  625. it.user ("starttime", properties, 0.0f), it.user ("endtime", properties, 1.0f),
  626. it.user ("startvalue", properties, 1.0f), it.user ("endvalue", properties, 0.0f)
  627. );
  628. } else if (name == "colorchange") {
  629. return std::make_unique<ColorChangeOperator> (
  630. it.user ("starttime", properties, 0.0f), it.user ("endtime", properties, 1.0f),
  631. it.user ("startvalue", properties, glm::vec3 (1.0f)), it.user ("endvalue", properties, glm::vec3 (1.0f))
  632. );
  633. } else if (name == "turbulence") {
  634. return std::make_unique<TurbulenceOperator> (
  635. it.user ("scale", properties, 0.005f), it.user ("speedmin", properties, 500.0f),
  636. it.user ("speedmax", properties, 1000.0f), it.user ("timescale", properties, 0.01f),
  637. it.user ("mask", properties, glm::vec3 (1.0f, 1.0f, 0.0f)), it.user ("phasemin", properties, 0.0f),
  638. it.user ("phasemax", properties, 0.0f), it.user ("audioprocessingmode", properties, 0),
  639. it.user ("audioprocessingbounds", properties, glm::vec2 (0.0f, 1.0f)),
  640. it.user ("audioprocessingexponent", properties, 1.0f),
  641. it.user ("audioprocessingfrequencystart", properties, 0),
  642. it.user ("audioprocessingfrequencyend", properties, 15)
  643. );
  644. } else if (name == "vortex" || name == "vortex_v2") {
  645. return std::make_unique<VortexOperator> (
  646. it.optional ("controlpoint", 0),
  647. it.optional ("flags", 0), // 1 = infinite axis, 2 = maintain distance, 4 = ring shape
  648. it.user ("axis", properties, glm::vec3 (0.0f, 0.0f, 1.0f)),
  649. it.user ("offset", properties, glm::vec3 (0.0f)), it.user ("distanceinner", properties, 500.0f),
  650. it.user ("distanceouter", properties, 650.0f), it.user ("speedinner", properties, 2500.0f),
  651. it.user ("speedouter", properties, 0.0f), it.user ("centerforce", properties, 1.0f),
  652. it.user ("ringradius", properties, 300.0f), it.user ("ringwidth", properties, 50.0f),
  653. it.user ("ringpulldistance", properties, 50.0f), it.user ("ringpullforce", properties, 10.0f),
  654. it.user ("audioprocessingmode", properties, 0),
  655. it.user ("audioprocessingbounds", properties, glm::vec2 (0.0f, 1.0f))
  656. );
  657. } else if (name == "controlpointattract") {
  658. return std::make_unique<ControlPointAttractOperator> (
  659. it.optional ("controlpoint", 0), it.user ("origin", properties, glm::vec3 (0.0f)),
  660. it.user ("scale", properties, 100.0f), it.user ("threshold", properties, 1000.0f)
  661. );
  662. } else if (name == "oscillatealpha") {
  663. return std::make_unique<OscillateAlphaOperator> (
  664. it.user ("frequencymin", properties, 0.0f), it.user ("frequencymax", properties, 10.0f),
  665. it.user ("scalemin", properties, 0.0f), it.user ("scalemax", properties, 1.0f),
  666. it.user ("phasemin", properties, 0.0f), it.user ("phasemax", properties, glm::two_pi<float> ())
  667. );
  668. } else if (name == "oscillatesize") {
  669. return std::make_unique<OscillateSizeOperator> (
  670. it.user ("frequencymin", properties, 0.0f), it.user ("frequencymax", properties, 10.0f),
  671. it.user ("scalemin", properties, 0.8f), it.user ("scalemax", properties, 1.2f),
  672. it.user ("phasemin", properties, 0.0f), it.user ("phasemax", properties, glm::two_pi<float> ())
  673. );
  674. } else if (name == "oscillateposition") {
  675. return std::make_unique<OscillatePositionOperator> (
  676. it.user ("frequencymin", properties, 0.0f), it.user ("frequencymax", properties, 5.0f),
  677. it.user ("scalemin", properties, 0.0f), it.user ("scalemax", properties, 10.0f),
  678. it.user ("phasemin", properties, 0.0f), it.user ("phasemax", properties, glm::two_pi<float> ()),
  679. it.user ("mask", properties, glm::vec3 (1.0f, 1.0f, 0.0f))
  680. );
  681. }
  682. return nullptr;
  683. }
  684. ParticleRenderer ObjectParser::parseParticleRenderer (const JSON& it) {
  685. std::string name = "sprite";
  686. const auto nameIt = it.find ("name");
  687. if (nameIt != it.end () && nameIt->is_string ()) {
  688. name = nameIt->get<std::string> ();
  689. }
  690. // Renderer-type-specific defaults
  691. float subdivisionDefault = (name == "rope") ? 4.0f : 1.0f;
  692. float lengthDefault = (name == "ropetrail") ? 1.0f : 0.05f;
  693. return ParticleRenderer {
  694. .name = name,
  695. .length = it.optional ("length", lengthDefault),
  696. .maxLength = it.optional ("maxlength", 10.0f),
  697. .minLength = it.optional ("minlength", 0.0f),
  698. .subdivision = it.optional ("subdivision", subdivisionDefault),
  699. .segments = it.optional ("segments", 4.0f),
  700. .uvScale = it.optional ("uvscale", 1.0f),
  701. .uvScrolling = it.optional ("uvscrolling", false),
  702. .uvSmoothing = it.optional ("uvsmoothing", true),
  703. .fadeAlpha = it.optional ("fadealpha", false),
  704. .fadeSize = it.optional ("fadesize", false),
  705. };
  706. }
  707. ParticleControlPoint ObjectParser::parseParticleControlPoint (const JSON& it) {
  708. // Parse offset - can be string "x y z" or array [x,y,z]
  709. glm::vec3 offset (0.0f);
  710. const auto offsetIt = it.find ("offset");
  711. if (offsetIt != it.end ()) {
  712. if (offsetIt->is_string ()) {
  713. // Parse string format "x y z"
  714. std::string offsetStr = offsetIt->get<std::string> ();
  715. std::istringstream iss (offsetStr);
  716. iss >> offset.x >> offset.y >> offset.z;
  717. } else {
  718. // Try parsing as vec3 directly
  719. try {
  720. offset = it.optional ("offset", glm::vec3 (0.0f));
  721. } catch (...) {
  722. offset = glm::vec3 (0.0f);
  723. }
  724. }
  725. }
  726. return ParticleControlPoint {
  727. .id = it.optional ("id", -1),
  728. .flags = it.optional ("flags", 0u),
  729. .offset = offset,
  730. .lockToPointer = it.optional ("locktopointer", false),
  731. };
  732. }
  733. ParticleChild ObjectParser::parseParticleChild (const JSON& it, const Project& project) {
  734. std::string particleFile = "";
  735. const auto particleIt = it.find ("particle");
  736. if (particleIt != it.end () && particleIt->is_string ()) {
  737. particleFile = particleIt->get<std::string> ();
  738. }
  739. std::string type = "static";
  740. const auto typeIt = it.find ("type");
  741. if (typeIt != it.end () && typeIt->is_string ()) {
  742. type = typeIt->get<std::string> ();
  743. }
  744. std::string name = "";
  745. const auto nameIt = it.find ("name");
  746. if (nameIt != it.end () && nameIt->is_string ()) {
  747. name = nameIt->get<std::string> ();
  748. }
  749. // Helper lambda to parse vec3 fields that might be strings, arrays, single numbers, or missing
  750. auto parseVec3 = [&] (const char* fieldName, const glm::vec3& defaultValue) -> glm::vec3 {
  751. const auto fieldIt = it.find (fieldName);
  752. if (fieldIt == it.end ()) {
  753. return defaultValue;
  754. }
  755. if (fieldIt->is_string ()) {
  756. return it.optional (fieldName, defaultValue);
  757. }
  758. if (fieldIt->is_number ()) {
  759. // Single number - use for all components
  760. float val = fieldIt->get<float> ();
  761. return glm::vec3 (val, val, val);
  762. }
  763. if (fieldIt->is_array () && fieldIt->size () >= 3) {
  764. return glm::vec3 ((*fieldIt)[0].get<float> (), (*fieldIt)[1].get<float> (), (*fieldIt)[2].get<float> ());
  765. }
  766. return defaultValue;
  767. };
  768. return ParticleChild {
  769. .type = type,
  770. .name = name,
  771. .maxCount = it.optional ("maxcount", 20),
  772. .controlPointStartIndex = it.optional ("controlpointstartindex", 0),
  773. .probability = it.optional ("probability", 1.0f),
  774. .angles = parseVec3 ("angles", glm::vec3 (0.0f)),
  775. .origin = parseVec3 ("origin", glm::vec3 (0.0f)),
  776. .scale = parseVec3 ("scale", glm::vec3 (1.0f)),
  777. .particleFile = particleFile,
  778. };
  779. }
  780. ParticleInstanceOverride ObjectParser::parseParticleInstanceOverride (const JSON& it, const Properties& properties) {
  781. return ParticleInstanceOverride {
  782. .enabled = it.user ("enabled", properties, true),
  783. .alpha = it.user ("alpha", properties, 1.0f),
  784. .size = it.user ("size", properties, 1.0f),
  785. .lifetime = it.user ("lifetime", properties, 1.0f),
  786. .rate = it.user ("rate", properties, 1.0f),
  787. .speed = it.user ("speed", properties, 1.0f),
  788. .count = it.user ("count", properties, 1.0f),
  789. .color = it.user ("color", properties, glm::vec3 (1.0f)),
  790. .colorn = it.user ("colorn", properties, glm::vec3 (1.0f)),
  791. };
  792. }