ObjectParser.cpp 34 KB

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