├── CMakeLists.txt
├── LICENSE
├── README.md
├── example.gif
└── src
├── BaseSolver.h
├── BasicSPHSolver.cu
├── BasicSPHSolver.h
├── CMakeLists.txt
├── CUDAFunctions.cuh
├── DArray.h
├── DFSPHSolver.cu
├── DFSPHSolver.h
├── PBDSolver.cu
├── PBDSolver.h
├── Particles.cu
├── Particles.h
├── SPHParticles.h
├── SPHSystem.cu
├── SPHSystem.h
├── ShaderUtility.cpp
├── ShaderUtility.h
├── global.h
├── main.cpp
├── particles.frag
├── particles.vert
└── vbo.cu
/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.8.0 FATAL_ERROR)
2 |
3 | if(NOT "${CMAKE_GENERATOR}" MATCHES "(Win64|IA64)")
4 | message("Please use 64-bit cmake generator.")
5 | endif()
6 |
7 | project(CPP_Fluid_Particles VERSION 0.1.0 LANGUAGES CXX C CUDA)
8 |
9 | find_package(CUDA REQUIRED)
10 | set(CMAKE_CUDA_ARCH 5 6)
11 | set(CMAKE_CONFIGURATION_TYPES "Release")
12 |
13 | set(CUDASAMPLESROOT $ENV{NVCUDASAMPLES_ROOT})
14 | message("cuda samples root ${CUDASAMPLESROOT}")
15 | include_directories(${CUDASAMPLESROOT}/common/inc)
16 | link_directories(${CUDASAMPLESROOT}/common/lib/x64/)
17 |
18 | add_subdirectory(src)
19 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # C++ Fluid Particles
2 |
3 | This repository contains my own implementation of several Smoothed Particle Hydrodynamics (SPH) related papers using C++ and CUDA, including the Weakly Compressible SPH [1], Position-Based Fluids [2], Divergence-Free SPH [3], etc. All credits should be given to the authors of the original papers. My own implementation is meant for study and research use only.
4 |
5 | ## Some Results (GIF)
6 | This example contains 20,736 particles and is timed on a Windows PC with i5-6500 CPU, GTX 1070 GPU and CUDA 8.0 installed.
7 | Left: WCSPH, dt = 0.001 s, avg performance = 4.4 ms/frame (227 FPS)
8 | Middle: DFSPH, dt = 0.004 s, avg performance = 23.0 ms/frame (43.4 FPS)
9 | Right: PBD, dt = 0.004 s, avg performance = 11.3 ms/frame (88.5 FPS)
10 | 
11 |
12 | ## Requirements
13 |
14 | * CUDA (7.5 or above)
15 | * OpenGL (normally comes with CUDA Samples)
16 |
17 | 🔶__Important Note (if you are not using CMake): Due to the use of several C++ lambda functions in Thrust calls, it's necessary to specify '--expt-extended-lambda' on the nvcc compile command line. Besides, the helper_math.h used in the code can be found in CUDA Samples along with the OpenGL headers.__🔶
18 | I used Visual Studio 2019 Preview and CUDA 10.1 to develop the code on a Windows PC with an Nvidia GTX 980 Ti GPU. I also tested the code (without any changes) on another Windows PC with an Nvidia GTX 1070 GPU and CUDA 8.0 installed. Different platforms may need changes on the code.
19 |
20 | ## Brief Description of the Program
21 | ### Controls
22 | Space - Start/Pause
23 | Key N - One Step Forward
24 | Key Q - Quit
25 | Key 1 - Restart Simulation Using SPH Solver
26 | Key 2 - Restart Simulation Using DFSPH Solver
27 | Key 3 - Restart Simulation Using PBD Solver
28 | Key R - Reset Viewpoint
29 | Key , - Zoom In
30 | Key . - Zoom Out
31 | Mouse Drag - Change Viewpoint
32 | ### SPH System
33 | This class is responsible for initiating the simulation, storing the particle states, passing simulation parameters, doing the neighbor search and calling the solver in each iteration.
34 | ### Particles
35 | SPHParticles objects (derived from the Particles) are responsible for storing the particle properties (such as position, density, pressure, velocity, etc.) on GPU memory and providing accessor methods for these properties. Smart pointers and some lambda tricks are taken advantage of in the DArray class (stands for Device Array) to automatically free the GPU memory when the reference count goes to zero.
36 | ### Solvers
37 | 3 popular particle-based fluid solvers, namely the WCSPH [1], PBD [2] and DFSPH [3], are included in this repository. These classes hold the necessary auxiliary GPU memories and provide their respective pressure correction functions. Also, the PBD solver applies the XSPH variant of the viscosity calculation. Additionally, a recent model for surface tension and air pressure by He et al. [4] is incorporated in these solvers with the dedicated smoothing kernel deduced following Akinci et al. [5] to encourage the balance between attraction and repulsion.
38 | ### Rendering
39 | The particle is efficiently rendered using OpenGL's vertex shader and fragment shader (via a technique similar to the point sprites). The color of particles indicates their density. Specifically, magenta means the particle is compressed and holds a higher density than the balance state, while on the opposite, navy means the particle has lower density.
40 |
41 | ## Additional Note
42 | 🔶__This issue is automatically addressed if you are using CMake with the latest commit.__🔶
43 | There seems to be a bug that prevents CUDA 10.1 from working perfectly with Visual Studio 2019 Preview. The host compiler and nvcc write to 'vc142.pdb' at the same time, and the building process would quit erroneously when this happens. To avoid such situation, consider using '/MP' flag in the host compile command line and add '/FS' in 'Project Properties' - 'CUDA C/C++' - 'Host' - 'Additional Compiler Options'.
44 |
45 | ## Reference
46 | [1] Becker M, Teschner M. Weakly compressible SPH for free surface flows[C]//Proceedings of the 2007 ACM SIGGRAPH/Eurographics symposium on Computer animation. Eurographics Association, 2007: 209-217.
47 |
48 | [2] Macklin M, Müller M. Position based fluids[J]. ACM Transactions on Graphics (TOG), 2013, 32(4): 104.
49 |
50 | [3] Bender J, Koschier D. Divergence-free smoothed particle hydrodynamics[C]//Proceedings of the 14th ACM SIGGRAPH/Eurographics symposium on computer animation. ACM, 2015: 147-155.
51 |
52 | [4] He X, Wang H, Zhang F, et al. Robust simulation of sparsely sampled thin features in SPH-based free surface flows[J]. ACM Transactions on Graphics (TOG), 2014, 34(1): 7.
53 |
54 | [5] Akinci N, Akinci G, Teschner M. Versatile surface tension and adhesion for SPH fluids[J]. ACM Transactions on Graphics (TOG), 2013, 32(6): 182.
55 |
--------------------------------------------------------------------------------
/example.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zhai-xiao/CPP-Fluid-Particles/f88e6e16ffa40ac1a14d4e0c8d439db4490cc070/example.gif
--------------------------------------------------------------------------------
/src/BaseSolver.h:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #pragma once
19 |
20 | class BaseSolver {
21 | public:
22 | virtual void step(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
23 | const DArray& cellStartFluid, const DArray& cellStartBoundary, float3 spaceSize,
24 | int3 cellSize, float cellLength, float radius, float dt,
25 | float rho0, float rhoB, float stiff, float visc, float3 G,
26 | float surfaceTensionIntensity, float airPressure) = 0;
27 | virtual ~BaseSolver(){}
28 | protected:
29 | virtual void advect(std::shared_ptr& fluids, float dt, float3 spaceSize) = 0;
30 | virtual void force(std::shared_ptr& fluids, float dt, float3 G) = 0;
31 | };
32 |
--------------------------------------------------------------------------------
/src/BasicSPHSolver.cu:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include "CUDAFunctions.cuh"
26 | #include "DArray.h"
27 | #include "Particles.h"
28 | #include "SPHParticles.h"
29 | #include "BaseSolver.h"
30 | #include "BasicSPHSolver.h"
31 |
32 | __device__ void contributeFluidDensity(float* density, const int i, float3* pos, float* mass, const int cellStart, const int cellEnd, const float radius)
33 | {
34 | auto j = cellStart;
35 | while (j < cellEnd)
36 | {
37 | *density += mass[j] * cubic_spline_kernel(length(pos[i] - pos[j]), radius);
38 | ++j;
39 | }
40 | return;
41 | }
42 |
43 | __device__ void contributeBoundaryDensity(float* density, const float3 pos_i, float3* pos, float* mass, const int cellStart, const int cellEnd, const float radius)
44 | {
45 | auto j = cellStart;
46 | while (j < cellEnd)
47 | {
48 | *density += mass[j] * cubic_spline_kernel(length(pos_i - pos[j]), radius);
49 | ++j;
50 | }
51 | return;
52 | }
53 |
54 | __global__ void computeDensity_CUDA(float* density, const int num,
55 | float3* posFluid, float* massFluid, int* cellStartFluid,
56 | float3* posBoundary, float* massBoundary, int* cellStartBoundary,
57 | const int3 cellSize, const float cellLength, const float radius)
58 | {
59 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
60 | if (i >= num) return;
61 | __syncthreads();
62 | #pragma unroll
63 | for (auto m = 0; m < 27; __syncthreads(), ++m)
64 | {
65 | const auto cellID = particlePos2cellIdx(
66 | make_int3(posFluid[i] / cellLength) + make_int3(m / 9 - 1, (m % 9) / 3 - 1, m % 3 - 1), cellSize);
67 | if (cellID == (cellSize.x * cellSize.y * cellSize.z)) continue;
68 | contributeFluidDensity(&density[i], i, posFluid, massFluid, cellStartFluid[cellID], cellStartFluid[cellID + 1], radius);
69 | contributeBoundaryDensity(&density[i], posFluid[i], posBoundary, massBoundary, cellStartBoundary[cellID], cellStartBoundary[cellID + 1], radius);
70 | }
71 | return;
72 | }
73 |
74 | void BasicSPHSolver::computeDensity(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
75 | const DArray& cellStartFluid, const DArray& cellStartBoundary, int3 cellSize, float cellLength, float radius) const
76 | {
77 | int num = fluids->size();
78 | thrust::fill(thrust::device, fluids->getDensityPtr(), fluids->getDensityPtr() + num, 0);
79 | computeDensity_CUDA <<<(num - 1) / block_size + 1, block_size >>> (fluids->getDensityPtr(), num,
80 | fluids->getPosPtr(), fluids->getMassPtr(), cellStartFluid.addr(),
81 | boundaries->getPosPtr(), boundaries->getMassPtr(), cellStartBoundary.addr(),
82 | cellSize, cellLength, radius);
83 | }
84 |
85 | __global__ void enforceBoundary_CUDA(float3* pos, float3* vel, const int num, const float3 spaceSize)
86 | {
87 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
88 | if (i >= num) return;
89 | if (pos[i].x <= spaceSize.x * .00f) { pos[i].x = spaceSize.x * .00f; vel[i].x = fmaxf(vel[i].x, 0.0f); }
90 | if (pos[i].x >= spaceSize.x * .99f) { pos[i].x = spaceSize.x * .99f; vel[i].x = fminf(vel[i].x, 0.0f); }
91 | if (pos[i].y <= spaceSize.y * .00f) { pos[i].y = spaceSize.y * .00f; vel[i].y = fmaxf(vel[i].y, 0.0f); }
92 | if (pos[i].y >= spaceSize.y * .99f) { pos[i].y = spaceSize.y * .99f; vel[i].y = fminf(vel[i].y, 0.0f); }
93 | if (pos[i].z <= spaceSize.z * .00f) { pos[i].z = spaceSize.z * .00f; vel[i].z = fmaxf(vel[i].z, 0.0f); }
94 | if (pos[i].z >= spaceSize.z * .99f) { pos[i].z = spaceSize.z * .99f; vel[i].z = fminf(vel[i].z, 0.0f); }
95 | return;
96 | }
97 |
98 | void BasicSPHSolver::advect(std::shared_ptr& fluids, float dt, float3 spaceSize) {
99 | fluids->advect(dt);
100 | enforceBoundary_CUDA <<<((fluids->size())-1)/block_size+1, block_size >>> (fluids->getPosPtr(), fluids->getVelPtr(), fluids->size(), spaceSize);
101 | }
102 |
103 | __global__ void computePressure_CUDA(float* pressure, float* density, const int num, const float rho0, const float stiff)
104 | {
105 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
106 | if (i >= num) return;
107 | pressure[i] = stiff * (powf((density[i] / rho0), 7) - 1.0f);
108 | //clamp
109 | if (pressure[i] < 0.0f) pressure[i] = 0.0f;
110 | return;
111 | }
112 |
113 | __device__ void contributeFluidPressure(float3* a, const int i, float3* pos, float* mass,
114 | float* density, float* pressure, const int cellStart, const int cellEnd, const float radius)
115 | {
116 | auto j = cellStart;
117 | while (j < cellEnd)
118 | {
119 | if (i != j)
120 | * a += -mass[j] *
121 | (pressure[i] / fmaxf(EPSILON, density[i] * density[i]) + pressure[j] / fmaxf(EPSILON, density[j] * density[j]))
122 | * cubic_spline_kernel_gradient(pos[i] - pos[j], radius);
123 | ++j;
124 | }
125 | return;
126 | }
127 |
128 | __device__ void contributeBoundaryPressure(float3* a, const float3 pos_i, float3* pos, float* mass,
129 | const float density, const float pressure, const int cellStart, const int cellEnd, const float radius)
130 | {
131 | auto j = cellStart;
132 | while (j < cellEnd)
133 | {
134 | *a += -mass[j] * (pressure / fmaxf(EPSILON, density * density)) * cubic_spline_kernel_gradient(pos_i - pos[j], radius);
135 | ++j;
136 | }
137 | return;
138 | }
139 |
140 | __global__ void pressureForce_CUDA(float3* velFluid, float3* posFluid, float* massFluid,
141 | float* density, float* pressure, const int num, int* cellStartFluid,
142 | float3* posBoundary, float* massBoundary, int* cellStartBoundary,
143 | const int3 cellSize, const float cellLength, const float radius, const float dt)
144 | {
145 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
146 | if (i >= num) return;
147 | auto a = make_float3(0.0f);
148 | __syncthreads();
149 | #pragma unroll
150 | for (auto m = 0; m < 27; __syncthreads(), ++m)
151 | {
152 | const auto cellID = particlePos2cellIdx(
153 | make_int3(posFluid[i] / cellLength) + make_int3(m / 9 - 1, (m % 9) / 3 - 1, m % 3 - 1), cellSize);
154 | if (cellID == (cellSize.x * cellSize.y * cellSize.z)) continue;
155 | contributeFluidPressure(&a, i, posFluid, massFluid, density, pressure, cellStartFluid[cellID], cellStartFluid[cellID + 1], radius);
156 | contributeBoundaryPressure(&a, posFluid[i], posBoundary, massBoundary, density[i], pressure[i], cellStartBoundary[cellID], cellStartBoundary[cellID + 1], radius);
157 | }
158 |
159 | // dirty trick to prevent blowups in large dt
160 | if (length(a) > MAX_A)
161 | a = normalize(a) * MAX_A;
162 |
163 | velFluid[i] += a * dt;
164 | return;
165 | }
166 |
167 | void BasicSPHSolver::project(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
168 | const DArray& cellStartFluid, const DArray& cellStartBoundary, float rho0, float stiff,
169 | int3 cellSize, float cellLength, float radius, float dt)
170 | {
171 | int num = fluids->size();
172 | // step 1:: calculate density
173 | computeDensity(fluids, boundaries, cellStartFluid, cellStartBoundary, cellSize, cellLength, radius);
174 | // step 2: calculate pressure from density
175 | computePressure_CUDA <<<(num - 1) / block_size + 1, block_size >>> (fluids->getPressurePtr(), fluids->getDensityPtr(), num, rho0, stiff);
176 | // step 3: apply pressure force according to pressure
177 | pressureForce_CUDA <<<(num - 1) / block_size + 1, block_size >>> (fluids->getVelPtr(), fluids->getPosPtr(), fluids->getMassPtr(),
178 | fluids->getDensityPtr(), fluids->getPressurePtr(), num, cellStartFluid.addr(),
179 | boundaries->getPosPtr(), boundaries->getMassPtr(), cellStartBoundary.addr(),
180 | cellSize, cellLength, radius, dt);
181 | }
182 |
183 | __device__ void contributeViscosity(float3* a, const int i, float3* pos, float3* vel,
184 | float* mass, int j/*cellStart*/, const int cellEnd, const float rho0, const float radius) {
185 | while (j < cellEnd) {
186 | *a += mass[j] * ((vel[j] - vel[i]) / rho0) * viscosity_kernel_laplacian(length(pos[i] - pos[j]), radius);
187 | ++j;
188 | }
189 | return;
190 | }
191 |
192 | __global__ void viscosity_CUDA(float3* deltaV, float3* vel, float3* pos,
193 | float* mass, const int num, int* cellStart, const int3 cellSize,
194 | const float cellLength, const float rho0, const float radius, const float visc, const float dt) {
195 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
196 | if (i >= num) return;
197 | auto a = make_float3(0.0f);
198 | __syncthreads();
199 | #pragma unroll
200 | for (auto m = 0; m < 27; __syncthreads(), ++m) {
201 | const auto cellID = particlePos2cellIdx(make_int3(pos[i] / cellLength) + make_int3(m / 9 - 1, (m % 9) / 3 - 1, m % 3 - 1),
202 | cellSize);
203 | if (cellID == (cellSize.x * cellSize.y * cellSize.z)) continue;
204 | contributeViscosity(&a, i, pos, vel, mass, cellStart[cellID], cellStart[cellID + 1], rho0, radius);
205 | }
206 |
207 | deltaV[i] = visc * a * dt;
208 | return;
209 | }
210 |
211 | void BasicSPHSolver::diffuse(std::shared_ptr& fluids, const DArray& cellStartFluid,
212 | int3 cellSize, float cellLength, float rho0,
213 | float radius, float visc, float dt)
214 | {
215 | int num = fluids->size();
216 | viscosity_CUDA <<<(num - 1) / block_size + 1, block_size >>> (bufferFloat3.addr(), fluids->getVelPtr(), fluids->getPosPtr(),
217 | fluids->getMassPtr(), num, cellStartFluid.addr(), cellSize, cellLength,
218 | rho0, radius, visc, dt);
219 | thrust::transform(thrust::device,
220 | fluids->getVelPtr(), fluids->getVelPtr() + num,
221 | bufferFloat3.addr(),
222 | fluids->getVelPtr(),
223 | thrust::plus()
224 | );
225 | }
226 |
227 | void BasicSPHSolver::force(std::shared_ptr& fluids, float dt, float3 G)
228 | {
229 | const auto dv = dt * G;
230 | thrust::transform(thrust::device,
231 | fluids->getVelPtr(), fluids->getVelPtr() + fluids->size(),
232 | fluids->getVelPtr(),
233 | ThrustHelper::plus(dv)
234 | );
235 | }
236 |
237 | void BasicSPHSolver::step(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
238 | const DArray& cellStartFluid, const DArray& cellStartBoundary, float3 spaceSize,
239 | int3 cellSize, float cellLength, float radius, float dt,
240 | float rho0, float rhoB, float stiff, float visc, float3 G,
241 | float surfaceTensionIntensity, float airPressure)
242 | {
243 | // step 1: non-pressure, non-viscosity force
244 | force(fluids, dt, G);
245 | // step 2: viscosity force, surface tension
246 | diffuse(fluids, cellStartFluid, cellSize,
247 | cellLength, rho0, radius,
248 | visc, dt);
249 | if (surfaceTensionIntensity > EPSILON || airPressure > EPSILON)
250 | handleSurface(fluids, boundaries,
251 | cellStartFluid, cellStartBoundary,
252 | rho0, rhoB, cellSize, cellLength, radius,
253 | dt, surfaceTensionIntensity, airPressure);
254 | // step 3: pressure force
255 | project(fluids, boundaries,
256 | cellStartFluid, cellStartBoundary, rho0, stiff,
257 | cellSize, cellLength, radius, dt);
258 | // step 4:: advection
259 | advect(fluids, dt, spaceSize);
260 | }
261 |
262 | void BasicSPHSolver::handleSurface(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
263 | const DArray& cellStartFluid, const DArray& cellStartBoundary,
264 | float rho0, float rhoB, int3 cellSize, float cellLength, float radius,
265 | float dt, float surfaceTensionIntensity, float airPressure)
266 | {
267 | // the free surface handling method is from
268 | // [2014][TOG][Robust Simulation of Small-Scale Thin Features in SPH-based Free Surface Flows]
269 | // use bufferFloat3 as color gradient array
270 | surfaceDetection(bufferFloat3, fluids, boundaries,
271 | cellStartFluid, cellStartBoundary,
272 | rho0, rhoB, cellSize, cellLength, radius);
273 | applySurfaceEffects(fluids, bufferFloat3, cellStartFluid,
274 | rho0, cellSize, cellLength, radius, dt, surfaceTensionIntensity, airPressure);
275 | }
276 |
277 | __device__ auto contributeColorGrad_fluid(float3& numerator, float& denominator, const int i, float3* pos, float* mass, int j, const int cellEnd, const float radius, const float rho0) -> void
278 | {
279 | while (j < cellEnd)
280 | {
281 | numerator += mass[j] / rho0 * cubic_spline_kernel_gradient(pos[i] - pos[j], radius);
282 | denominator += mass[j] / rho0 * cubic_spline_kernel(length(pos[i] - pos[j]), radius);
283 | ++j;
284 | }
285 | return;
286 | }
287 |
288 | __device__ void contributeColorGrad_boundary(float3& numerator, float& denominator, float3* pos_i, float3* pos, float* mass, int j, const int cellEnd, const float radius, const float rhoB)
289 | {
290 | while (j < cellEnd)
291 | {
292 | numerator += mass[j] / rhoB * cubic_spline_kernel_gradient(*pos_i - pos[j], radius);
293 | denominator += mass[j] / rhoB * cubic_spline_kernel(length(*pos_i - pos[j]), radius);
294 | ++j;
295 | }
296 | return;
297 | }
298 |
299 | __global__ void computeColorGrad_CUDA(float3* colorGrad, float3* posFluid, float* massFluid, const int num, int* cellStartFluid, const int3 cellSize,
300 | float3* posBoundary, float* massBoudnary, int* cellStartBoundary, const float cellLength, const float radius, const float rho0, const float rhoB)
301 | {
302 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
303 | if (i >= num) return;
304 | auto c_g = make_float3(0.0f);
305 | auto denominator = 0.0f;
306 | #pragma unroll
307 | for (auto m = 0; m < 27; __syncthreads(), ++m)
308 | {
309 | const auto cellID = particlePos2cellIdx(
310 | make_int3(posFluid[i] / cellLength) + make_int3(m / 9 - 1, (m % 9) / 3 - 1, m % 3 - 1), cellSize);
311 | if (cellID == (cellSize.x * cellSize.y * cellSize.z)) continue;
312 | contributeColorGrad_fluid(c_g, denominator, i, posFluid, massFluid, cellStartFluid[cellID], cellStartFluid[cellID + 1], radius, rho0);
313 | contributeColorGrad_boundary(c_g, denominator, &posFluid[i], posBoundary, massBoudnary, cellStartBoundary[cellID], cellStartBoundary[cellID + 1], radius, rhoB);
314 | }
315 |
316 | colorGrad[i] = c_g / fmaxf(EPSILON, denominator);
317 | return;
318 | }
319 |
320 | void BasicSPHSolver::surfaceDetection(DArray& colorGrad, const std::shared_ptr& fluids, const std::shared_ptr& boundaries,
321 | const DArray& cellStartFluid, const DArray& cellStartBoundary,
322 | float rho0, float rhoB, int3 cellSize, float cellLength, float radius)
323 | {
324 | computeColorGrad_CUDA <<<(fluids->size()-1)/block_size+1, block_size>>> (colorGrad.addr(),
325 | fluids->getPosPtr(), fluids->getMassPtr(), fluids->size(), cellStartFluid.addr(),
326 | cellSize, boundaries->getPosPtr(),
327 | boundaries->getMassPtr(), cellStartBoundary.addr(), cellLength,
328 | radius, rho0, rhoB);
329 | return;
330 | }
331 |
332 | __device__ void contributeSurfaceTensionAndAirPressure(float3& a, const int i, float3* pos, float* mass,
333 | float3* color_grad, int j, const int cellEnd, const float radius,
334 | const float rho0, const float color_energy_coefficient, const float airPressure)
335 | {
336 | while (j < cellEnd)
337 | {
338 | // surface tension
339 | a += 0.25f * mass[j] / (rho0 * rho0) * color_energy_coefficient
340 | * (dot(color_grad[i], color_grad[i]) + dot(color_grad[j], color_grad[j]))
341 | * surface_tension_kernel_gradient(pos[i] - pos[j], radius);
342 | // air pressure
343 | a += airPressure * mass[j] / (rho0 * rho0)
344 | * cubic_spline_kernel_gradient(pos[i] - pos[j], radius)
345 | /*following terms disable inner particles*/
346 | * length(color_grad[i]) / fmaxf(EPSILON, length(color_grad[i]));
347 | ++j;
348 | }
349 | return;
350 | }
351 |
352 | __global__ void surfaceTensionAndAirPressure_CUDA(float3* vel, float3* pos_fluid, float* mass_fluid,
353 | float3* color_grad, const int num, int* cellStart, const int3 cellSize, const float cellLength, const float radius, const float dt,
354 | const float rho0, const float color_energy_coefficient, const float airPressure)
355 | {
356 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
357 | if (i >= num) return;
358 | auto a = make_float3(0.0f);
359 | #pragma unroll
360 | for (auto m = 0; m < 27; __syncthreads(), ++m)
361 | {
362 | const auto cellID = particlePos2cellIdx(
363 | make_int3(pos_fluid[i] / cellLength) + make_int3(m / 9 - 1, (m % 9) / 3 - 1, m % 3 - 1), cellSize);
364 | if (cellID == (cellSize.x * cellSize.y * cellSize.z)) continue;
365 | contributeSurfaceTensionAndAirPressure(a, i, pos_fluid, mass_fluid, color_grad, cellStart[cellID], cellStart[cellID + 1],
366 | radius, rho0, color_energy_coefficient, airPressure);
367 | }
368 | vel[i] += a * dt;
369 | return;
370 | }
371 |
372 | void BasicSPHSolver::applySurfaceEffects(std::shared_ptr& fluids, const DArray& colorGrad,
373 | const DArray& cellStartFluid, float rho0, int3 cellSize, float cellLength,
374 | float radius, float dt, float surfaceTensionIntensity, float airPressure)
375 | {
376 | int num = fluids->size();
377 | surfaceTensionAndAirPressure_CUDA <<<(num - 1) / block_size + 1, block_size>>> (fluids->getVelPtr(),
378 | fluids->getPosPtr(), fluids->getMassPtr(), colorGrad.addr(),
379 | num, cellStartFluid.addr(), cellSize, cellLength, radius, dt, rho0,
380 | surfaceTensionIntensity, airPressure);
381 | }
382 |
--------------------------------------------------------------------------------
/src/BasicSPHSolver.h:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #pragma once
19 |
20 | class BasicSPHSolver: public BaseSolver {
21 | public:
22 | virtual void step(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
23 | const DArray& cellStartFluid, const DArray& cellStartBoundary, float3 spaceSize,
24 | int3 cellSize, float cellLength, float radius, float dt,
25 | float rho0, float rhoB, float stiff, float visc, float3 G,
26 | float surfaceTensionIntensity, float airPressure) override;
27 | explicit BasicSPHSolver(int num) :bufferFloat3(num) {}
28 | virtual ~BasicSPHSolver() noexcept { }
29 | protected:
30 | virtual void force(std::shared_ptr& fluids, float dt, float3 G) override final;
31 | virtual void advect(std::shared_ptr& fluids, float dt, float3 spaceSize) override final;
32 | virtual void project(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
33 | const DArray& cellStartFluid, const DArray& cellStartBoundary, float rho0, float stiff,
34 | int3 cellSize, float cellLength, float radius, float dt);
35 | virtual void diffuse(std::shared_ptr& fluids, const DArray& cellStartFluid,
36 | int3 cellSize, float cellLength, float rho0,
37 | float radius, float visc, float dt);
38 | virtual void handleSurface(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
39 | const DArray& cellStartFluid, const DArray& cellStartBoundary,
40 | float rho0, float rhoB, int3 cellSize, float cellLength, float radius,
41 | float dt, float surfaceTensionIntensity, float airPressure);
42 | private:
43 | DArray bufferFloat3;
44 | void computeDensity(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
45 | const DArray& cellStartFluid, const DArray& cellStartBoundary, int3 cellSize, float cellLength, float radius) const;
46 | void surfaceDetection(DArray& colorGrad, const std::shared_ptr& fluids, const std::shared_ptr& boundaries,
47 | const DArray& cellStartFluid, const DArray& cellStartBoundary,
48 | float rho0, float rhoB, int3 cellSize, float cellLength, float radius);
49 | void applySurfaceEffects(std::shared_ptr& fluids, const DArray& colorGrad,
50 | const DArray& cellStartFluid, float rho0, int3 cellSize, float cellLength,
51 | float radius, float dt, float surfaceTensionIntensity, float airPressure);
52 | };
--------------------------------------------------------------------------------
/src/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | set(shaderfile particles.frag particles.vert)
2 | file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/${shaderfile}
3 | DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
4 |
5 | set(headers
6 | BaseSolver.h
7 | BasicSPHSolver.h
8 | DArray.h
9 | DFSPHSolver.h
10 | global.h
11 | Particles.h
12 | PBDSolver.h
13 | ShaderUtility.h
14 | SPHParticles.h
15 | SPHSystem.h
16 | CUDAFunctions.cuh
17 | )
18 |
19 | set(source
20 | BasicSPHSolver.cu
21 | DFSPHSolver.cu
22 | Particles.cu
23 | PBDSolver.cu
24 | SPHSystem.cu
25 | vbo.cu
26 | ShaderUtility.cpp
27 | main.cpp
28 | )
29 |
30 | add_executable(CPP_Fluid_Particles
31 | ${headers}
32 | ${source}
33 | )
34 |
35 | if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
36 | # Optimization options for C/C++
37 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /O2 /Ob2 /Ot /Oi /Gy /MP")
38 | # Optimization options for C/C++ Linkers
39 | set_property(TARGET CPP_Fluid_Particles APPEND PROPERTY LINK_FLAGS "/OPT:REF /OPT:ICF")
40 | endif(CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
41 |
42 | # Optimization options for CUDA C/C++
43 | set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} --expt-extended-lambda -use_fast_math -Xcompiler \"/wd 4819 /wd 4267 /FS\"")
44 |
45 | set(Libs glew64)
46 | target_link_libraries(CPP_Fluid_Particles ${Libs})
47 |
48 | #copy dlls
49 | add_custom_command(
50 | TARGET CPP_Fluid_Particles
51 | POST_BUILD
52 | COMMAND ${CMAKE_COMMAND} -E copy_directory
53 | "${CUDASAMPLESROOT}/bin/win64/Release"
54 | $
55 | )
56 |
57 | #copy shader files
58 | add_custom_command(
59 | TARGET CPP_Fluid_Particles
60 | POST_BUILD
61 | COMMAND ${CMAKE_COMMAND} -E copy_directory
62 | "${CUDASAMPLESROOT}/bin/win64/Release"
63 | $
64 | COMMAND ${CMAKE_COMMAND} -E copy
65 | ${CMAKE_CURRENT_SOURCE_DIR}/${shaderfile}
66 | $
67 | )
--------------------------------------------------------------------------------
/src/CUDAFunctions.cuh:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #pragma once
19 |
20 | #include
21 | #include "global.h"
22 |
23 | static inline __device__ float cubic_spline_kernel(const float r, const float radius)
24 | {
25 | const auto q = 2.0f * fabs(r) / radius;
26 | //return (q < EPSILON) ? 0.0f :
27 | // ((q) <= 1.0f ? (powf(2.0f - q, 3) - 4.0f * powf(1.0f - q, 3)) :
28 | // (q) <= 2.0f ? (powf(2.0f - q, 3)) :
29 | // 0.0f) / (4.0f * PI * powf(radius, 3));
30 | if (q > 2.0f || q < EPSILON) return 0.0f;
31 | else {
32 | const auto a = 0.25f / (PI * radius * radius * radius);
33 | return a * ((q > 1.0f) ? (2.0f - q) * (2.0f - q) * (2.0f - q) : ((3.0f * q - 6.0f) * q * q + 4.0f));
34 | }
35 | }
36 |
37 | static inline __device__ float3 cubic_spline_kernel_gradient(const float3 r, const float radius)
38 | {
39 | const auto q = 2.0f * length(r) / radius;
40 | //return
41 | // ((q) <= 1.0f ? -(3.0f * (2.0f - q) * (2.0f - q) - 12.0f * (1.0f - q) * (1.0f - q)) :
42 | // (q) <= 2.0f ? -(3.0f * (2.0f - q) * (2.0f - q)) :
43 | // 0.0f) / (2.0f * PI * powf(radius, 4)) * r / fmaxf(EPSILON, length(r));
44 | if (q > 2.0f) return make_float3(0.0f);
45 | else {
46 | //const auto a = r / ((length(r) + EPSILON) * 2.0f * PI * radius * radius * radius * radius);
47 | const auto a = r / (PI * (q + EPSILON) * radius * radius * radius * radius * radius);
48 | return a * ((q > 1.0f) ? ((12.0f - 3.0f * q) * q - 12.0f) : ((9.0f * q - 12.0f) * q));
49 | }
50 | }
51 |
52 | static inline __device__ float viscosity_kernel_laplacian(const float r, const float radius) {
53 | return (r <= radius) ? (45.0f * (radius - r) / (PI * powf(radius, 6))) : 0.0f;
54 | }
55 |
56 | static __global__ void countingInCell_CUDA(int* cellStart, int* particle2cell, const int num)
57 | {
58 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
59 | if (i >= num) return;
60 | atomicAdd(&cellStart[particle2cell[i]], 1);
61 | return;
62 | }
63 |
64 | static inline __device__ int particlePos2cellIdx(const int3 pos, const int3 cellSize)
65 | {
66 | // return (cellSize.x*cellSize.y*cellSize.z) if the particle is out of the grid
67 | return (pos.x >= 0 && pos.x < cellSize.x && pos.y >= 0 && pos.y < cellSize.y && pos.z >= 0 && pos.z < cellSize.z) ?
68 | (((pos.x * cellSize.y) + pos.y) * cellSize.z + pos.z)
69 | : (cellSize.x * cellSize.y * cellSize.z);
70 | }
71 |
72 | static __global__ void mapParticles2Cells_CUDA(int* particles2cells, float3* pos, const float cellLength, const int3 cellSize, const int num)
73 | {
74 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
75 | if (i >= num) return;
76 | particles2cells[i] = particlePos2cellIdx(make_int3(pos[i] / cellLength), cellSize);
77 | return;
78 | }
79 |
80 | // smoothing kernel in [2013][SIGGRAPH ASIA][Versatile Surface Tension and Adhesion for SPH Fluids].
81 | // it's already been 3D spherical normalized.
82 | inline __device__ float3 surface_tension_kernel_gradient(float3 r, const float radius)
83 | {
84 | const auto x = length(r);
85 | //return
86 | // (x < EPSILON) ? make_float3(0.0f) : (
87 | // 2.0f * x <= radius ? 2.0f * powf((radius - x), 3) * powf(x, 3) - 0.0156f * powf(radius, 6) :
88 | // x <= radius ? powf((radius - x), 3) * powf(x, 3) :
89 | // 0.0f) * 136.0241f / (PI * powf(radius, 9)) * -r / fmaxf(EPSILON, x);
90 | if (x > radius || x < EPSILON) return make_float3(0.0f);
91 | else {
92 | auto cube = [](float x) {return x * x * x; };
93 | const float3 a = 136.0241f * -r / (PI * cube(radius) * cube(radius) * cube(radius) * x);
94 | return a * ((2.0f * x <= radius) ?
95 | (2.0f * cube(radius - x) * cube(x) - 0.0156f * cube(radius) * cube(radius)) :
96 | (cube(radius - x) * cube(x)));
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/src/DArray.h:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #pragma once
19 | #include "global.h"
20 |
21 | template
22 | class DArray {
23 | static_assert(
24 | std::is_same::value || std::is_same::value ||
25 | std::is_same::value, "DArray must be of int, float or float3.");
26 | public:
27 | explicit DArray(const unsigned int length) :
28 | _length(length),
29 | d_array([length]() {
30 | T* ptr;
31 | CUDA_CALL(cudaMalloc((void**)& ptr, sizeof(T) * length));
32 | std::shared_ptr t(new(ptr)T[length], [](T* ptr) {CUDA_CALL(cudaFree(ptr)); });
33 | return t;
34 | }()) {
35 | this->clear();
36 | }
37 |
38 | DArray(const DArray&) = delete;
39 | DArray& operator=(const DArray&) = delete;
40 |
41 | T* addr(const int offset= 0) const {
42 | return d_array.get() + offset;
43 | }
44 |
45 | unsigned int length() const { return _length; }
46 | void clear()
47 | { CUDA_CALL(cudaMemset(this->addr(), 0, sizeof(T) * this->length())); }
48 |
49 | ~DArray() noexcept { }
50 |
51 | private:
52 | const unsigned int _length;
53 | const std::shared_ptr d_array;
54 | };
--------------------------------------------------------------------------------
/src/DFSPHSolver.cu:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include "CUDAFunctions.cuh"
26 | #include "DArray.h"
27 | #include "Particles.h"
28 | #include "SPHParticles.h"
29 | #include "BaseSolver.h"
30 | #include "BasicSPHSolver.h"
31 | #include "DFSPHSolver.h"
32 |
33 | void DFSPHSolver::step(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
34 | const DArray& cellStartFluid, const DArray& cellStartBoundary, float3 spaceSize,
35 | int3 cellSize, float cellLength, float radius, float dt,
36 | float rho0, float rhoB, float stiff, float visc, float3 G,
37 | float surfaceTensionIntensity, float airPressure)
38 | {
39 | // the order of steps is slighted adjusted to accomodate the call from step() in SPHSystem.cu
40 |
41 | // step 1: update neighborhodd
42 | // done by caller of this function
43 |
44 | // step 2: compute density and alpha
45 | computeDensityAlpha(fluids, boundaries, cellStartFluid, cellStartBoundary,
46 | cellSize, cellLength, radius);
47 |
48 | // step 3: correct divergence error
49 | auto it_div = correctDivergenceError(fluids, boundaries, cellStartFluid, cellStartBoundary,
50 | rho0, cellSize, cellLength, radius, dt,
51 | divergenceErrorThreshold, maxIter);
52 |
53 | // step 4: non-pressure forces
54 | force(fluids, dt, G);
55 | diffuse(fluids, cellStartFluid, cellSize,
56 | cellLength, rho0, radius,
57 | visc, dt);
58 | if (surfaceTensionIntensity > EPSILON || airPressure > EPSILON)
59 | handleSurface(fluids, boundaries,
60 | cellStartFluid, cellStartBoundary,
61 | rho0, rhoB, cellSize, cellLength, radius,
62 | dt, surfaceTensionIntensity, airPressure);
63 |
64 | // step 5: correct density error
65 | auto it_den = project(fluids, boundaries,
66 | cellStartFluid, cellStartBoundary,
67 | rho0, cellSize, cellLength, radius, dt,
68 | densityErrorThreshold, maxIter);
69 |
70 | // step 6: advect
71 | advect(fluids, dt, spaceSize);
72 | }
73 |
74 | __device__ auto contributeDensityError_fluid(float& e, const int i, float3* pos, float3* vel, float* mass, int j, const int cellEnd, const float radius) -> void
75 | {
76 | while (j < cellEnd)
77 | {
78 | e += mass[j] * dot((vel[i] - vel[j]), cubic_spline_kernel_gradient(pos[i] - pos[j], radius));
79 | ++j;
80 | }
81 | return;
82 | }
83 |
84 | __device__ void contributeDensityError_boundary(float& e, const float3 vel_i, const float3 pos_i, float3* pos, float* mass, int j, const int cellEnd, const float radius)
85 | {
86 | while (j < cellEnd)
87 | {
88 | e += mass[j] * dot(vel_i, cubic_spline_kernel_gradient(pos_i - pos[j], radius));
89 | ++j;
90 | }
91 | return;
92 | }
93 |
94 | __global__ void computeDensityError_CUDA(float* error, float* stiff, float3* posFluid, float3* velFluid, float* massFluid, const int num,
95 | float* density, float* alpha, int* cellStartFluid, const int3 cellSize, const float cellLength, const float dt, const float rho0, const float radius,
96 | float3* posBoundary, float* massBoundary, int* cellStartBoundary)
97 | {
98 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
99 | if (i >= num) return;
100 | auto e = 0.0f;
101 | __syncthreads();
102 | #pragma unroll
103 | for (auto m = 0; m < 27; __syncthreads(), ++m)
104 | {
105 | const auto cellID = particlePos2cellIdx(
106 | make_int3(posFluid[i] / cellLength) + make_int3(m / 9 - 1, (m % 9) / 3 - 1, m % 3 - 1), cellSize);
107 | if (cellID == (cellSize.x * cellSize.y * cellSize.z)) continue;
108 | contributeDensityError_fluid(e, i, posFluid, velFluid, massFluid, cellStartFluid[cellID], cellStartFluid[cellID + 1], radius);
109 | contributeDensityError_boundary(e, velFluid[i], posFluid[i], posBoundary, massBoundary, cellStartBoundary[cellID], cellStartBoundary[cellID + 1], radius);
110 | }
111 |
112 | //clamp
113 | error[i] = fmaxf(0.0f, dt * e + density[i] - rho0);
114 | stiff[i] = error[i] * alpha[i];
115 | return;
116 | }
117 |
118 | __device__ void contributeAcceleration_fluid(float3& a, const int i, float3* pos, float* mass, float* stiff, int j, const int cellEnd, const float radius)
119 | {
120 | while (j < cellEnd)
121 | {
122 | a += mass[j] * (stiff[i] + stiff[j]) * cubic_spline_kernel_gradient(pos[i] - pos[j], radius);
123 | ++j;
124 | }
125 | return;
126 | }
127 |
128 | __device__ void contributeAcceleration_boundary(float3& a, const float3 pos_i, float3* pos, float* mass, const float stiff_i, int j, const int cellEnd, const float radius)
129 | {
130 | while (j < cellEnd)
131 | {
132 | a += mass[j] * (stiff_i)* cubic_spline_kernel_gradient(pos_i - pos[j], radius);
133 | ++j;
134 | }
135 | return;
136 | }
137 |
138 | __global__ void correctDensityError_CUDA(float3* velFluid, float3* posFluid, float* massFluid, float* stiff, const int num,
139 | int* cellStartFluid, const int3 cellSize,
140 | float3* posBoundary, float* massBoundary, int* cellStartBoundary, const float cellLength, const float dt, const float radius)
141 | {
142 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
143 | if (i >= num) return;
144 | auto a = make_float3(0.0f);
145 | __syncthreads();
146 | #pragma unroll
147 | for (auto m = 0; m < 27; __syncthreads(), ++m)
148 | {
149 | const auto cellID = particlePos2cellIdx(
150 | make_int3(posFluid[i] / cellLength) + make_int3(m / 9 - 1, (m % 9) / 3 - 1, m % 3 - 1), cellSize);
151 | if (cellID == (cellSize.x * cellSize.y * cellSize.z)) continue;
152 | contributeAcceleration_fluid(a, i, posFluid, massFluid, stiff, cellStartFluid[cellID], cellStartFluid[cellID + 1], radius);
153 | contributeAcceleration_boundary(a, posFluid[i], posBoundary, massBoundary, stiff[i], cellStartBoundary[cellID], cellStartBoundary[cellID + 1], radius);
154 | }
155 |
156 | velFluid[i] += a / dt;
157 | return;
158 | }
159 |
160 | int DFSPHSolver::project(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
161 | const DArray& cellStartFluid, const DArray& cellStartBoundary,
162 | float rho0, int3 cellSize, float cellLength, float radius, float dt,
163 | float errorThreshold, int maxIter)
164 | {
165 | int num = fluids->size();
166 | auto totalError = std::numeric_limits::max();
167 | auto iter = 0;
168 |
169 | // gather warm stiffness from last time step using particle2cell table
170 | CUDA_CALL(cudaMemcpy(bufferInt.addr(), fluids->getParticle2Cell(), sizeof(int) * num, cudaMemcpyDeviceToDevice));
171 | thrust::sort_by_key(thrust::device, bufferInt.addr(), bufferInt.addr() + num, denWarmStiff.addr());
172 | // warm start
173 | correctDensityError_CUDA << <(num - 1) / block_size + 1, block_size >> > (fluids->getVelPtr(),
174 | fluids->getPosPtr(), fluids->getMassPtr(), denWarmStiff.addr(), num,
175 | cellStartFluid.addr(), cellSize,
176 | boundaries->getPosPtr(), boundaries->getMassPtr(), cellStartBoundary.addr(),
177 | cellLength, dt, radius);
178 |
179 | // bufferFloat act as the stiffness array in the paper
180 | computeDensityError_CUDA <<<(num-1)/block_size+1, block_size>>> (error.addr(), bufferFloat.addr(),
181 | fluids->getPosPtr(), fluids->getVelPtr(), fluids->getMassPtr(), num,
182 | fluids->getDensityPtr(), alpha.addr(), cellStartFluid.addr(), cellSize, cellLength, dt, rho0, radius,
183 | boundaries->getPosPtr(), boundaries->getMassPtr(), cellStartBoundary.addr());
184 | // reset warm stiffness
185 | CUDA_CALL(cudaMemcpy(denWarmStiff.addr(), bufferFloat.addr(), sizeof(float) * num, cudaMemcpyDeviceToDevice));
186 |
187 | while ((iter<2 || totalError>errorThreshold*num * rho0) && iter < maxIter)
188 | {
189 | correctDensityError_CUDA <<<(num - 1) / block_size + 1, block_size >>> (fluids->getVelPtr(),
190 | fluids->getPosPtr(), fluids->getMassPtr(), bufferFloat.addr(), num,
191 | cellStartFluid.addr(), cellSize,
192 | boundaries->getPosPtr(), boundaries->getMassPtr(), cellStartBoundary.addr(),
193 | cellLength, dt, radius);
194 | computeDensityError_CUDA << <(num - 1) / block_size + 1, block_size >> > (error.addr(), bufferFloat.addr(),
195 | fluids->getPosPtr(), fluids->getVelPtr(), fluids->getMassPtr(), num,
196 | fluids->getDensityPtr(), alpha.addr(), cellStartFluid.addr(), cellSize, cellLength, dt, rho0, radius,
197 | boundaries->getPosPtr(), boundaries->getMassPtr(), cellStartBoundary.addr());
198 | // accumulate warm stiffness
199 | thrust::transform(thrust::device,
200 | denWarmStiff.addr(), denWarmStiff.addr() + num,
201 | bufferFloat.addr(),
202 | denWarmStiff.addr(),
203 | thrust::plus());
204 | ++iter;
205 | if (iter >= 2) {
206 | totalError = thrust::reduce(thrust::device, error.addr(), error.addr() + num, 0.0f, ThrustHelper::abs_plus());
207 | }
208 | }
209 | return iter;
210 | }
211 |
212 | __device__ void contributeDensityAlpha(float& density, float3& gradientSum, float& sampleLambda, const float3 pos_i, float3* pos, float* mass, int j, const int cellEnd, const bool isBoundary, const float radius)
213 | {
214 | while (j < cellEnd)
215 | {
216 | density += mass[j] * cubic_spline_kernel(length(pos_i - pos[j]), radius);
217 | gradientSum += mass[j] * cubic_spline_kernel_gradient(pos_i - pos[j], radius);
218 | if (!isBoundary)
219 | sampleLambda += dot(mass[j] * cubic_spline_kernel_gradient(pos_i - pos[j], radius), mass[j] * cubic_spline_kernel_gradient(pos_i - pos[j], radius));
220 | ++j;
221 | }
222 | return;
223 | }
224 |
225 | __global__ void computeDensityAlpha_CUDA(float* density, float* alpha,
226 | float3* posFluid, float* massFluid, const int num, int* cellStartFluid, const int3 cellSize,
227 | float3* posBoundary, float* massBoundary, int* cellStartBoundary,
228 | const float cellLength, const float radius)
229 | {
230 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
231 | if (i >= num) return;
232 | auto gradientSum = make_float3(0.0f);
233 | auto sampleLambda = 0.0f;
234 | auto den = 0.0f;
235 | __syncthreads();
236 | #pragma unroll
237 | for (auto m = 0; m < 27; __syncthreads(), ++m)
238 | {
239 | const auto cellID = particlePos2cellIdx(
240 | make_int3(posFluid[i] / cellLength) + make_int3(m / 9 - 1, (m % 9) / 3 - 1, m % 3 - 1), cellSize);
241 | if (cellID == (cellSize.x * cellSize.y * cellSize.z)) continue;
242 | contributeDensityAlpha(den, gradientSum, sampleLambda, posFluid[i], posFluid, massFluid, cellStartFluid[cellID], cellStartFluid[cellID + 1], false, radius);
243 | contributeDensityAlpha(den, gradientSum, sampleLambda, posFluid[i], posBoundary, massBoundary, cellStartBoundary[cellID], cellStartBoundary[cellID + 1], true, radius);
244 | }
245 |
246 | density[i] = den;
247 | alpha[i] = -1.0f / fmaxf(EPSILON, (dot(gradientSum, gradientSum) + sampleLambda));
248 | return;
249 | }
250 |
251 | void DFSPHSolver::computeDensityAlpha(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
252 | const DArray& cellStartFluid, const DArray& cellStartBoundary,
253 | int3 cellSize, float cellLength, float radius)
254 | {
255 | computeDensityAlpha_CUDA <<<(fluids->size()-1)/block_size+1, block_size >>> (fluids->getDensityPtr(), alpha.addr(),
256 | fluids->getPosPtr(), fluids->getMassPtr(), fluids->size(), cellStartFluid.addr(), cellSize,
257 | boundaries->getPosPtr(), boundaries->getMassPtr(), cellStartBoundary.addr(),
258 | cellLength, radius);
259 | }
260 |
261 | __device__ void contributeDivergenceError_fluid(float& e, const int i, float3* pos, float3* vel, float* mass, int j, const int cellEnd, const float radius)
262 | {
263 | while (j < cellEnd)
264 | {
265 | e += mass[j] * dot((vel[i] - vel[j]), cubic_spline_kernel_gradient(pos[i] - pos[j], radius));
266 | ++j;
267 | }
268 | return;
269 | }
270 |
271 | __device__ void contributeDivergenceError_boundary(float& e, const float3 pos_i, const float3 vel_i, float3* pos, float* mass, int j, const int cellEnd, const float radius)
272 | {
273 | while (j < cellEnd)
274 | {
275 | e += mass[j] * dot(vel_i, cubic_spline_kernel_gradient(pos_i - pos[j], radius));
276 | ++j;
277 | }
278 | return;
279 | }
280 |
281 | __global__ void computeDivergenceError_CUDA(float* error, float* stiff,
282 | float3* posFluid, float3* velFluid, float* massFluid, float* density, const int num,
283 | float* alpha, int* cellStartFluid, const int3 cellSize,
284 | float3* posBoundary, float* massBoundary, int* cellStartBoundary,
285 | const float cellLength, const float dt, const float rho0, const float radius)
286 | {
287 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
288 | if (i >= num) return;
289 | auto e = 0.0f;
290 | __syncthreads();
291 | #pragma unroll
292 | for (auto m = 0; m < 27; __syncthreads(), ++m)
293 | {
294 | const auto cellID = particlePos2cellIdx(
295 | make_int3(posFluid[i] / cellLength) + make_int3(m / 9 - 1, (m % 9) / 3 - 1, m % 3 - 1), cellSize);
296 | if (cellID == (cellSize.x * cellSize.y * cellSize.z)) continue;
297 | contributeDivergenceError_fluid(e, i, posFluid, velFluid, massFluid, cellStartFluid[cellID], cellStartFluid[cellID + 1], radius);
298 | contributeDivergenceError_boundary(e, posFluid[i], velFluid[i], posBoundary, massBoundary, cellStartBoundary[cellID], cellStartBoundary[cellID + 1], radius);
299 | }
300 | error[i] = fmaxf(0.0f, e);
301 | // clamp: if the predicted density is less than the rest density, compress is allowed
302 | if (density[i] + dt * error[i] < rho0 && density[i] <= rho0)
303 | error[i] = 0.0f;
304 | stiff[i] = error[i] * alpha[i];
305 | return;
306 | }
307 |
308 | __global__ void correctDivergenceError_CUDA(float3* velFluid, float3* posFluid, float* massFluid, float* stiff, const int num,
309 | int* cellStartFluid, const int3 cellSize,
310 | float3* posBoundary, float* massBoundary, int* cellStartBoundary, const float cellLength, const float radius)
311 | {
312 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
313 | if (i >= num) return;
314 | auto a = make_float3(0.0f);
315 | __syncthreads();
316 | #pragma unroll
317 | for (auto m = 0; m < 27; __syncthreads(), ++m)
318 | {
319 | const auto cellID = particlePos2cellIdx(
320 | make_int3(posFluid[i] / cellLength) + make_int3(m / 9 - 1, (m % 9) / 3 - 1, m % 3 - 1), cellSize);
321 | if (cellID == (cellSize.x * cellSize.y * cellSize.z)) continue;
322 | contributeAcceleration_fluid(a, i, posFluid, massFluid, stiff, cellStartFluid[cellID], cellStartFluid[cellID + 1], radius);
323 | contributeAcceleration_boundary(a, posFluid[i], posBoundary, massBoundary, stiff[i], cellStartBoundary[cellID], cellStartBoundary[cellID + 1], radius);
324 |
325 | }
326 |
327 | velFluid[i] += a; // dt is already included in a
328 | return;
329 | }
330 |
331 | int DFSPHSolver::correctDivergenceError(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
332 | const DArray& cellStartFluid, const DArray& cellStartBoundary,
333 | float rho0, int3 cellSize, float cellLength, float radius, float dt,
334 | float errorThreshold, int maxIter)
335 | {
336 | int num = fluids->size();
337 | auto totalError = std::numeric_limits::max();
338 | auto iter = 0;
339 |
340 | // bufferFloat again act as the stiffness array
341 | computeDivergenceError_CUDA <<<(num-1)/block_size+1, block_size>>> (error.addr(), bufferFloat.addr(),
342 | fluids->getPosPtr(), fluids->getVelPtr(), fluids->getMassPtr(), fluids->getDensityPtr(), num,
343 | alpha.addr(), cellStartFluid.addr(), cellSize,
344 | boundaries->getPosPtr(), boundaries->getMassPtr(), cellStartBoundary.addr(),
345 | cellLength, dt, rho0, radius);
346 |
347 | while ((iter<1 || totalError>errorThreshold *num* rho0) && iter < maxIter)
348 | {
349 | correctDivergenceError_CUDA <<<(num - 1) / block_size + 1, block_size>>> (fluids->getVelPtr(),
350 | fluids->getPosPtr(), fluids->getMassPtr(), bufferFloat.addr(), num,
351 | cellStartFluid.addr(), cellSize,
352 | boundaries->getPosPtr(), boundaries->getMassPtr(), cellStartBoundary.addr(),
353 | cellLength, radius);
354 | computeDivergenceError_CUDA <<<(num - 1) / block_size + 1, block_size>>> (error.addr(), bufferFloat.addr(),
355 | fluids->getPosPtr(), fluids->getVelPtr(), fluids->getMassPtr(), fluids->getDensityPtr(), num,
356 | alpha.addr(), cellStartFluid.addr(), cellSize,
357 | boundaries->getPosPtr(), boundaries->getMassPtr(), cellStartBoundary.addr(),
358 | cellLength, dt, rho0, radius);
359 | ++iter;
360 | totalError = thrust::reduce(thrust::device, error.addr(), error.addr() + num, 0.0f, ThrustHelper::abs_plus());
361 | }
362 | return iter;
363 | }
364 |
--------------------------------------------------------------------------------
/src/DFSPHSolver.h:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #pragma once
19 |
20 | class DFSPHSolver final : public BasicSPHSolver {
21 | public:
22 | virtual void step(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
23 | const DArray& cellStartFluid, const DArray& cellStartBoundary, float3 spaceSize,
24 | int3 cellSize, float cellLength, float radius, float dt,
25 | float rho0, float rhoB, float stiff, float visc, float3 G,
26 | float surfaceTensionIntensity, float airPressure) override;
27 | explicit DFSPHSolver(int num,
28 | float defaultDensityErrorThreshold = 1e-3f,
29 | float defaultDivergenceErrorThreshold = 1e-3f,
30 | int defaultMaxIter = 20)
31 | :BasicSPHSolver(num),
32 | alpha(num),
33 | bufferFloat(num),
34 | bufferInt(num),
35 | error(num),
36 | denWarmStiff(num),
37 | densityErrorThreshold(defaultDensityErrorThreshold),
38 | divergenceErrorThreshold(defaultDivergenceErrorThreshold),
39 | maxIter(defaultMaxIter){}
40 | virtual ~DFSPHSolver() noexcept { }
41 | protected:
42 | // overwrite and hide the project function in BasicSPHSolver
43 | // in project, correct density error from alpha
44 | virtual int project(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
45 | const DArray& cellStartFluid, const DArray& cellStartBoundary,
46 | float rho0, int3 cellSize, float cellLength, float radius, float dt,
47 | float errorThreshold, int maxIter);
48 |
49 | private:
50 | void computeDensityAlpha(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
51 | const DArray& cellStartFluid, const DArray& cellStartBoundary,
52 | int3 cellSize, float cellLength, float radius);
53 | int correctDivergenceError(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
54 | const DArray& cellStartFluid, const DArray& cellStartBoundary,
55 | float rho0, int3 cellSize, float cellLength, float radius, float dt,
56 | float errorThreshold, int maxIter);
57 | DArray alpha;
58 | DArray bufferFloat;
59 | DArray bufferInt;
60 | DArray error;
61 | DArray denWarmStiff;
62 | const float densityErrorThreshold;
63 | const float divergenceErrorThreshold;
64 | const int maxIter;
65 | };
--------------------------------------------------------------------------------
/src/PBDSolver.cu:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include "CUDAFunctions.cuh"
27 | #include "DArray.h"
28 | #include "Particles.h"
29 | #include "SPHParticles.h"
30 | #include "BaseSolver.h"
31 | #include "BasicSPHSolver.h"
32 | #include "PBDSolver.h"
33 |
34 | void PBDSolver::step(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
35 | const DArray& cellStartFluid, const DArray& cellStartBoundary, float3 spaceSize,
36 | int3 cellSize, float cellLength, float radius, float dt,
37 | float rho0, float rhoB, float stiff, float visc, float3 G,
38 | float surfaceTensionIntensity, float airPressure)
39 | {
40 | // the order of steps is slighted adjusted to accomodate the call from step() in SPHSystem.cu
41 |
42 | // Position-based Fluids need the position in last timestep to calculate velocity.
43 | // If it is not provided, use the current position as the history position in the next timestep.
44 | if (!posLastInitialized) {
45 | initializePosLast(fluids->getPos());
46 | throw "PBD: The last position of fluids is initialized.";
47 | }
48 | //// step 1: update local neighborhood
49 | updateNeighborhood(fluids);
50 | // step 2: iteratively correct position
51 | project(fluids, boundaries,
52 | cellStartFluid, cellStartBoundary,
53 | rho0, cellSize, spaceSize, cellLength, radius, maxIter);
54 | // step 3: calculate velocity
55 | thrust::transform(thrust::device,
56 | fluids->getPosPtr(), fluids->getPosPtr() + fluids->size(),
57 | fluidPosLast.addr(),
58 | fluids->getVelPtr(),
59 | [dt]__host__ __device__(const float3& lhs, const float3& rhs) { return (lhs - rhs)/dt; }
60 | );
61 | // step 4: apply non-pressure forces (gravity, XSPH viscosity and surface tension)
62 | diffuse(fluids, cellStartFluid, cellSize,
63 | cellLength, rho0, radius, xSPH_c);
64 | if (surfaceTensionIntensity > EPSILON || airPressure > EPSILON)
65 | handleSurface(fluids, boundaries,
66 | cellStartFluid, cellStartBoundary,
67 | rho0, rhoB, cellSize, cellLength, radius,
68 | dt, surfaceTensionIntensity, airPressure);
69 | force(fluids, dt, G);
70 |
71 | // step 5: predict position for next timestep
72 | predict(fluids, dt, spaceSize);
73 | }
74 |
75 | void PBDSolver::predict(std::shared_ptr& fluids, float dt, float3 spaceSize)
76 | {
77 | CUDA_CALL(cudaMemcpy(fluidPosLast.addr(), fluids->getPosPtr(), sizeof(float3) * fluids->size(), cudaMemcpyDeviceToDevice));
78 | advect(fluids, dt, spaceSize);
79 | }
80 |
81 | void PBDSolver::updateNeighborhood(const std::shared_ptr& particles)
82 | {
83 | const int num = particles->size();
84 | CUDA_CALL(cudaMemcpy(bufferInt.addr(), particles->getParticle2Cell(), sizeof(int) * num, cudaMemcpyDeviceToDevice));
85 | thrust::sort_by_key(thrust::device, bufferInt.addr(), bufferInt.addr() + num, fluidPosLast.addr());
86 | return;
87 | }
88 |
89 | __device__ void contributeXSPHViscosity(float3* a, const int i, float3* pos, float3* vel,
90 | float* mass, int j/*cellStart*/, const int cellEnd, const float radius) {
91 | while (j < cellEnd) {
92 | *a += mass[j]*(vel[j] - vel[i]) * cubic_spline_kernel(length(pos[i] - pos[j]), radius);
93 | ++j;
94 | }
95 | return;
96 | }
97 |
98 | __global__ void XSPHViscosity_CUDA(float3* vel, float3* pos,
99 | float *mass, const int num, int* cellStart, const int3 cellSize,
100 | const float cellLength, const float radius, const float visc, const float rho0) {
101 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
102 | if (i >= num) return;
103 | auto a = make_float3(0.0f);
104 | __syncthreads();
105 | #pragma unroll
106 | for (auto m = 0; m < 27; __syncthreads(), ++m) {
107 | const auto cellID = particlePos2cellIdx(make_int3(pos[i] / cellLength) + make_int3(m / 9 - 1, (m % 9) / 3 - 1, m % 3 - 1),
108 | cellSize);
109 | if (cellID == (cellSize.x * cellSize.y * cellSize.z)) continue;
110 | contributeXSPHViscosity(&a, i, pos, vel, mass, cellStart[cellID], cellStart[cellID + 1], radius);
111 | }
112 |
113 | vel[i] += visc * a/rho0;
114 | return;
115 | }
116 |
117 | void PBDSolver::diffuse(std::shared_ptr& fluids, const DArray& cellStartFluid,
118 | int3 cellSize, float cellLength, float rho0,
119 | float radius, float visc)
120 | {
121 | int num = fluids->size();
122 | XSPHViscosity_CUDA <<<(num - 1) / block_size + 1, block_size>>> (fluids->getVelPtr(), fluids->getPosPtr(),
123 | fluids->getMassPtr(), num, cellStartFluid.addr(), cellSize,
124 | cellLength, radius, visc, rho0);
125 | }
126 |
127 | __device__ void contributeDensityLambda(float& density, float3& gradientSum, float& sampleLambda, const float3 pos_i, float3* pos,
128 | float* mass, int j, const int cellEnd, const bool rho0, const float radius)
129 | {
130 | while (j < cellEnd)
131 | {
132 | density += mass[j] * cubic_spline_kernel(length(pos_i - pos[j]), radius);
133 | const auto gradient = - mass[j] * cubic_spline_kernel_gradient(pos_i - pos[j], radius) / rho0;
134 | gradientSum -= gradient;
135 | sampleLambda += dot(gradient, gradient);
136 | ++j;
137 | }
138 | return;
139 | }
140 |
141 | __global__ void computeDensityLambda_CUDA(float* density, float* lambda,
142 | float3* posFluid, float* massFluid, const int num, int* cellStartFluid, const int3 cellSize,
143 | float3* posBoundary, float* massBoundary, int* cellStartBoundary,
144 | const float cellLength, const float radius, const float rho0, const float relaxation)
145 | {
146 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
147 | if (i >= num) return;
148 | auto gradientSum = make_float3(0.0f);
149 | auto sampleLambda = 0.0f;
150 | auto den = 0.0f;
151 | __syncthreads();
152 | #pragma unroll
153 | for (auto m = 0; m < 27; __syncthreads(), ++m)
154 | {
155 | const auto cellID = particlePos2cellIdx(
156 | make_int3(posFluid[i] / cellLength) + make_int3(m / 9 - 1, (m % 9) / 3 - 1, m % 3 - 1), cellSize);
157 | if (cellID == (cellSize.x * cellSize.y * cellSize.z)) continue;
158 | contributeDensityLambda(den, gradientSum, sampleLambda, posFluid[i], posFluid, massFluid, cellStartFluid[cellID], cellStartFluid[cellID + 1], rho0, radius);
159 | contributeDensityLambda(den, gradientSum, sampleLambda, posFluid[i], posBoundary, massBoundary, cellStartBoundary[cellID], cellStartBoundary[cellID + 1], rho0, radius);
160 | }
161 |
162 | density[i] = den;
163 | lambda[i] = (den > rho0) ?
164 | (-(den / rho0 - 1.0f) / (dot(gradientSum, gradientSum) + sampleLambda + EPSILON))
165 | : 0.0f;
166 | lambda[i] *= relaxation;
167 | return;
168 | }
169 |
170 | __device__ void contributeDeltaPos_fluid(float3& a, const int i, float3* pos, float* lambda, float *mass, int j, const int cellEnd, const float radius)
171 | {
172 | while (j < cellEnd)
173 | {
174 | a += mass[j] * (lambda[i] + lambda[j]) * cubic_spline_kernel_gradient(pos[i] - pos[j], radius);
175 | ++j;
176 | }
177 | return;
178 | }
179 |
180 | __device__ void contributeDeltaPos_boundary(float3& a, const float3 pos_i, float3* pos, const float lambda_i, float* mass, int j, const int cellEnd, const float radius)
181 | {
182 | while (j < cellEnd)
183 | {
184 | a += mass[j] * (lambda_i)* cubic_spline_kernel_gradient(pos_i - pos[j], radius);
185 | ++j;
186 | }
187 | return;
188 | }
189 |
190 | __global__ void computeDeltaPos_CUDA(float3* deltaPos, float3* posFluid, float3* posBoundary, float *lambda,
191 | float *massFluid, float *massBoundary, const int num, int* cellStartFluid, int* cellStartBoundary, const int3 cellSize,
192 | const float cellLength, const float radius, const float rho0)
193 | {
194 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
195 | if (i >= num) return;
196 | auto dp = make_float3(0.0f);
197 | __syncthreads();
198 | #pragma unroll
199 | for (auto m = 0; m < 27; __syncthreads(), ++m)
200 | {
201 | const auto cellID = particlePos2cellIdx(
202 | make_int3(posFluid[i] / cellLength) + make_int3(m / 9 - 1, (m % 9) / 3 - 1, m % 3 - 1), cellSize);
203 | if (cellID == (cellSize.x * cellSize.y * cellSize.z)) continue;
204 | contributeDeltaPos_fluid(dp, i, posFluid, lambda, massFluid, cellStartFluid[cellID], cellStartFluid[cellID + 1], radius);
205 | contributeDeltaPos_boundary(dp, posFluid[i], posBoundary, lambda[i], massBoundary, cellStartBoundary[cellID], cellStartBoundary[cellID + 1], radius);
206 | }
207 |
208 | deltaPos[i] = dp/rho0;
209 | return;
210 | }
211 |
212 | __global__ void enforceBoundary_CUDA(float3* pos, const int num, const float3 spaceSize)
213 | {
214 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
215 | if (i >= num) return;
216 | if (pos[i].x <= spaceSize.x * .00f) { pos[i].x = spaceSize.x * .00f; }
217 | if (pos[i].x >= spaceSize.x * .99f) { pos[i].x = spaceSize.x * .99f; }
218 | if (pos[i].y <= spaceSize.y * .00f) { pos[i].y = spaceSize.y * .00f; }
219 | if (pos[i].y >= spaceSize.y * .99f) { pos[i].y = spaceSize.y * .99f; }
220 | if (pos[i].z <= spaceSize.z * .00f) { pos[i].z = spaceSize.z * .00f; }
221 | if (pos[i].z >= spaceSize.z * .99f) { pos[i].z = spaceSize.z * .99f; }
222 | return;
223 | }
224 |
225 | int PBDSolver::project(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
226 | const DArray& cellStartFluid, const DArray& cellStartBoundary,
227 | float rho0, int3 cellSize, float3 spaceSize, float cellLength,
228 | float radius, int maxIter)
229 | {
230 | int num = fluids->size();
231 | auto iter = 0;
232 | while (iter < maxIter) {
233 | // step 1: compute lambda
234 | // use bufferFloat as lambda
235 | computeDensityLambda_CUDA <<<(num - 1) / block_size + 1, block_size >>> (fluids->getDensityPtr(), bufferFloat.addr(),
236 | fluids->getPosPtr(), fluids->getMassPtr(), fluids->size(), cellStartFluid.addr(), cellSize,
237 | boundaries->getPosPtr(), boundaries->getMassPtr(), cellStartBoundary.addr(),
238 | cellLength, radius, rho0, relaxation);
239 | // step 2: compute Delta pos for density correction
240 | // use bufferFloat3 as Delta pos
241 | computeDeltaPos_CUDA << <(num - 1) / block_size + 1, block_size >> > (bufferFloat3.addr(),
242 | fluids->getPosPtr(), boundaries->getPosPtr(), bufferFloat.addr(),
243 | fluids->getMassPtr(), boundaries->getMassPtr(), num,
244 | cellStartFluid.addr(), cellStartBoundary.addr(), cellSize,
245 | cellLength, radius, rho0);
246 | // step 3: update pos
247 | thrust::transform(thrust::device,
248 | fluids->getPosPtr(), fluids->getPosPtr() + num,
249 | bufferFloat3.addr(),
250 | fluids->getPosPtr(),
251 | thrust::plus());
252 | enforceBoundary_CUDA <<<(num - 1) / block_size + 1, block_size>>>
253 | (fluids->getPosPtr(), num, spaceSize);
254 |
255 | ++iter;
256 | }
257 | return iter;
258 | }
--------------------------------------------------------------------------------
/src/PBDSolver.h:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #pragma once
19 |
20 | class PBDSolver final : public BasicSPHSolver {
21 | public:
22 | virtual void step(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
23 | const DArray& cellStartFluid, const DArray& cellStartBoundary, float3 spaceSize,
24 | int3 cellSize, float cellLength, float radius, float dt,
25 | float rho0, float rhoB, float stiff, float visc, float3 G,
26 | float surfaceTensionIntensity, float airPressure) override;
27 | explicit PBDSolver(int num,
28 | int defaultMaxIter = 20,
29 | float defaultXSPH_c = 0.05f,
30 | float defaultRelaxation = 0.75f)
31 | :BasicSPHSolver(num),
32 | maxIter(defaultMaxIter),
33 | xSPH_c(defaultXSPH_c),
34 | relaxation(defaultRelaxation),
35 | bufferInt(num),
36 | fluidPosLast(num),
37 | bufferFloat3(num),
38 | bufferFloat(num) {}
39 |
40 | explicit PBDSolver(const std::shared_ptr& particles,
41 | int defaultMaxIter = 20,
42 | float defaultXSPH_c = 0.1f,
43 | float defaultRelaxation = 1.0f)
44 | :BasicSPHSolver(particles->size()),
45 | maxIter(defaultMaxIter),
46 | xSPH_c(defaultXSPH_c),
47 | relaxation(defaultRelaxation),
48 | bufferInt(particles->size()),
49 | fluidPosLast(particles->size()),
50 | bufferFloat3(particles->size()),
51 | bufferFloat(particles->size()) {
52 | initializePosLast(particles->getPos());
53 | }
54 |
55 | virtual ~PBDSolver() noexcept { }
56 |
57 | void initializePosLast(const DArray& posFluid) {
58 | CUDA_CALL(cudaMemcpy(fluidPosLast.addr(), posFluid.addr(), sizeof(float3) * fluidPosLast.length(), cudaMemcpyDeviceToDevice));
59 | posLastInitialized = true;
60 | }
61 |
62 | protected:
63 | void predict(std::shared_ptr& fluids, float dt, float3 spaceSize);
64 |
65 | // overwrite and hide the project function in BasicSPHSolver
66 | virtual int project(std::shared_ptr& fluids, const std::shared_ptr& boundaries,
67 | const DArray& cellStartFluid, const DArray& cellStartBoundary,
68 | float rho0, int3 cellSize, float3 spaceSize, float cellLength,
69 | float radius, int maxIter);
70 |
71 | // overwrite and hide the diffuse function in BasicSPHSolver, apply XSPH viscosity
72 | virtual void diffuse(std::shared_ptr& fluids, const DArray& cellStartFluid,
73 | int3 cellSize, float cellLength, float rho0,
74 | float radius, float visc);
75 |
76 | private:
77 | bool posLastInitialized = false;
78 | const int maxIter;
79 | const float xSPH_c;
80 | const float relaxation;
81 | DArray bufferInt;
82 | DArray fluidPosLast;
83 | DArray bufferFloat3;
84 | DArray bufferFloat;
85 | void updateNeighborhood(const std::shared_ptr& particles);
86 | };
--------------------------------------------------------------------------------
/src/Particles.cu:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include "DArray.h"
26 | #include "Particles.h"
27 |
28 | void Particles::advect(float dt)
29 | {
30 | thrust::transform(thrust::device,
31 | pos.addr(), pos.addr() + size(),
32 | vel.addr(),
33 | pos.addr(),
34 | [dt]__host__ __device__(const float3& lhs, const float3& rhs) { return lhs + dt*rhs; }
35 | );
36 | }
37 |
--------------------------------------------------------------------------------
/src/Particles.h:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #pragma once
19 |
20 | class Particles {
21 | public:
22 | explicit Particles::Particles(const std::vector& p)
23 | :pos(p.size()), vel(p.size()) {
24 | CUDA_CALL(cudaMemcpy(pos.addr(), &p[0], sizeof(float3) * p.size(), cudaMemcpyHostToDevice));
25 | }
26 |
27 | Particles(const Particles&) = delete;
28 | Particles& operator=(const Particles&) = delete;
29 |
30 | unsigned int size() const {
31 | return pos.length();
32 | }
33 | float3* getPosPtr() const {
34 | return pos.addr();
35 | }
36 | float3* getVelPtr() const {
37 | return vel.addr();
38 | }
39 | const DArray& getPos() const {
40 | return pos;
41 | }
42 |
43 | void advect(float dt);
44 |
45 | virtual ~Particles() noexcept { }
46 |
47 | protected:
48 | DArray pos;
49 | DArray vel;
50 | };
51 |
--------------------------------------------------------------------------------
/src/SPHParticles.h:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #pragma once
19 |
20 | class SPHParticles final : public Particles {
21 | public:
22 | explicit SPHParticles::SPHParticles(const std::vector& p)
23 | :Particles(p),
24 | pressure(p.size()),
25 | density(p.size()),
26 | mass(p.size()),
27 | particle2Cell(p.size()) {
28 | CUDA_CALL(cudaMemcpy(pos.addr(), &p[0], sizeof(float3) * p.size(), cudaMemcpyHostToDevice));
29 | }
30 |
31 | SPHParticles(const SPHParticles&) = delete;
32 | SPHParticles& operator=(const SPHParticles&) = delete;
33 |
34 | float* getPressurePtr() const {
35 | return pressure.addr();
36 | }
37 | const DArray& getPressure() const {
38 | return pressure;
39 | }
40 | float* getDensityPtr() const {
41 | return density.addr();
42 | }
43 | const DArray& getDensity() const {
44 | return density;
45 | }
46 | int* getParticle2Cell() const {
47 | return particle2Cell.addr();
48 | }
49 | float* getMassPtr() const {
50 | return mass.addr();
51 | }
52 |
53 | virtual ~SPHParticles() noexcept { }
54 |
55 | protected:
56 | DArray pressure;
57 | DArray density;
58 | DArray mass;
59 | DArray particle2Cell; // lookup key
60 | };
61 |
--------------------------------------------------------------------------------
/src/SPHSystem.cu:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include "CUDAFunctions.cuh"
27 | #include "DArray.h"
28 | #include "Particles.h"
29 | #include "SPHParticles.h"
30 | #include "BaseSolver.h"
31 | #include "SPHSystem.h"
32 |
33 | SPHSystem::SPHSystem(
34 | std::shared_ptr& fluidParticles,
35 | std::shared_ptr& boundaryParticles,
36 | std::shared_ptr& solver,
37 | const float3 spaceSize,
38 | const float sphCellLength,
39 | const float sphSmoothingRadius,
40 | const float dt,
41 | const float sphM0,
42 | const float sphRho0,
43 | const float sphRhoBoundary,
44 | const float sphStiff,
45 | const float sphVisc,
46 | const float sphSurfaceTensionIntensity,
47 | const float sphAirPressure,
48 | const float3 sphG,
49 | const int3 cellSize)
50 | :_fluids(std::move(fluidParticles)), _boundaries(std::move(boundaryParticles)),
51 | _solver(std::move(solver)),
52 | cellStartFluid(cellSize.x* cellSize.y* cellSize.z + 1),
53 | cellStartBoundary(cellSize.x* cellSize.y* cellSize.z + 1),
54 | _spaceSize(spaceSize),
55 | _sphSmoothingRadius(sphSmoothingRadius),
56 | _sphCellLength(sphCellLength),
57 | _dt(dt),
58 | _sphRho0(sphRho0),
59 | _sphRhoBoundary(sphRhoBoundary),
60 | _sphStiff(sphStiff),
61 | _sphG(sphG),
62 | _sphVisc(sphVisc),
63 | _sphSurfaceTensionIntensity(sphSurfaceTensionIntensity),
64 | _sphAirPressure(sphAirPressure),
65 | _cellSize(cellSize),
66 | bufferInt(max(totalSize(), cellSize.x* cellSize.y* cellSize.z + 1))
67 | {
68 | // step 1: init boundary particles
69 | neighborSearch(_boundaries, cellStartBoundary);
70 | // step 2: calculate boundary particles' mass
71 | computeBoundaryMass();
72 | // step 3: init fluid particles
73 | thrust::fill(thrust::device, _fluids->getMassPtr(), _fluids->getMassPtr() + _fluids->size(), sphM0);
74 | neighborSearch(_fluids, cellStartFluid);
75 | // step 4: fill all fluid particles' properties by calling step()
76 | step();
77 | }
78 |
79 | __device__ void contributeBoundaryKernel(float* sum_kernel, const int i, const int cellID, float3* pos, int* cellStart, const int3 cellSize, const float radius)
80 | {
81 | if (cellID == (cellSize.x * cellSize.y * cellSize.z)) return;
82 | auto j = cellStart[cellID];
83 | const auto end = cellStart[cellID + 1];
84 | while (j < end)
85 | {
86 | *sum_kernel += cubic_spline_kernel(length(pos[i] - pos[j]), radius);
87 | ++j;
88 | }
89 | return;
90 | }
91 |
92 | __global__ void computeBoundaryMass_CUDA(float* mass, float3* pos, const int num, int* cellStart, const int3 cellSize, const float cellLength, const float rhoB, const float radius)
93 | {
94 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
95 | if (i >= num) return;
96 | const auto cellPos = make_int3(pos[i] / cellLength);
97 | #pragma unroll
98 | for (auto m = 0; m < 27; ++m)
99 | {
100 | const auto cellID = particlePos2cellIdx(cellPos + make_int3(m / 9 - 1, (m % 9) / 3 - 1, m % 3 - 1), cellSize);
101 | contributeBoundaryKernel(&mass[i], i, cellID, pos, cellStart, cellSize, radius);
102 | }
103 | mass[i] = rhoB / fmaxf(EPSILON, mass[i]);
104 | return;
105 | }
106 |
107 | void SPHSystem::computeBoundaryMass()
108 | {
109 | computeBoundaryMass_CUDA <<<(_boundaries->size() - 1) / block_size + 1, block_size >>> (
110 | _boundaries->getMassPtr(), _boundaries->getPosPtr(), _boundaries->size(),
111 | cellStartBoundary.addr(), _cellSize, _sphCellLength, _sphRhoBoundary, _sphSmoothingRadius);
112 | }
113 |
114 | void SPHSystem::neighborSearch(const std::shared_ptr &particles, DArray &cellStart)
115 | {
116 | int num = particles->size();
117 | mapParticles2Cells_CUDA <<<(num - 1) / block_size + 1, block_size >>> (particles->getParticle2Cell(), particles->getPosPtr(), _sphCellLength, _cellSize, num);
118 | CUDA_CALL(cudaMemcpy(bufferInt.addr(), particles->getParticle2Cell(), sizeof(int) * num, cudaMemcpyDeviceToDevice));
119 | thrust::sort_by_key(thrust::device, bufferInt.addr(), bufferInt.addr() + num, particles->getPosPtr());
120 | CUDA_CALL(cudaMemcpy(bufferInt.addr(), particles->getParticle2Cell(), sizeof(int) * num, cudaMemcpyDeviceToDevice));
121 | thrust::sort_by_key(thrust::device, bufferInt.addr(), bufferInt.addr() + num, particles->getVelPtr());
122 |
123 | thrust::fill(thrust::device, cellStart.addr(), cellStart.addr() + _cellSize.x * _cellSize.y * _cellSize.z + 1, 0);
124 | countingInCell_CUDA <<<(num - 1) / block_size + 1, block_size >>> (cellStart.addr(), particles->getParticle2Cell(), num);
125 | thrust::exclusive_scan(thrust::device, cellStart.addr(), cellStart.addr() + _cellSize.x * _cellSize.y * _cellSize.z + 1, cellStart.addr());
126 | return;
127 | }
128 |
129 | float SPHSystem::step()
130 | {
131 | cudaEvent_t start, stop;
132 | CUDA_CALL(cudaEventCreate(&start));
133 | CUDA_CALL(cudaEventCreate(&stop));
134 | CUDA_CALL(cudaEventRecord(start, 0));
135 |
136 | neighborSearch(_fluids, cellStartFluid);
137 | try {
138 | _solver->step(_fluids, _boundaries, cellStartFluid, cellStartBoundary,
139 | _spaceSize, _cellSize, _sphCellLength, _sphSmoothingRadius,
140 | _dt, _sphRho0, _sphRhoBoundary, _sphStiff, _sphVisc, _sphG,
141 | _sphSurfaceTensionIntensity, _sphAirPressure);
142 | cudaDeviceSynchronize(); CHECK_KERNEL();
143 | }
144 | catch (const char* s) {
145 | std::cout << s << "\n";
146 | }
147 | catch (...) {
148 | std::cout << "Unknown Exception at "<<__FILE__<<": line "<<__LINE__ << "\n";
149 | }
150 |
151 | float milliseconds;
152 | CUDA_CALL(cudaEventRecord(stop, 0));
153 | CUDA_CALL(cudaEventSynchronize(stop));
154 | CUDA_CALL(cudaEventElapsedTime(&milliseconds, start, stop));
155 | CUDA_CALL(cudaEventDestroy(start));
156 | CUDA_CALL(cudaEventDestroy(stop));
157 | return milliseconds;
158 | }
159 |
--------------------------------------------------------------------------------
/src/SPHSystem.h:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #pragma once
19 |
20 | class SPHSystem {
21 | public:
22 | SPHSystem(
23 | std::shared_ptr& fluidParticles,
24 | std::shared_ptr& boundaryParticles,
25 | std::shared_ptr& solver,
26 | float3 spaceSize,
27 | float sphCellLength,
28 | float sphSmoothingRadius,
29 | float dt,
30 | float sphM0,
31 | float sphRho0,
32 | float sphRhoBoundary,
33 | float sphStiff,
34 | float sphVisc,
35 | float sphSurfaceTensionIntensity,
36 | float sphAirPressure,
37 | float3 sphG,
38 | int3 cellSize);
39 | SPHSystem(const SPHSystem&) = delete;
40 | SPHSystem& operator=(const SPHSystem&) = delete;
41 |
42 | float step();
43 |
44 | int size() const {
45 | return fluidSize();
46 | }
47 | int fluidSize() const {
48 | return (*_fluids).size();
49 | }
50 | int boundarySize() const {
51 | return (*_boundaries).size();
52 | }
53 | int totalSize() const {
54 | return (*_fluids).size() + (*_boundaries).size();
55 | }
56 | auto getFluids() const {
57 | return static_cast>(_fluids);
58 | }
59 | auto getBoundaries() const {
60 | return static_cast>(_boundaries);
61 | }
62 | ~SPHSystem() noexcept { }
63 | private:
64 | std::shared_ptr _fluids;
65 | const std::shared_ptr _boundaries;
66 | std::shared_ptr _solver;
67 | DArray cellStartFluid;
68 | DArray cellStartBoundary;
69 | const float3 _spaceSize;
70 | const float _sphSmoothingRadius;
71 | const float _sphCellLength;
72 | const float _dt;
73 | const float _sphRho0;
74 | const float _sphRhoBoundary;
75 | const float _sphStiff;
76 | const float3 _sphG;
77 | const float _sphVisc;
78 | const float _sphSurfaceTensionIntensity;
79 | const float _sphAirPressure;
80 | const int3 _cellSize;
81 | DArray bufferInt;
82 | void computeBoundaryMass();
83 | void neighborSearch(const std::shared_ptr& particles, DArray& cellStart);
84 | };
--------------------------------------------------------------------------------
/src/ShaderUtility.cpp:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #include "ShaderUtility.h"
19 | #include
20 | #if defined (_WIN32)
21 | #include
22 | #endif
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 |
29 | namespace ShaderUtility {
30 | void* initGLEW()
31 | {
32 | // add for glew tools
33 | glewInit();
34 | if (!glewIsSupported("GL_VERSION_2_0 GL_VERSION_1_5 GL_ARB_multitexture GL_ARB_vertex_buffer_object")) {
35 | fprintf(stderr, "Required OpenGL extensions missing.");
36 | exit(-1);
37 | }
38 |
39 | #if defined (_WIN32)
40 | if (wglewIsSupported("WGL_EXT_swap_control")) {
41 | // disable vertical sync
42 | wglSwapIntervalEXT(0);
43 | }
44 | #endif
45 | }
46 |
47 | char* loadFile(char *fname, GLint &fSize)
48 | {
49 | char * memblock;
50 | std::string text;
51 |
52 | // file read based on example in cplusplus.com tutorial
53 | std::ifstream file (fname, std::ios::in| std::ios::binary| std::ios::ate);
54 | if (file.is_open())
55 | {
56 | const auto size = file.tellg();
57 | fSize = GLuint(size);
58 | memblock = new char [size];
59 | file.seekg (0, std::ios::beg);
60 | file.read (memblock, size);
61 | file.close();
62 | //cout << "file " << fname << " loaded" << "\n";
63 | text.assign(memblock);
64 | }
65 | else
66 | {
67 | std::cout << "Unable to open file " << fname << "\n";
68 | exit(1);
69 | }
70 | return memblock;
71 | }
72 |
73 | // printShaderInfoLog
74 | // From OpenGL Shading Language 3rd Edition, p215-216
75 | // Display (hopefully) useful error messages if shader fails to compile
76 | void printShaderInfoLog(const GLint shader)
77 | {
78 | auto infoLogLen = 0;
79 | auto charsWritten = 0;
80 |
81 | glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLen);
82 |
83 | // should additionally check for OpenGL errors here
84 |
85 | if (infoLogLen > 0)
86 | {
87 | const auto infoLog = new GLchar[infoLogLen];
88 | // error check for fail to allocate memory omitted
89 | glGetShaderInfoLog(shader,infoLogLen, &charsWritten, infoLog);
90 | std::cout << "InfoLog:\n" << infoLog << "\n";
91 | delete [] infoLog;
92 | }
93 |
94 | // should additionally check for OpenGL errors here
95 | }
96 |
97 | void printLinkInfoLog(const GLint prog)
98 | {
99 | auto infoLogLen = 0;
100 | auto charsWritten = 0;
101 |
102 | glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &infoLogLen);
103 |
104 | // should additionally check for OpenGL errors here
105 |
106 | if (infoLogLen > 0)
107 | {
108 | const auto infoLog = new GLchar[infoLogLen];
109 | // error check for fail to allocate memory omitted
110 | glGetProgramInfoLog(prog,infoLogLen, &charsWritten, infoLog);
111 | std::cout << "InfoLog:\n" << infoLog << "\n";
112 | delete [] infoLog;
113 | }
114 | }
115 |
116 | shaders_t loadShaders(char * vert_path, char * frag_path) {
117 | const auto v = glCreateShader(GL_VERTEX_SHADER);
118 | const auto f = glCreateShader(GL_FRAGMENT_SHADER);
119 |
120 | // load shaders & get length of each
121 | GLint vlen;
122 | GLint flen;
123 | const auto vs = loadFile(vert_path, vlen);
124 | const auto fs = loadFile(frag_path, flen);
125 |
126 | const char * vv = vs;
127 | const char * ff = fs;
128 |
129 | glShaderSource(v, 1, &vv,&vlen);
130 | glShaderSource(f, 1, &ff,&flen);
131 |
132 | GLint compiled;
133 |
134 | glCompileShader(v);
135 | glGetShaderiv(v, GL_COMPILE_STATUS, &compiled);
136 | if (!compiled)
137 | {
138 | std::cout << "Vertex shader not compiled.\n";
139 | printShaderInfoLog(v);
140 | system("PAUSE");
141 | }
142 |
143 | glCompileShader(f);
144 | glGetShaderiv(f, GL_COMPILE_STATUS, &compiled);
145 | if (!compiled)
146 | {
147 | std::cout << "Fragment shader not compiled.\n";
148 | printShaderInfoLog(f);
149 | system("PAUSE");
150 | }
151 | shaders_t out; out.vertex = v; out.fragment = f;
152 |
153 | delete [] vs; // dont forget to free allocated memory
154 | delete [] fs; // we allocated this in the loadFile function...
155 |
156 | return out;
157 | }
158 |
159 | void attachAndLinkProgram(const GLuint program, const shaders_t shaders) {
160 | glAttachShader(program, shaders.vertex);
161 | glAttachShader(program, shaders.fragment);
162 |
163 | glLinkProgram(program);
164 | GLint linked;
165 | glGetProgramiv(program,GL_LINK_STATUS, &linked);
166 | if (!linked)
167 | {
168 | std::cout << "Program did not link.\n";
169 | printLinkInfoLog(program);
170 | }
171 | }
172 |
173 | }
--------------------------------------------------------------------------------
/src/ShaderUtility.h:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #pragma once
19 |
20 | namespace ShaderUtility {
21 |
22 | typedef struct {
23 | unsigned int vertex;
24 | unsigned int fragment;
25 | } shaders_t;
26 |
27 | void* initGLEW();
28 |
29 | shaders_t loadShaders(char * vert_path, char * frag_path);
30 |
31 | void attachAndLinkProgram( unsigned int program, shaders_t shaders);
32 |
33 | char* loadFile(char *fname, int &fSize);
34 |
35 | // printShaderInfoLog
36 | // From OpenGL Shading Language 3rd Edition, p215-216
37 | // Display (hopefully) useful error messages if shader fails to compile
38 | void printShaderInfoLog(int shader);
39 |
40 | void printLinkInfoLog(int prog) ;
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/src/global.h:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #pragma once
19 |
20 | const int block_size = 256;
21 | #define EPSILON (1e-6f)
22 | #define PI (3.14159265358979323846f)
23 | #define CUDA_CALL(x) do { if((x)!=cudaSuccess) { printf("CUDA Error at %s:%d\t Error code = %d\n",__FILE__,__LINE__,x);}} while(0)
24 | //#define CUDA_CALL(x) do { x ;} while(0)
25 | #define CHECK_KERNEL(); {cudaError_t err = cudaGetLastError();if(err)printf("CUDA Error at %s:%d:\t%s\n",__FILE__,__LINE__,cudaGetErrorString(err));}
26 | #define MAX_A (1000.0f)
27 |
28 | namespace ThrustHelper {
29 | template
30 | struct plus {
31 | T _a;
32 | plus(const T a) :_a(a) {}
33 | __host__ __device__
34 | T operator()(const T& lhs) const {
35 | return lhs + _a;
36 | }
37 | };
38 |
39 | template
40 | struct abs_plus
41 | {
42 | __host__ __device__
43 | T operator()(const T& lhs, const T& rhs) const {
44 | return abs(lhs) + abs(rhs);
45 | }
46 | };
47 | }
--------------------------------------------------------------------------------
/src/main.cpp:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include "ShaderUtility.h"
27 | #include "DArray.h"
28 | #include "Particles.h"
29 | #include "SPHParticles.h"
30 | #include "BaseSolver.h"
31 | #include "BasicSPHSolver.h"
32 | #include "DFSPHSolver.h"
33 | #include "PBDSolver.h"
34 | #include "SPHSystem.h"
35 |
36 | // vbo and GL variables
37 | static GLuint particlesVBO;
38 | static GLuint particlesColorVBO;
39 | static GLuint m_particles_program;
40 | static const int m_window_h = 700;
41 | static const int m_fov = 30;
42 | static const float particle_radius = 0.01f;
43 | // view variables
44 | static float rot[2] = { 0.0f, 0.0f };
45 | static int mousePos[2] = { -1,-1 };
46 | static bool mouse_left_down = false;
47 | static float zoom = 0.3f;
48 | // state variables
49 | static int frameId = 0;
50 | static float totalTime = 0.0f;
51 | bool running = false;
52 | // particle system variables
53 | std::shared_ptr pSystem;
54 | const float3 spaceSize = make_float3(1.0f);
55 | const float sphSpacing = 0.02f;
56 | const float sphSmoothingRadius = 2.0f * sphSpacing;
57 | const float sphCellLength = 1.01f * sphSmoothingRadius;
58 | const float dt = 0.002f;
59 | const float sphRho0 = 1.0f;
60 | const float sphRhoBoundary = 1.4f * sphRho0;
61 | const float sphM0 = 76.596750762082e-6f;
62 | const float sphStiff = 10.0f;
63 | const float3 sphG = make_float3(0.0f, -9.8f, 0.0f);
64 | const float sphVisc = 5e-4f;
65 | const float sphSurfaceTensionIntensity = 0.0001f;
66 | const float sphAirPressure = 0.0001f;
67 | const int3 cellSize = make_int3(ceil(spaceSize.x / sphCellLength), ceil(spaceSize.y / sphCellLength), ceil(spaceSize.z / sphCellLength));
68 |
69 | namespace fluid_solver {
70 | enum { SPH, DFSPH, PBD};
71 | }
72 |
73 | void initSPHSystem(const int solver = fluid_solver::PBD) {
74 | // initiate fluid particles
75 | std::vector pos;
76 | for (auto i = 0; i < 36; ++i) {
77 | for (auto j = 0; j < 24; ++j) {
78 | for (auto k = 0; k < 24; ++k) {
79 | auto x = make_float3(0.27f + sphSpacing * j,
80 | 0.10f + sphSpacing * i,
81 | 0.27f + sphSpacing * k);
82 | pos.push_back(x);
83 | }
84 | }
85 | }
86 | auto fluidParticles = std::make_shared(pos);
87 | // initiate boundary particles
88 | pos.clear();
89 | const auto compactSize = 2 * make_int3(ceil(spaceSize.x / sphCellLength), ceil(spaceSize.y / sphCellLength), ceil(spaceSize.z / sphCellLength));
90 | // front and back
91 | for (auto i = 0; i < compactSize.x; ++i) {
92 | for (auto j = 0; j < compactSize.y; ++j) {
93 | auto x = make_float3(i, j, 0) / make_float3(compactSize - make_int3(1)) * spaceSize;
94 | pos.push_back(0.99f * x + 0.005f * spaceSize);
95 | x = make_float3(i, j, compactSize.z - 1) / make_float3(compactSize - make_int3(1)) * spaceSize;
96 | pos.push_back(0.99f * x + 0.005f * spaceSize);
97 | }
98 | }
99 | // top and bottom
100 | for (auto i = 0; i < compactSize.x; ++i) {
101 | for (auto j = 0; j < compactSize.z-2; ++j) {
102 | auto x = make_float3(i, 0, j+1) / make_float3(compactSize - make_int3(1)) * spaceSize;
103 | pos.push_back(0.99f * x + 0.005f * spaceSize);
104 | x = make_float3(i, compactSize.y - 1, j+1) / make_float3(compactSize - make_int3(1)) * spaceSize;
105 | pos.push_back(0.99f * x + 0.005f * spaceSize);
106 | }
107 | }
108 | // left and right
109 | for (auto i = 0; i < compactSize.y - 2; ++i) {
110 | for (auto j = 0; j < compactSize.z - 2; ++j) {
111 | auto x = make_float3(0, i + 1, j + 1) / make_float3(compactSize - make_int3(1)) * spaceSize;
112 | pos.push_back(0.99f * x + 0.005f * spaceSize);
113 | x = make_float3(compactSize.x - 1, i + 1, j + 1) / make_float3(compactSize - make_int3(1)) * spaceSize;
114 | pos.push_back(0.99f * x + 0.005f * spaceSize);
115 | }
116 | }
117 | auto boundaryParticles = std::make_shared(pos);
118 | // initiate solver and particle system
119 | std::shared_ptr pSolver;
120 | switch (solver) {
121 | case fluid_solver::PBD:
122 | pSolver = std::make_shared(fluidParticles->size());
123 | break;
124 | case fluid_solver::DFSPH:
125 | pSolver = std::make_shared(fluidParticles->size());
126 | break;
127 | default:
128 | pSolver = std::make_shared(fluidParticles->size());
129 | break;
130 | }
131 | pSystem = std::make_shared(fluidParticles, boundaryParticles, pSolver,
132 | spaceSize, sphCellLength, sphSmoothingRadius, dt, sphM0,
133 | sphRho0, sphRhoBoundary, sphStiff, sphVisc,
134 | sphSurfaceTensionIntensity, sphAirPressure, sphG, cellSize);
135 | }
136 |
137 | void createVBO(GLuint* vbo, const unsigned int length) {
138 | // create buffer object
139 | glGenBuffers(1, vbo);
140 | glBindBuffer(GL_ARRAY_BUFFER, *vbo);
141 |
142 | // initialize buffer object
143 | glBufferData(GL_ARRAY_BUFFER, length, nullptr, GL_DYNAMIC_DRAW);
144 | glBindBuffer(GL_ARRAY_BUFFER, 0);
145 |
146 | // register buffer object with CUDA
147 | CUDA_CALL(cudaGLRegisterBufferObject(*vbo));
148 | }
149 |
150 | void deleteVBO(GLuint* vbo) {
151 | glBindBuffer(1, *vbo);
152 | glDeleteBuffers(1, vbo);
153 |
154 | CUDA_CALL(cudaGLUnregisterBufferObject(*vbo));
155 |
156 | *vbo = NULL;
157 | }
158 |
159 | void onClose(void) {
160 | deleteVBO(&particlesVBO);
161 | deleteVBO(&particlesColorVBO);
162 | pSystem = nullptr;
163 | CUDA_CALL(cudaDeviceReset());
164 | exit(0);
165 | }
166 |
167 | namespace particle_attributes {
168 | enum { POSITION, COLOR, SIZE, };
169 | }
170 |
171 | void initGL(void) {
172 | // create VBOs
173 | createVBO(&particlesVBO, sizeof(float3) * pSystem->size());
174 | createVBO(&particlesColorVBO, sizeof(float3) * pSystem->size());
175 | // initiate shader program
176 | m_particles_program = glCreateProgram();
177 | glBindAttribLocation(m_particles_program, particle_attributes::SIZE, "pointSize");
178 | ShaderUtility::attachAndLinkProgram(m_particles_program, ShaderUtility::loadShaders("particles.vert", "particles.frag"));
179 | return;
180 | }
181 |
182 | void mouseFunc(const int button, const int state, const int x, const int y) {
183 | if (GLUT_DOWN == state) {
184 | if (GLUT_LEFT_BUTTON == button) {
185 | mouse_left_down = true;
186 | mousePos[0] = x;
187 | mousePos[1] = y;
188 | }
189 | else if (GLUT_RIGHT_BUTTON == button) {}
190 | }
191 | else {
192 | mouse_left_down = false;
193 | }
194 | return;
195 | }
196 |
197 | void motionFunc(const int x, const int y) {
198 | int dx, dy;
199 | if (-1 == mousePos[0] && -1 == mousePos[1])
200 | {
201 | mousePos[0] = x;
202 | mousePos[1] = y;
203 | dx = dy = 0;
204 | }
205 | else
206 | {
207 | dx = x - mousePos[0];
208 | dy = y - mousePos[1];
209 | }
210 | if (mouse_left_down)
211 | {
212 | rot[0] += (float(dy) * 180.0f) / 720.0f;
213 | rot[1] += (float(dx) * 180.0f) / 720.0f;
214 | }
215 |
216 | mousePos[0] = x;
217 | mousePos[1] = y;
218 |
219 | glutPostRedisplay();
220 | return;
221 | }
222 |
223 | void keyboardFunc(const unsigned char key, const int x, const int y) {
224 | switch (key) {
225 | case '1':
226 | initSPHSystem(fluid_solver::SPH);
227 | frameId = 0;
228 | totalTime = 0.0f;
229 | break;
230 | case '2':
231 | initSPHSystem(fluid_solver::DFSPH);
232 | frameId = 0;
233 | totalTime = 0.0f;
234 | break;
235 | case '3':
236 | initSPHSystem(fluid_solver::PBD);
237 | frameId = 0;
238 | totalTime = 0.0f;
239 | break;
240 | case ' ':
241 | running = !running;
242 | break;
243 | case ',':
244 | zoom *= 1.2f;
245 | break;
246 | case '.':
247 | zoom /= 1.2f;
248 | break;
249 | case 'q':
250 | case 'Q':
251 | onClose();
252 | break;
253 | case 'r':
254 | case 'R':
255 | rot[0] = rot[1] = 0;
256 | zoom = 0.3f;
257 | break;
258 | case 'n':
259 | case 'N':
260 | void oneStep();
261 | oneStep();
262 | break;
263 | default:
264 | ;
265 | }
266 | }
267 |
268 | extern "C" void generate_dots(float3* dot, float3* color, const std::shared_ptr particles);
269 |
270 | void renderParticles(void) {
271 | // map OpenGL buffer object for writing from CUDA
272 | float3 *dptr;
273 | float3 *cptr;
274 | CUDA_CALL(cudaGLMapBufferObject((void**)&dptr, particlesVBO));
275 | CUDA_CALL(cudaGLMapBufferObject((void**)&cptr, particlesColorVBO));
276 |
277 | // calculate the dots' position and color
278 | generate_dots(dptr, cptr, pSystem->getFluids());
279 |
280 | // unmap buffer object
281 | CUDA_CALL(cudaGLUnmapBufferObject(particlesVBO));
282 | CUDA_CALL(cudaGLUnmapBufferObject(particlesColorVBO));
283 |
284 |
285 | glBindBuffer(GL_ARRAY_BUFFER, particlesVBO);
286 | glVertexPointer(3, GL_FLOAT, 0, nullptr);
287 | glEnableClientState(GL_VERTEX_ARRAY);
288 |
289 | glBindBuffer(GL_ARRAY_BUFFER, particlesColorVBO);
290 | glColorPointer(3, GL_FLOAT, 0, nullptr);
291 | glEnableClientState(GL_COLOR_ARRAY);
292 |
293 | glDrawArrays(GL_POINTS, 0, pSystem->size());
294 |
295 | glDisableClientState(GL_VERTEX_ARRAY);
296 | glDisableClientState(GL_COLOR_ARRAY);
297 | return;
298 | }
299 |
300 | void oneStep() {
301 | ++frameId;
302 | const auto milliseconds = pSystem->step();
303 | totalTime += milliseconds;
304 | printf("Frame %d - %2.2f ms, avg time - %2.2f ms/frame (%3.2f FPS)\r",
305 | frameId%10000, milliseconds, totalTime / float(frameId), float(frameId)*1000.0f/totalTime);
306 | }
307 |
308 | void displayFunc(void) {
309 | if (running) {
310 | oneStep();
311 | }
312 | ////////////////////
313 | glClearColor(0.9f, 0.9f, 0.92f, 1.0f);
314 | glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
315 |
316 | glViewport(0, 0, m_window_h, m_window_h);
317 | glUseProgram(0);
318 |
319 | glMatrixMode(GL_PROJECTION);
320 | glLoadIdentity();
321 | gluPerspective(m_fov, 1.0, 0.01, 100.0);
322 | glMatrixMode(GL_MODELVIEW);
323 | glLoadIdentity();
324 | gluLookAt(0, 0, 1.0 / zoom, 0, 0, 0, 0, 1, 0);
325 |
326 | glPushMatrix();
327 | glRotatef(rot[0], 1.0f, 0.0f, 0.0f);
328 | glRotatef(rot[1], 0.0f, 1.0f, 0.0f);
329 | glColor4f(0.7f, 0.7f, 0.7f, 1.0f);
330 | glLineWidth(1.0);
331 | ////////////////////
332 | glEnable(GL_MULTISAMPLE_ARB);
333 | glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
334 | glutSolidCube(1.0);
335 | ////////////////////
336 | glUseProgram(m_particles_program);
337 | glUniform1f(glGetUniformLocation(m_particles_program, "pointScale"), m_window_h / tanf(m_fov*0.5f*float(PI) / 180.0f));
338 | glUniform1f(glGetUniformLocation(m_particles_program, "pointRadius"), particle_radius);
339 | glEnable(GL_POINT_SPRITE_ARB);
340 | glTexEnvi(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
341 | glEnable(GL_VERTEX_PROGRAM_POINT_SIZE_NV);
342 | glDepthMask(GL_TRUE);
343 | glEnable(GL_DEPTH_TEST);
344 | glPushMatrix();
345 | glTranslatef(-.5, -.5, -.5);
346 | renderParticles();
347 | glPopMatrix();
348 | ////////////////////
349 | glPopMatrix();
350 | glutSwapBuffers();
351 | glutPostRedisplay();
352 | }
353 |
354 | int main(int argc, char* argv[]) {
355 | try{
356 | glutInit(&argc, argv);
357 | glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_MULTISAMPLE);
358 | glutInitWindowPosition(400, 0);
359 | glutInitWindowSize(m_window_h, m_window_h);
360 | glutCreateWindow("");
361 | glutDisplayFunc(&displayFunc);
362 | glutKeyboardFunc(&keyboardFunc);
363 | glutMouseFunc(&mouseFunc);
364 | glutMotionFunc(&motionFunc);
365 |
366 | glewInit();
367 | ////////////////////
368 | initSPHSystem();
369 | initGL();
370 |
371 | std::cout << "Instructions\n";
372 | std::cout << "The color indicates the density of a particle.\nMagenta means higher density, navy means lesser density.\n";
373 | std::cout << "Controls\n";
374 | std::cout << "Space - Start/Pause\n";
375 | std::cout << "Key N - One Step Forward\n";
376 | std::cout << "Key Q - Quit\n";
377 | std::cout << "Key 1 - Restart Simulation Using SPH Solver\n";
378 | std::cout << "Key 2 - Restart Simulation Using DFSPH Solver\n";
379 | std::cout << "Key 3 - Restart Simulation Using PBD Solver\n";
380 | std::cout << "Key R - Reset Viewpoint\n";
381 | std::cout << "Key , - Zoom In\n";
382 | std::cout << "Key . - Zoom Out\n";
383 | std::cout << "Mouse Drag - Change Viewpoint\n\n";
384 | ////////////////////
385 | glutMainLoop();
386 | }
387 | catch (...) {
388 | std::cout << "Unknown Exception at " << __FILE__ << ": line " << __LINE__ << "\n";
389 | }
390 | return 0;
391 | }
--------------------------------------------------------------------------------
/src/particles.frag:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #version 120
19 |
20 |
21 | varying float fs_pointSize;
22 |
23 | varying vec3 fs_PosEye;
24 | varying mat4 u_Persp;
25 |
26 | void main(void)
27 | {
28 | // calculate normal from texture coordinates
29 | vec3 N;
30 |
31 | N.xy = gl_PointCoord.xy*vec2(2.0, -2.0) + vec2(-1.0, 1.0);
32 |
33 | float mag = dot(N.xy, N.xy);
34 | if (mag > 1.0) discard; // kill pixels outside circle
35 | N.z = sqrt(1.0-mag);
36 |
37 | //calculate depth
38 | vec4 pixelPos = vec4(fs_PosEye + normalize(N)*fs_pointSize,1.0f);
39 | vec4 clipSpacePos = u_Persp * pixelPos;
40 | //gl_FragDepth = clipSpacePos.z / clipSpacePos.w;
41 |
42 | gl_FragColor = vec4(exp(-mag*mag)*gl_Color.rgb,1.0f);
43 | //gl_FragColor = vec4(vec3(0.03f),1.0f);
44 | }
45 |
--------------------------------------------------------------------------------
/src/particles.vert:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #version 120
19 |
20 |
21 | uniform float pointRadius; // point size in world space
22 |
23 | attribute float pointSize;
24 | varying float fs_pointSize;
25 |
26 | varying vec3 fs_PosEye; // center of the viewpoint space
27 |
28 | uniform float pointScale;
29 | varying mat4 u_Persp;
30 |
31 | void main(void) {
32 |
33 | vec3 posEye = (gl_ModelViewMatrix * vec4(gl_Vertex.xyz, 1.0f)).xyz;
34 | float dist = length(posEye);
35 |
36 |
37 | gl_PointSize = pointRadius * pointScale/ dist;
38 |
39 | fs_PosEye = posEye;
40 |
41 | gl_FrontColor = gl_Color;
42 |
43 | u_Persp = gl_ProjectionMatrix;
44 |
45 | gl_Position = ftransform();
46 | fs_pointSize = pointSize;
47 | }
--------------------------------------------------------------------------------
/src/vbo.cu:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2019 Xiao Zhai
2 | //
3 | // This file is part of CPP-Fluid-Particles.
4 | //
5 | // CPP-Fluid-Particles is free software: you can redistribute it and/or modify
6 | // it under the terms of the GNU General Public License as published by
7 | // the Free Software Foundation, either version 3 of the License, or
8 | // (at your option) any later version.
9 | //
10 | // CPP-Fluid-Particles is distributed in the hope that it will be useful,
11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | // GNU General Public License for more details.
14 | //
15 | // You should have received a copy of the GNU General Public License
16 | // along with CPP-Fluid-Particles. If not, see .
17 |
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include "DArray.h"
23 | #include "Particles.h"
24 | #include "SPHParticles.h"
25 |
26 | __global__ void generate_dots_CUDA(float3* dot, float3* posColor, float3* pos, float* density, const int num)
27 | {
28 | const unsigned int i = __mul24(blockIdx.x, blockDim.x) + threadIdx.x;
29 | if (i >= num) return;
30 |
31 | dot[i] = pos[i];
32 | if (density[i] < 0.75f) {
33 | posColor[i] = make_float3(0.34f, 0.46f, 0.7f);
34 | }
35 | else if (density[i] < 1.0f) {
36 | const auto w = (density[i] - 0.75f) * 4.0f;
37 | posColor[i] = w * make_float3(0.9f) + (1 - w) * make_float3(0.34f, 0.46f, 0.7f);
38 | }
39 | else {
40 | auto w = (powf(density[i], 2) - 1.0f)*4.0f;
41 | w = fminf(w, 1.0f);
42 | posColor[i] = (1-w)*make_float3(0.9f) + w*make_float3(1.0f, 0.4f, 0.7f);
43 | }
44 | }
45 |
46 | extern "C" void generate_dots(float3* dot, float3* color, const std::shared_ptr particles) {
47 | generate_dots_CUDA <<<(particles->size() - 1) / block_size + 1, block_size >>>
48 | (dot, color, particles->getPosPtr(), particles->getDensityPtr(), particles->size());
49 | cudaDeviceSynchronize(); CHECK_KERNEL();
50 | return;
51 | }
--------------------------------------------------------------------------------