particle_system.hpp 12.2 KB
Newer Older
1
2
#pragma once

3
4
#include <mirrage/renderer/model.hpp>

5
#include <mirrage/asset/asset_manager.hpp>
6
#include <mirrage/ecs/entity_manager.hpp>
7
#include <mirrage/graphic/texture.hpp>
8
#include <mirrage/utils/random.hpp>
9
#include <mirrage/utils/sf2_glm.hpp>
10
#include <mirrage/utils/small_vector.hpp>
11
12
13
14
15
#include <mirrage/utils/units.hpp>

#include <glm/vec3.hpp>
#include <sf2/sf2.hpp>

16
#include <memory>
17
18
#include <tuple>

19
20
21

namespace mirrage::renderer {

22
23
24
25
26
27
	struct Particle {
		glm::vec4 position; // xyz + uintBitsToFloat(last_feedback_buffer_index)
		glm::vec4 velocity; // xyz + seed
		glm::vec4 ttl;      // ttl_left, ttl_initial, <empty>, <empty>
	};

28
29
30
31
	class Particle_script {
	  public:
		explicit Particle_script(vk::UniquePipeline pipeline) : _pipeline(std::move(pipeline)) {}

32
		void bind(vk::CommandBuffer) const;
33
34
35
36
37

	  private:
		vk::UniquePipeline _pipeline;
	};

38
39
	enum class Particle_blend_mode { solid, transparent };
	sf2_enumDef(Particle_blend_mode, solid, transparent);
40

41
42
	enum class Particle_geometry { billboard, mesh };
	sf2_enumDef(Particle_geometry, billboard, mesh);
43
44

	struct Particle_color {
45
46
47
48
		float hue        = 0.f;
		float saturation = 0.f;
		float value      = 0.f;
		float alpha      = 0.f;
49
	};
50
	sf2_structDef(Particle_color, hue, saturation, value, alpha);
51

52
53
54
55
	template <typename T>
	struct Random_value {
		T mean{};
		T stddev{};
56
	};
57
58
59
	sf2_structDef(Random_value<float>, mean, stddev);
	sf2_structDef(Random_value<glm::vec4>, mean, stddev);
	sf2_structDef(Random_value<Particle_color>, mean, stddev);
60

61

62
63
64
65
66
67
68
	/// modify velocities of living particles
	/// e.g.
	/// gravity: {..., force=10, dir={0,-1,0}, decay=0, fixed_dir=true}
	/// point: {position=? dir={0,0,0}, decay=2}
	/// flow: {position=? dir={1,0,0}, decay=2}
	struct Particle_effector_config {
		glm::quat rotation{1, 0, 0, 0};
69

70
		glm::vec3 position{0, 0, 0};
71
72
73
74
		float     force = 0.f;
		glm::vec3 force_dir{0, 0, 0};
		float     distance_decay = 2.f;

75
		bool fixed_dir       = false; //< ignore position of effector when calculating the force
76
		bool scale_with_mass = true;
77
		bool absolute        = false;
78
79
80
81
82
83
84
85
86
	};
	sf2_structDef(Particle_effector_config,
	              position,
	              rotation,
	              force,
	              force_dir,
	              distance_decay,
	              fixed_dir,
	              scale_with_mass);
87

88
89
90
91
	/// describes how living particles are updated and drawn
	struct Particle_type_config {
		Random_value<Particle_color> color        = {{1, 1, 1, 1}};
		Random_value<Particle_color> color_change = {{0, 0, 0, 0}};
92

93
94
		Random_value<glm::vec4> size        = {{1.f, 1.f, 1.f, 0.f}};
		Random_value<glm::vec4> size_change = {{0.f, 0.f, 0.f, 0.f}};
95

96
97
		Random_value<float> sprite_rotation        = {0.0f};
		Random_value<float> sprite_rotation_change = {0.0f};
98

99
100
101
102
		float base_mass = 1.f;
		float density   = 0.f;
		float drag      = 0.f;

103
104
105
		Particle_blend_mode blend    = Particle_blend_mode::transparent;
		Particle_geometry   geometry = Particle_geometry::billboard;

106
107
108
109
		float update_range = -1.f;
		float draw_range   = -1.f;
		bool  shadowcaster = false;

110
111
112
113
114
115
		std::string            material_id;
		renderer::Material_ptr material;

		std::string                 model_id;
		asset::Ptr<renderer::Model> model;

116
		std::string                 update_script_id;
117
		asset::Ptr<Particle_script> update_script;
118
	};
119
120
121
122
123
124
125
126
127
	sf2_structDef(Particle_type_config,
	              color,
	              color_change,
	              size,
	              size_change,
	              base_mass,
	              density,
	              sprite_rotation,
	              sprite_rotation_change,
128
	              blend,
129
	              geometry,
130
131
132
	              update_range,
	              draw_range,
	              shadowcaster,
133
134
135
136
137
	              material_id,
	              model_id,
	              drag,
	              update_script_id);

138
139
140

	struct Particle_emitter_spawn {
		float particles_per_second = 10.f;
141
		float stddev               = 0.f;
142
143
		float time                 = -1.f;
	};
144
	sf2_structDef(Particle_emitter_spawn, particles_per_second, stddev, time);
145
146
147
148
149
150
151
152
153
154

	// describes how new particles are created
	struct Particle_emitter_config {
		Random_value<float> ttl = {1.f};

		Random_value<float> velocity = {1.f};

		float parent_velocity = 0.f;

		glm::vec3 offset{0, 0, 0};
155
156
		glm::quat rotation{1, 0, 0, 0};

157
158
159
		util::small_vector<Particle_emitter_spawn, 4> spawn;
		bool                                          spawn_loop = true;

160
161
162
163
164
		std::string                 emit_script_id;
		asset::Ptr<Particle_script> emit_script;

		std::string                      type_id;
		asset::Ptr<Particle_type_config> type;
165
	};
166
167
168
169
170
171
172
173
174
175
	sf2_structDef(Particle_emitter_config,
	              spawn,
	              spawn_loop,
	              ttl,
	              velocity,
	              parent_velocity,
	              offset,
	              rotation,
	              emit_script_id,
	              type_id);
176
177

	struct Particle_system_config {
178
179
		util::small_vector<Particle_emitter_config, 1> emitters;
		std::vector<Particle_effector_config>          effectors;
180
	};
181
	sf2_structDef(Particle_system_config, emitters, effectors);
182
183


184
185
186
187
188
	class Particle_emitter_gpu_data {
	  public:
		auto valid() const noexcept { return _live_rev && *_live_rev == _rev; }
		void set(const std::uint64_t* rev,
		         vk::Buffer,
189
		         vk::DescriptorSet,
190
191
192
193
		         std::int32_t  offset,
		         std::int32_t  count,
		         std::uint32_t feedback_idx);

194
195
196
		void next_uniforms(vk::DescriptorSet s) { _next_uniforms = s; }
		auto next_uniforms() const noexcept { return _next_uniforms; }

197
198
	  private:
		vk::Buffer           _buffer;
199
200
		vk::DescriptorSet    _uniforms;
		vk::DescriptorSet    _next_uniforms;
201
202
203
204
205
206
207
208
209
		const std::uint64_t* _live_rev     = nullptr;
		std::uint64_t        _rev          = 0;
		std::int32_t         _offset       = 0;
		std::int32_t         _count        = 0;
		std::uint32_t        _feedback_idx = 0;

		friend class Particle_emitter;
	};

210
211
	class Particle_emitter {
	  public:
212
		explicit Particle_emitter(const Particle_emitter_config& cfg) : _cfg(&cfg) {}
213

214
215
216
		void active(bool b) noexcept { _active = b; }
		auto active() const noexcept { return _active; }

217
		void position(glm::vec3 p) noexcept { _position = p; }
218
219
		auto position() const noexcept { return _position; }

220
		void rotation(glm::quat r) noexcept { _rotation = r; }
221
222
		auto rotation() const noexcept { return _rotation; }

223
224
225
		void absolute(bool b) noexcept { _absolute = b; }
		auto absolute() const noexcept { return _absolute; }

226
		void incr_time(float dt);
227
228
229
230
231
232
233
234
235
236
		auto spawn(util::default_rand&) -> std::int32_t;

		auto drawable() const noexcept { return _gpu_data && _gpu_data->valid(); }
		auto particle_offset() const noexcept { return drawable() ? _gpu_data->_offset : 0; }
		auto particle_count() const noexcept { return drawable() ? _gpu_data->_count : 0; }
		auto particle_feedback_idx() const noexcept
		{
			return drawable() ? util::just(_gpu_data->_feedback_idx) : util::nothing;
		}
		auto particle_buffer() const noexcept { return drawable() ? _gpu_data->_buffer : vk::Buffer{}; }
237
238
239
240
		auto particle_uniforms() const noexcept
		{
			return drawable() ? _gpu_data->_uniforms : vk::DescriptorSet{};
		}
241
242
243
244
		auto particles_to_spawn() const noexcept { return _particles_to_spawn; }
		auto last_timestep() const noexcept { return _last_timestep; }

		auto gpu_data() -> std::shared_ptr<Particle_emitter_gpu_data>;
245

246
		auto cfg() const noexcept -> auto& { return *_cfg; }
247
248

	  private:
249
		const Particle_emitter_config* _cfg;
250
251

		// TODO: userdata?
252
		bool      _active = true;
253
254
		glm::vec3 _position{0, 0, 0};
		glm::quat _rotation{1, 0, 0, 0};
255
		bool      _absolute = false;
256

257
258
259
260
261
262
263
264
265
		float       _time_accumulator  = 0.f;
		std::size_t _spawn_idx         = 0;
		float       _spawn_entry_timer = 0;

		std::int32_t _particles_to_spawn = 0;
		float        _last_timestep      = 0;

		// shared_ptr because its update after the async compute tasks finished
		std::shared_ptr<Particle_emitter_gpu_data> _gpu_data;
266
267
	};

268
	class Particle_system : private std::enable_shared_from_this<Particle_system> {
269
	  public:
270
271
		using Emitter_list  = util::small_vector<Particle_emitter, 1>;
		using Effector_list = std::vector<Particle_effector_config>;
272

273
274
275
276
		Particle_system() = default;
		Particle_system(asset::Ptr<Particle_system_config> cfg,
		                glm::vec3                          position = {0, 0, 0},
		                glm::quat                          rotation = {1, 0, 0, 0});
277

278
		auto cfg() const noexcept { return _cfg; }
279
		auto cfg_aid() const { return _cfg ? util::just(_cfg.aid()) : util::nothing; }
280

281
282
283
284
285
		auto emitters() noexcept -> auto&
		{
			_check_reload();
			return _emitters;
		}
286

287
288
289
290
291
		auto effectors() noexcept -> auto&
		{
			_check_reload();
			return _effectors;
		}
292

293
		void position(glm::vec3 p) noexcept { _position = p; }
294
295
		auto position() const noexcept { return _position; }

296
		void rotation(glm::quat r) noexcept { _rotation = r; }
297
298
		auto rotation() const noexcept { return _rotation; }

299
300
301
302
303
304
305
		auto emitter_position(const Particle_emitter& e) const noexcept
		{
			return e.absolute() ? e.position() : _position + e.position();
		}

		auto emitter_rotation(const Particle_emitter& e) const noexcept
		{
306
			return e.absolute() ? e.rotation() : glm::normalize(_rotation * e.rotation());
307
308
		}

309
	  private:
310
311
		friend class Particle_pass;

312
313
314
315
		asset::Ptr<Particle_system_config> _cfg;
		bool                               _loaded = false;
		Emitter_list                       _emitters;
		Effector_list                      _effectors;
316

317
		glm::vec3 _position{0, 0, 0};
318
		glm::vec3 _last_position{0, 0, 0};
319
		glm::quat _rotation{1, 0, 0, 0};
320
321

		void _check_reload();
322
	};
323
324
325
326
327
328
329
330
331
332
333


	class Particle_system_comp : public ecs::Component<Particle_system_comp> {
	  public:
		static constexpr const char* name() { return "Particle_system"; }
		friend void                  load_component(ecs::Deserializer& state, Particle_system_comp&);
		friend void                  save_component(ecs::Serializer& state, const Particle_system_comp&);

		Particle_system_comp() = default;
		Particle_system_comp(ecs::Entity_handle owner, ecs::Entity_manager& em) : Component(owner, em) {}

334
335
336
		Particle_system particle_system;
	};

337
	class Particle_effector_comp : public ecs::Component<Particle_effector_comp> {
338
339
340
341
342
343
344
345
346
	  public:
		static constexpr const char* name() { return "Particle_effector"; }
		friend void                  load_component(ecs::Deserializer& state, Particle_effector_comp&);
		friend void                  save_component(ecs::Serializer& state, const Particle_effector_comp&);

		Particle_effector_comp() = default;
		Particle_effector_comp(ecs::Entity_handle owner, ecs::Entity_manager& em) : Component(owner, em) {}

		Particle_effector_config effector;
347
348
	};

349
350
351
352
353
354
355
356
357

	extern auto create_particle_shared_desc_set_layout(graphic::Device&) -> vk::UniqueDescriptorSetLayout;

	extern auto create_particle_script_pipeline_layout(graphic::Device&        device,
	                                                   vk::DescriptorSetLayout shared_desc_set,
	                                                   vk::DescriptorSetLayout storage_buffer,
	                                                   vk::DescriptorSetLayout uniform_buffer)
	        -> vk::UniquePipelineLayout;

358
} // namespace mirrage::renderer
359
360
361
362
363
364

namespace mirrage::asset {

	template <>
	struct Loader<renderer::Particle_script> {
	  public:
365
366
367
		Loader(graphic::Device&        device,
		       vk::DescriptorSetLayout storage_buffer,
		       vk::DescriptorSetLayout uniform_buffer);
368
369
370
371

		auto              load(istream in) -> renderer::Particle_script;
		[[noreturn]] void save(ostream, const renderer::Particle_script&)
		{
372
			MIRRAGE_FAIL("Save of Particle_script is not supported!");
373
374
375
		}

	  private:
376
377
378
		graphic::Device&              _device;
		vk::UniqueDescriptorSetLayout _shared_desc_set;
		vk::UniquePipelineLayout      _layout;
379
380
381
382
383
384
385
386
	};

	template <>
	struct Loader<renderer::Particle_system_config> {
	  public:
		static auto              load(istream in) -> async::task<renderer::Particle_system_config>;
		[[noreturn]] static void save(ostream, const renderer::Particle_system_config&)
		{
387
388
389
390
391
392
393
394
395
396
397
			MIRRAGE_FAIL("Save of Particle_system_config is not supported!");
		}
	};

	template <>
	struct Loader<renderer::Particle_type_config> {
	  public:
		static auto              load(istream in) -> async::task<renderer::Particle_type_config>;
		[[noreturn]] static void save(ostream, const renderer::Particle_type_config&)
		{
			MIRRAGE_FAIL("Save of Particle_type_config is not supported!");
398
399
400
401
		}
	};

} // namespace mirrage::asset