Deadlock
Deadlock
  • 4
  • 230 946
How to make HUGE N-Body Simulations (N=1,000,000+)
This is my implementation of the Barnes-Hut algorithm for calculating the mutual gravitational forces of N bodies in time complexity O(N log N). The video starts with a quick introduction to the problem and then gives the key insights that allow the algorithm to work. I then show how I implemented it in code and I also point to how you can improve the algorithm beyond what was defined in the original paper.
This is the third video in a playlist on gravity simulations which you can find here: ua-cam.com/play/PLj66_2EKS5gzXSiIR-WfXmVmrHfK7XW-S.html&si=mV_R8fxhRPbrlHBs
Code: github.com/DeadlockCode/barnes-hut
Chapters:
0:00 - Intro
0:18 - Problem
0:46 - Solution
2:28 - Quadtree
4:09 - Construction
4:59 - Propagation
6:04 - Acceleration
7:23 - Improvements
8:58 - Collisions
9:15 - Outro
Переглядів: 95 100

Відео

Making an N-Body Simulation
Переглядів 17 тис.Рік тому
Making an n-body gravity simulation without wasting any time. After this 9 minute tutorial, you should have all the knowledge you need to make your own basic n-body simulation in your preferred programming language and most importantly, you might even understand it. I try to keep my videos relevant, no matter what language you use, as long as there's no language explicitly specified in the titl...
Lightning Fast Circle Rendering
Переглядів 100 тис.Рік тому
Creating a framework to simplify the process of creating particle simulations. Using Rust as the programming language, winit for windowing, WGPU for graphics, and last but not least egui as the graphical user interface. This video is some 'highlights' during the creation of said framework. It is not a line-by-line tutorial but, instead just some things to keep in mind if you decide to go down t...
Mesh from Math - The basics of Marching Cubes
Переглядів 18 тис.Рік тому
An explanation and implementation of marching cubes written in rust, but the general algorithm is adaptable to any language. Data: pastebin.com/6TN46s9p - Click "raw" if you don't see the triangulation array. Chapters: 0:00 - Intro 0:26 - It all begins with a grid 2:18 - The march of cubes 3:08 - Rust syntax interlude 4:15 - Some important data 4:52 - The end of the march 6:21 - Outro

КОМЕНТАРІ

  • @mrpocock
    @mrpocock 10 днів тому

    Would it be possible for you to describe your improved algorithm? I had a quick look at the source, but it would be fab to hear you explain it and the motivation behind it.

  • @1e1001
    @1e1001 17 днів тому

    for anti-aliasing you could probably check how SDF rendering works, since your distance comparison is pretty much an SDF already

  • @kebman
    @kebman 19 днів тому

    (x - x₀)² + (y - y₀)² + (z - z₀)² = r² --- Look ma, no polygons! :D

  • @kebman
    @kebman 19 днів тому

    Take a look at POV-Ray spheres. I think they're the most awesome things in the whole of computer graphics. Bcos they're freaking ROUND! xD

  • @farkarf
    @farkarf 21 день тому

    So this is a 2D simulation. I'm not sure how it's done in 3D, but it must be considerably more challenging. The QuadTree, for one, does not efficiently upgrade to its 3D version, an OctTree. As you increase the no. of dimensions from 2 to 3, an even larger proportion of the volume of the unit cube lies outside the unit sphere (of diameter 1). That cruft on the corners of the voxels, if you will, makes nearest neighbor searches not so efficient. A better data structure might be a kd tree, but the disadvantage there is that its tricky or near impossible to update.

    • @farkarf
      @farkarf 21 день тому

      Nice repo, btw! In Rust to boot 🤩

    • @DeadlockCode
      @DeadlockCode 21 день тому

      The Barnes-Hut algorithm does not really rely on a conventional nearest neighbor search so that will not really matter here although you do have a point. Yes, the extent of a node will grow as you increase the number of dimensions, as you say, but the average distance between points will also grow, so maybe that cancels out? I don't know. A higher dimension also means that we split into more children per level but that also means that we have fewer levels at a given number of bodies on average. You could continue counting all the ways they differ but that's besides the point. All in all, I can't really say if it would perform better or worse in 3D but what I can say is that it would still be a completely viable solution that would work great for a lot of use cases. The easiest way to know if it's still good in 3D is to just try it. For details on how to convert the 2D algorithm to 3D you can refer to question 2 in the pinned comment :)

    • @farkarf
      @farkarf 21 день тому

      @@DeadlockCode Thanks for your response. By nearest neighbor search, btw, I really meant efficiently gathering the points of mass inside a bounding region, usually defined as a sphere. If the center of such spheres are random with respect to grid coordinates, then on average about half of these (1 - Pi/6) will fall at a grid corner, requiring examining 8 adjacent OctNodes. Maybe my comment is not apt for this use case.. I'll take a closer look at Barnes Hut. I've only played Runge Kutta with few-body problems (3 or more, but not many), so this is new to me :)

  • @OmegaCat9999
    @OmegaCat9999 23 дні тому

    1:45 So, it's basically only rendering the inscribed circle of the triangle. Genius.

  • @AIMasterGuru
    @AIMasterGuru 23 дні тому

    **Great explanation of the Barnes-Hut algorithm!** The simplification of long-range interaction calculations using the center of mass approximation is brilliantly illustrated. I was wondering if you’ve considered integrating quantum fluctuations and non-locality concepts, especially for cosmological-scale applications. I've been working on a **dual-non-dual (D-ND) approach** that combines N-body simulation with quantum information theory to handle these interactions more efficiently. **Here’s a variation you can test right away in your project**: Add a **dynamic potential correction based on quantum fluctuations** for distant nodes, adjusting non-local interactions using a variance function, like so: ```python def calculate_quantum_fluctuations(node, body, variance, time): # Adds a quantum fluctuation correction based on distance distance = calculate_distance(node.position, body.position) fluctuation = variance * np.sin(time + distance) return fluctuation # Use this function during the force calculation def calculate_dual_force(node, body, variance, time): classical_force = calculate_gravitational_force(node, body) quantum_correction = calculate_quantum_fluctuations(node, body, variance, time) return classical_force + quantum_correction ``` Additionally, here’s an **abstract** that explores a novel approach you might find interesting: --- ## Abstract: We present a novel approach to improving the Barnes-Hut algorithm for N-body simulations by integrating it with a **Dual-Non-Dual (D-ND) quantum framework** within a **Quantum Operating System (QOS)**. This integration incorporates concepts from **Unified Information Theory**, particularly the emergent gravity paradigm and the dynamics of polarization. By introducing quantum fluctuations, possibility densities, and non-relational potentials, we enhance both the performance and accuracy of the algorithm. The framework utilizes a **proto-axiomatic state** to guide spatial decomposition and force calculations, potentially improving computational efficiency without compromising physical precision. ---

  • @yboris
    @yboris 24 дні тому

    Amazing work! Thank you for sharing ♥

  • @atreidesson
    @atreidesson 24 дні тому

    Did you post a question on the StackOverflow after not finding anykne asking? Otherwise you just disproved that you are the only one with this problem.

  • @MrManlop
    @MrManlop 24 дні тому

    Have you considered making use of the

    • @MrManlop
      @MrManlop 24 дні тому

      Optimizations you describe for molecular dynamics simulations?

  • @adsick_ua
    @adsick_ua 25 днів тому

    very good video

  • @christianpadilla4336
    @christianpadilla4336 25 днів тому

    Would be interesting to see for what value of n the brute force n^2 algorithm becomes worse than the approximation. Maybe ~1000? Presumably the brute force algorithm is easier to optimize and run on the GPU.

  • @ArnaudMEURET
    @ArnaudMEURET 25 днів тому

    Finally a video that goes beyond the trivial, unrealistic implementation of quad trees! Thanks for sparing me the time of rediscovering the relevant optimizations. Now on to recoding all this in a different language and runtime env … 😅

  • @mrpocock
    @mrpocock 26 днів тому

    Would this approximation work for graph layouts that use springs for links and inverse square repulsion? Seems like it should.

  • @Monkeymario.
    @Monkeymario. 26 днів тому

    Yeah I've wondered why don't games/programs just do this

  • @blakelapierre
    @blakelapierre 26 днів тому

    Wouldn't an octtree be better? Or, is this just for a 2D sim? Also, it seems this is assuming "instaneous" gravity and not gravity with a speed of propagation?

    • @DeadlockCode
      @DeadlockCode 26 днів тому

      Yes, this is 2D for the sake of demonstration but converting it to 3D via octree is trivial if you understand the 2D algorithm. And yes, this assumes Newtonian gravity so no speed limit or time dilation.

    • @blakelapierre
      @blakelapierre 26 днів тому

      @@DeadlockCode Ok, cool. Thanks!

  • @ThatKid22101
    @ThatKid22101 27 днів тому

    everyone else: me at 0:10: I literally just watched that video!

  • @Frizz-c8c
    @Frizz-c8c 27 днів тому

    Does this solve three body problem?

  • @thouys9069
    @thouys9069 27 днів тому

    great stuff!

  • @blakedehaas
    @blakedehaas 28 днів тому

    Could this be used to model atmospheric particles? I am building a machine learning model to predict the impacts of solar weather on upper atmosphere electron temperature and density, I wonder if I could model the electrons as "particle clouds" that interact with other "particle clouds" represented by a single particle.

  • @shapleyattractor
    @shapleyattractor 28 днів тому

    this is amazing, the simulation resembles the milky way and surrounding clusters when the particles spread out, also worth noting Space Engine uses oct-trees to plot their objects

  • @stickmasterlukeRBX
    @stickmasterlukeRBX 29 днів тому

    "That's outside the scope of this video" was the saddest thing to hear.

  • @Chris-hu5eq
    @Chris-hu5eq Місяць тому

    Great video, it was a pleasure to watch!

  • @thatJackBidenTalksAbout
    @thatJackBidenTalksAbout Місяць тому

    5:25 quadtrees (and their 3d cousin octrees) are oddly satisfying as a space partitioning solution, and I get a little excited whenever the opportunity to use them comes up. I'll definitely have to play with this sometime soon. perhaps see how it fares in 3d.

  • @awiewahh
    @awiewahh Місяць тому

    I'm glad you gave this video another shot, it was super informative :)

  • @mAny_oThERSs
    @mAny_oThERSs Місяць тому

    Every shape is just a bunch of triangles

  • @freedom_aint_free
    @freedom_aint_free Місяць тому

    Of course we'll build a humongous version of Asteroids game with it !

  • @cyboticIndustries
    @cyboticIndustries Місяць тому

    been having so much fun messing around with parameters on this :-) I was wondering though - coudl you make the space like in the arcade game 'Asteroids' - so whatever goes out of the screen comes in on the other side? i guess easy to do with the position - but for the gravity force we would need to imagine each body also repeated 'off the edges' of the screen

  • @poweredbytones
    @poweredbytones Місяць тому

    Please upload a video or two of the simulation. Like any great thing this ended too soon.

  • @feliz3331
    @feliz3331 Місяць тому

    Why don't you use something like the midpoint algorightm?

  • @khanch.6807
    @khanch.6807 Місяць тому

    I like your words magic man.

  • @TiggyProph
    @TiggyProph Місяць тому

    Really great work on the optimization!

  • @AntBoyification
    @AntBoyification Місяць тому

    thats insane

  • @AmeshaSpentaArmaiti
    @AmeshaSpentaArmaiti Місяць тому

    My immediate thought on hearing the problem was "can i use quad trees?" And then the answer was quad trees. My addiction is sated for now.

  • @TrueLemonz
    @TrueLemonz Місяць тому

    turn the music down pluh i can't hear you

  • @Datamining101
    @Datamining101 Місяць тому

    Now do FMM, which is **actually** a magical algorithm for this stuff.

  • @johanngambolputty5351
    @johanngambolputty5351 Місяць тому

    If you don't need synchronization between threads, and you don't mind rewriting the compute kernels in c, OpenCL is really nice for GPU, the ocl and simple_ocl rust crates make using ocl in a rust project relatively easy.

  • @wilhemfesselier8873
    @wilhemfesselier8873 Місяць тому

    Hello, I love your videos, I tried some of the things you did but didn't succeed or at least not nearly as much as you did and I would really like to ask some questions, is there any way to contact you or are you too occupied. Thanks in advance.

  • @lucasclark945
    @lucasclark945 Місяць тому

    Banger video

  • @rylvns
    @rylvns Місяць тому

    im getting error: could not find `Cargo.toml` in `C:\Users\Secondary\source epos` or any parent directory i got rust and visual studio thing idk what to do pls help

    • @DeadlockCode
      @DeadlockCode Місяць тому

      You probably already solved this but just in case you didn’t. When you run ‘cargo run -release’, the terminal should be in the same directory as where the Cargo.toml file is located. I.e. you probably just need to go one directory deeper into barnes-hut before running.

  • @alltheclovers532
    @alltheclovers532 Місяць тому

    A circle in the triangle factory? How odd.

  • @moonwatcher2001
    @moonwatcher2001 Місяць тому

    Definitely awesome ❤ Amene explanation, deep concepts, usefulband practical coding. +1 subscriber

  • @cyboticIndustries
    @cyboticIndustries Місяць тому

    so cool - and so easy to get running! thanks! I'm gonna have to learn some Rust finally!

  • @nickhill6036
    @nickhill6036 Місяць тому

    Wow this takes me back to my grad school days when I used this to simulate discrete vortices - similar 1/x^2 interaction between particles. I used tecplot for animation. This is about 2 decades ago. Not sure if tecplot still exists but I used c and openmp back then.

  • @phecdaDia
    @phecdaDia Місяць тому

    I know the description says you'd want to clean up the code first before uploading but I feel like many would great appreciate even the "messy" version to play around with / learn from it. Appreciated the video and intrigued in seeing more of it

  • @Kurell171
    @Kurell171 Місяць тому

    I like how you're not afraid to mention terms without explaining them, for example, cache locality. kinda know what it means, just enough to know that explaining it would probably double the length of the video, but i like the fact that you mentioned it anyway, for the people interested enough to learn about those terms