blob: cb8ab607322e9cf8afe795e87eea165fe520fedc [file] [log] [blame]
Corentin Wallezf07e3bd2017-04-20 14:38:20 -04001// Copyright 2017 The NXT Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Corentin Wallez9347e8f2017-06-19 13:15:13 -040015#include "SampleUtils.h"
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040016
Corentin Wallez5ee7afd2017-06-19 13:09:41 -040017#include "utils/NXTHelpers.h"
Corentin Wallez134e0802017-07-17 17:13:57 -040018#include "utils/SystemUtils.h"
Corentin Wallez5ee7afd2017-06-19 13:09:41 -040019
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040020#include <array>
21#include <cstring>
22#include <random>
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040023
24#include <glm/glm.hpp>
25
26nxt::Device device;
27nxt::Queue queue;
28
29nxt::Buffer modelBuffer;
30std::array<nxt::Buffer, 2> particleBuffers;
31
Corentin Wallez66ff4472017-07-14 11:32:57 -040032nxt::RenderPipeline renderPipeline;
Kai Ninomiya68df8b02017-05-16 14:04:22 -070033nxt::RenderPass renderpass;
34nxt::Framebuffer framebuffer;
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040035
36nxt::Buffer updateParams;
Corentin Wallez66ff4472017-07-14 11:32:57 -040037nxt::ComputePipeline updatePipeline;
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040038std::array<nxt::BindGroup, 2> updateBGs;
39
40std::array<nxt::CommandBuffer, 2> commandBuffers;
41
42size_t pingpong = 0;
43
44static const uint32_t kNumParticles = 1000;
45
46struct Particle {
47 glm::vec2 pos;
48 glm::vec2 vel;
49};
50
51struct SimParams {
52 float deltaT;
53 float rule1Distance;
54 float rule2Distance;
55 float rule3Distance;
56 float rule1Scale;
57 float rule2Scale;
58 float rule3Scale;
59 int particleCount;
60};
61
62void initBuffers() {
63 glm::vec2 model[3] = {
64 {-0.01, -0.02},
65 {0.01, -0.02},
66 {0.00, 0.02},
67 };
Corentin Wallez5ee7afd2017-06-19 13:09:41 -040068 modelBuffer = utils::CreateFrozenBufferFromData(device, model, sizeof(model), nxt::BufferUsageBit::Vertex);
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040069
Corentin Wallez83e779d2017-07-10 21:44:06 -040070 SimParams params = { 0.04f, 0.1f, 0.025f, 0.025f, 0.02f, 0.05f, 0.005f, kNumParticles };
Corentin Wallez5ee7afd2017-06-19 13:09:41 -040071 updateParams = utils::CreateFrozenBufferFromData(device, &params, sizeof(params), nxt::BufferUsageBit::Uniform);
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040072
73 std::vector<Particle> initialParticles(kNumParticles);
74 {
75 std::mt19937 generator;
76 std::uniform_real_distribution<float> dist(-1.0f, 1.0f);
77 for (auto& p : initialParticles)
78 {
79 p.pos = glm::vec2(dist(generator), dist(generator));
80 p.vel = glm::vec2(dist(generator), dist(generator)) * 0.1f;
81 }
82 }
83
84 for (int i = 0; i < 2; i++) {
85 particleBuffers[i] = device.CreateBufferBuilder()
Austin Eng39c901d2017-06-12 17:33:44 -040086 .SetAllowedUsage(nxt::BufferUsageBit::TransferDst | nxt::BufferUsageBit::Vertex | nxt::BufferUsageBit::Storage)
87 .SetInitialUsage(nxt::BufferUsageBit::TransferDst)
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040088 .SetSize(sizeof(Particle) * kNumParticles)
89 .GetResult();
90
91 particleBuffers[i].SetSubData(0,
92 sizeof(Particle) * kNumParticles / sizeof(uint32_t),
93 reinterpret_cast<uint32_t*>(initialParticles.data()));
94 }
95}
96
97void initRender() {
Corentin Wallez5ee7afd2017-06-19 13:09:41 -040098 nxt::ShaderModule vsModule = utils::CreateShaderModule(device, nxt::ShaderStage::Vertex, R"(
Corentin Wallezf07e3bd2017-04-20 14:38:20 -040099 #version 450
100 layout(location = 0) in vec2 a_particlePos;
101 layout(location = 1) in vec2 a_particleVel;
102 layout(location = 2) in vec2 a_pos;
103 void main() {
104 float angle = -atan(a_particleVel.x, a_particleVel.y);
105 vec2 pos = vec2(a_pos.x * cos(angle) - a_pos.y * sin(angle),
106 a_pos.x * sin(angle) + a_pos.y * cos(angle));
107 gl_Position = vec4(pos + a_particlePos, 0, 1);
108 }
109 )");
110
Corentin Wallez5ee7afd2017-06-19 13:09:41 -0400111 nxt::ShaderModule fsModule = utils::CreateShaderModule(device, nxt::ShaderStage::Fragment, R"(
Corentin Wallezf07e3bd2017-04-20 14:38:20 -0400112 #version 450
113 out vec4 fragColor;
114 void main() {
115 fragColor = vec4(1.0);
116 }
117 )");
118
119 nxt::InputState inputState = device.CreateInputStateBuilder()
120 .SetAttribute(0, 0, nxt::VertexFormat::FloatR32G32, offsetof(Particle, pos))
121 .SetAttribute(1, 0, nxt::VertexFormat::FloatR32G32, offsetof(Particle, vel))
122 .SetInput(0, sizeof(Particle), nxt::InputStepMode::Instance)
123 .SetAttribute(2, 1, nxt::VertexFormat::FloatR32G32, 0)
124 .SetInput(1, sizeof(glm::vec2), nxt::InputStepMode::Vertex)
125 .GetResult();
126
Corentin Wallez5ee7afd2017-06-19 13:09:41 -0400127 utils::CreateDefaultRenderPass(device, &renderpass, &framebuffer);
Corentin Wallez66ff4472017-07-14 11:32:57 -0400128 renderPipeline = device.CreateRenderPipelineBuilder()
Kai Ninomiya68df8b02017-05-16 14:04:22 -0700129 .SetSubpass(renderpass, 0)
Corentin Wallezf07e3bd2017-04-20 14:38:20 -0400130 .SetStage(nxt::ShaderStage::Vertex, vsModule, "main")
131 .SetStage(nxt::ShaderStage::Fragment, fsModule, "main")
132 .SetInputState(inputState)
133 .GetResult();
134}
135
136void initSim() {
Corentin Wallez5ee7afd2017-06-19 13:09:41 -0400137 nxt::ShaderModule module = utils::CreateShaderModule(device, nxt::ShaderStage::Compute, R"(
Corentin Wallezf07e3bd2017-04-20 14:38:20 -0400138 #version 450
139
140 struct Particle {
141 vec2 pos;
142 vec2 vel;
143 };
144
145 layout(std140, set = 0, binding = 0) uniform SimParams {
146 float deltaT;
147 float rule1Distance;
148 float rule2Distance;
149 float rule3Distance;
150 float rule1Scale;
151 float rule2Scale;
152 float rule3Scale;
153 int particleCount;
154 } params;
155
156 layout(std140, set = 0, binding = 1) buffer ParticlesA {
157 Particle particlesA[1000];
158 };
159
160 layout(std140, set = 0, binding = 2) buffer ParticlesB {
161 Particle particlesB[1000];
162 };
163
164 void main() {
165 // https://github.com/austinEng/Project6-Vulkan-Flocking/blob/master/data/shaders/computeparticles/particle.comp
166
167 uint index = gl_GlobalInvocationID.x;
168 if (index >= params.particleCount) { return; }
169
170 vec2 vPos = particlesA[index].pos;
171 vec2 vVel = particlesA[index].vel;
172
173 vec2 cMass = vec2(0.0, 0.0);
174 vec2 cVel = vec2(0.0, 0.0);
175 vec2 colVel = vec2(0.0, 0.0);
176 int cMassCount = 0;
177 int cVelCount = 0;
178
179 vec2 pos;
180 vec2 vel;
181 for (int i = 0; i < params.particleCount; ++i) {
182 if (i == index) { continue; }
183 pos = particlesA[i].pos.xy;
184 vel = particlesA[i].vel.xy;
185
186 if (distance(pos, vPos) < params.rule1Distance) {
187 cMass += pos;
188 cMassCount++;
189 }
190 if (distance(pos, vPos) < params.rule2Distance) {
191 colVel -= (pos - vPos);
192 }
193 if (distance(pos, vPos) < params.rule3Distance) {
194 cVel += vel;
195 cVelCount++;
196 }
197 }
198 if (cMassCount > 0) {
199 cMass = cMass / cMassCount - vPos;
200 }
201 if (cVelCount > 0) {
202 cVel = cVel / cVelCount;
203 }
204
205 vVel += cMass * params.rule1Scale + colVel * params.rule2Scale + cVel * params.rule3Scale;
206
207 // clamp velocity for a more pleasing simulation.
208 vVel = normalize(vVel) * clamp(length(vVel), 0.0, 0.1);
209
210 // kinematic update
211 vPos += vVel * params.deltaT;
212
213 // Wrap around boundary
214 if (vPos.x < -1.0) vPos.x = 1.0;
215 if (vPos.x > 1.0) vPos.x = -1.0;
216 if (vPos.y < -1.0) vPos.y = 1.0;
217 if (vPos.y > 1.0) vPos.y = -1.0;
218
219 particlesB[index].pos = vPos;
220
221 // Write back
222 particlesB[index].vel = vVel;
223 }
224 )");
225
226 nxt::BindGroupLayout bgl = device.CreateBindGroupLayoutBuilder()
227 .SetBindingsType(nxt::ShaderStageBit::Compute, nxt::BindingType::UniformBuffer, 0, 1)
228 .SetBindingsType(nxt::ShaderStageBit::Compute, nxt::BindingType::StorageBuffer, 1, 2)
229 .GetResult();
230
231 nxt::PipelineLayout pl = device.CreatePipelineLayoutBuilder()
232 .SetBindGroupLayout(0, bgl)
233 .GetResult();
234
Corentin Wallez66ff4472017-07-14 11:32:57 -0400235 updatePipeline = device.CreateComputePipelineBuilder()
Corentin Wallezf07e3bd2017-04-20 14:38:20 -0400236 .SetLayout(pl)
237 .SetStage(nxt::ShaderStage::Compute, module, "main")
238 .GetResult();
239
240 nxt::BufferView updateParamsView = updateParams.CreateBufferViewBuilder()
241 .SetExtent(0, sizeof(SimParams))
242 .GetResult();
243
244 std::array<nxt::BufferView, 2> views;
245 for (uint32_t i = 0; i < 2; ++i) {
246 views[i] = particleBuffers[i].CreateBufferViewBuilder()
247 .SetExtent(0, kNumParticles * sizeof(Particle))
248 .GetResult();
249 }
250
251 for (uint32_t i = 0; i < 2; ++i) {
252 updateBGs[i] = device.CreateBindGroupBuilder()
253 .SetLayout(bgl)
254 .SetUsage(nxt::BindGroupUsage::Frozen)
255 .SetBufferViews(0, 1, &updateParamsView)
256 .SetBufferViews(1, 1, &views[i])
257 .SetBufferViews(2, 1, &views[(i + 1) % 2])
258 .GetResult();
259 }
260}
261
262void initCommandBuffers() {
263 static const uint32_t zeroOffsets[1] = {0};
264 for (int i = 0; i < 2; ++i) {
265 auto& bufferSrc = particleBuffers[i];
266 auto& bufferDst = particleBuffers[(i + 1) % 2];
267 commandBuffers[i] = device.CreateCommandBufferBuilder()
Kai Ninomiya296951d2017-07-10 14:07:24 -0700268 .BeginComputePass()
Corentin Wallez66ff4472017-07-14 11:32:57 -0400269 .SetComputePipeline(updatePipeline)
Kai Ninomiya296951d2017-07-10 14:07:24 -0700270 .TransitionBufferUsage(bufferSrc, nxt::BufferUsageBit::Storage)
271 .TransitionBufferUsage(bufferDst, nxt::BufferUsageBit::Storage)
272 .SetBindGroup(0, updateBGs[i])
273 .Dispatch(kNumParticles, 1, 1)
274 .EndComputePass()
Corentin Wallezf07e3bd2017-04-20 14:38:20 -0400275
Kai Ninomiya68df8b02017-05-16 14:04:22 -0700276 .BeginRenderPass(renderpass, framebuffer)
Kai Ninomiyafa37f222017-06-29 23:53:08 -0700277 .BeginRenderSubpass()
Corentin Wallez66ff4472017-07-14 11:32:57 -0400278 .SetRenderPipeline(renderPipeline)
Kai Ninomiya68df8b02017-05-16 14:04:22 -0700279 .TransitionBufferUsage(bufferDst, nxt::BufferUsageBit::Vertex)
280 .SetVertexBuffers(0, 1, &bufferDst, zeroOffsets)
281 .SetVertexBuffers(1, 1, &modelBuffer, zeroOffsets)
282 .DrawArrays(3, kNumParticles, 0, 0)
Kai Ninomiyafa37f222017-06-29 23:53:08 -0700283 .EndRenderSubpass()
Kai Ninomiya68df8b02017-05-16 14:04:22 -0700284 .EndRenderPass()
Corentin Wallezf07e3bd2017-04-20 14:38:20 -0400285
286 .GetResult();
287 }
288}
289
290void init() {
Corentin Wallez583e9a82017-05-29 11:30:29 -0700291 device = CreateCppNXTDevice();
Corentin Wallezf07e3bd2017-04-20 14:38:20 -0400292
293 queue = device.CreateQueueBuilder().GetResult();
294
295 initBuffers();
296 initRender();
297 initSim();
298 initCommandBuffers();
299}
300
301void frame() {
302 queue.Submit(1, &commandBuffers[pingpong]);
Corentin Wallez583e9a82017-05-29 11:30:29 -0700303 DoSwapBuffers();
Corentin Wallezf07e3bd2017-04-20 14:38:20 -0400304
305 pingpong = (pingpong + 1) % 2;
306}
307
308int main(int argc, const char* argv[]) {
Corentin Wallez9347e8f2017-06-19 13:15:13 -0400309 if (!InitSample(argc, argv)) {
Corentin Wallezf07e3bd2017-04-20 14:38:20 -0400310 return 1;
311 }
312 init();
313
314 while (!ShouldQuit()) {
315 frame();
Corentin Wallez134e0802017-07-17 17:13:57 -0400316 utils::USleep(16000);
Corentin Wallezf07e3bd2017-04-20 14:38:20 -0400317 }
318
319 // TODO release stuff
320}