html – How do i put a image in particle explosion

I need to replace the particles with an image, i already tryed to do background-image: but doesn’t work.


$d: 20px;

html { overflow: hidden; background: #222; }

.particle {
    position: absolute;
    width: $d; height: $d;
    animation: shoot 3s ease-out infinite;
    animation-name: shoot, fade;
    border-radius: 50px;
    
    @for $i from 0 to 50 {
        $t: (1 + .01*random(50))*1s;
        
        &:nth-child(#{$i + 1}) {
            transform: translate(random(100)*1vw, 
                                                     random(100)*1vh);
            background: hsl(random(360), 100%, 65%);
            animation-duration: $t;
            animation-delay: -.01*random(100)*$t;
        }
    }
}

@keyframes shoot {
    0% { transform: translate(50vw, 50vh); }
}
@keyframes fade { to { opacity: 0 } }

1

python – Particle swarm algorithm with multiple threads

I wrote a simple multitthreading program which does particle swarm optimization. Optimization itself and some corresponding functions were taken from https://nathanrooy.github.io/posts/2016-08-17/simple-particle-swarm-optimization-with-python/. This is my first attempt to write multithread Python code 🙂

Code has 4 files:

  1. const.py – just some constants
  2. main.py – entry point
  3. particle.py particle class as a thread
  4. particle_producer – class which synchronizes all particles and computes next position/velocity

Thank you for your help 🙂

const.py

MAX_ITERATIONS = 300
NUMBER_OF_PARTICLES = 10
NUM_DIMENSIONS = 2

main.py

import threading
import random

from consts import NUM_DIMENSIONS, NUMBER_OF_PARTICLES
from particle import Particle
from particle_producer import ParticleSwarmProducer

import numpy as np


# Function to optimize
def fnc(x):
    total=0
    for i in range(len(x)):
        total+=x(i)**2
    return total


if __name__ == '__main__':
    x_down, x_up = (-100, 100)

    # All shared datastrucures between particles and particle producer
    dict_shared_new_position = {i: list(np.random.uniform(x_down, x_up, NUM_DIMENSIONS)) for i in range(0, NUMBER_OF_PARTICLES)}
    dict_shared_best_position = dict_shared_new_position.copy()
    dict_velocity = {i: (random.uniform(-1,1)) * NUM_DIMENSIONS for i in range(0, NUMBER_OF_PARTICLES)}
    dict_shared_errors = {i: -1 for i in range(0, NUMBER_OF_PARTICLES)}
    dict_shared_is_ready = {i: False for i in range(0, NUMBER_OF_PARTICLES)}

    bounds = ((x_down, x_up) for i in range(NUMBER_OF_PARTICLES))

    condition_wait = threading.Condition()


    producer = ParticleSwarmProducer(initial_particle_position=dict_shared_new_position,
                                     bounds=bounds,
                                     dict_shared_errors=dict_shared_errors,
                                     dict_shared_is_ready=dict_shared_is_ready,
                                     dict_shared_new_position=dict_shared_new_position,
                                     dict_shared_best_positions=dict_shared_best_position,
                                     dict_velocity=dict_velocity,
                                     condition_wait=condition_wait
                                     )

    particles = ()

    for i in range(NUMBER_OF_PARTICLES):
        p = Particle(thread_id=i,
                     name='Thread ' + str(i+1),
                     dict_shared_errors=dict_shared_errors,
                     dict_shared_is_ready=dict_shared_is_ready,
                     dict_shared_new_position=dict_shared_new_position,
                     dict_shared_best_positions=dict_shared_best_position,
                     fnc=fnc,
                     condition_wait=condition_wait)
        particles.append(p)

    producer.start()

    for p in particles:
        p.start()

    producer.join()

    for p in particles:
        p.join()

particle.py

import threading

from consts import MAX_ITERATIONS

threadLock = threading.Lock()


class Particle(threading.Thread):
    """ Represents one particle object with specific position/velocity"""
    def __init__(self,
                 thread_id,
                 name,
                 dict_shared_errors,
                 dict_shared_is_ready,
                 dict_shared_new_position,
                 dict_shared_best_positions,
                 fnc,
                 condition_wait
                 ):
        threading.Thread.__init__(self)

        self.thread_id = thread_id
        self.name = name

        self.dict_shared_errors = dict_shared_errors
        self.dict_shared_is_ready = dict_shared_is_ready
        self.dict_shared_new_positions = dict_shared_new_position
        self.dict_shared_best_positions = dict_shared_best_positions

        self.fnc = fnc
        self.condition_wait = condition_wait

    def run(self) -> None:

        it = 1
        best_particle_error = 9999

        while it < MAX_ITERATIONS+1:
            # print(f'{self.name} waiting for a new job...')
            threadLock.acquire(blocking=True)
            self.dict_shared_is_ready(self.thread_id) = True
            threadLock.release()

            with self.condition_wait:
                self.condition_wait.wait()

            threadLock.acquire(blocking=True)
            position = self.dict_shared_new_positions(self.thread_id)
            error = self.fnc(position)

            if error < best_particle_error:
                self.dict_shared_best_positions(self.thread_id) = position
                best_particle_error = error

            self.dict_shared_errors(self.thread_id) = self.fnc(position)

            # set to not ready
            self.dict_shared_is_ready(self.thread_id) = False
            threadLock.release()
            # print(f'{self.name} working on task')
            it +=1
            # print(f'{self.name}, {it}')

particle_producer.py

    import threading
    import time
    import random
    import numpy as np
    
    from consts import NUM_DIMENSIONS, NUMBER_OF_PARTICLES, MAX_ITERATIONS
    
    threadLock = threading.Lock()
    
    
    class ParticleSwarmProducer(threading.Thread):
        """ Synchronizes all particles and computes their next position/velocity"""
        def __init__(self,
                     initial_particle_position,
                     bounds,
                     dict_shared_errors,
                     dict_shared_is_ready,
                     dict_shared_new_position,
                     dict_shared_best_positions,
                     dict_velocity,
                     condition_wait):
    
            threading.Thread.__init__(self)
    
            self.initial_particle_positions = initial_particle_position
            self.bounds = bounds
    
            self.dict_velocity = dict_velocity
    
            self.dict_best_positions = dict_shared_best_positions
            self.dict_shared_errors = dict_shared_errors
            self.dict_shared_is_ready = dict_shared_is_ready
            self.dict_shared_new_position = dict_shared_new_position
    
            self.condition_wait = condition_wait
    
            self.current_iteration = 0
            self.err_best_g = -1  # best error for group
            self.pos_best_g = ()  # best position for group
    
            # Used for plotting
            self.output_pos = {i: np.empty((0, NUM_DIMENSIONS)) for i in range(NUMBER_OF_PARTICLES)}
    
        def run(self) -> None:
    
            i = 1
            while i < MAX_ITERATIONS+1:
                threadLock.acquire(blocking=True)
                ready = list(self.dict_shared_is_ready.values())
    
                # If all particles have finished their current jobs...
                if all(ready):
                    print(f'Iteration {i}')
                    print(f'Current positions: {self.dict_shared_new_position}')
                    print(f'Current errors: {self.dict_shared_errors}')
                    print(f'Current velocities: {self.dict_velocity}')
    
                    self.add_pos_to_out()
    
                    self.evaluate_all_particles()
                    self.update_all_particles()
    
                    print('All particles go!')
    
                    with self.condition_wait:
                        self.condition_wait.notifyAll()
                    i += 1
                threadLock.release()
                # time.sleep(0.2)
    
                time.sleep(0.02)
            with self.condition_wait:
                self.condition_wait.notifyAll()
            print(f'Current positions: {self.dict_shared_new_position}')
            print(f'Error: {self.err_best_g}')
    
    
        def evaluate_all_particles(self):
            for i in range(NUMBER_OF_PARTICLES):
                if self.dict_shared_errors(i) < self.err_best_g or self.err_best_g == -1:
                    self.pos_best_g = list(self.dict_shared_new_position(i))
                    self.err_best_g = float(self.dict_shared_errors(i))
    
        def update_all_particles(self):
            for i in range(NUMBER_OF_PARTICLES):
                self.update_velocity(i)
                self.update_position(i)
    
        def add_pos_to_out(self):
            for i in range(NUMBER_OF_PARTICLES):
                self.output_pos(i) = np.vstack((self.output_pos(i), self.dict_shared_new_position(i)))
    
        def update_velocity(self, i):
            w = 0.5  # constant inertia weight (how much to weigh the previous velocity)
            c1 = 1  # cognative constant
            c2 = 2  # social constant
    
            for j in range(0, NUM_DIMENSIONS):
                r1 = random.random()
                r2 = random.random()
    
                vel_cognitive = c1 * r1 * (self.dict_best_positions(i)(j) - self.dict_shared_new_position(i)(j))
                vel_social = c2 * r2 * (self.pos_best_g(j) - self.dict_shared_new_position(i)(j))
    
                self.dict_velocity(i)(j) = w * self.dict_velocity(i)(j) + vel_cognitive + vel_social
    
        def update_position(self, i):
            for j in range(0, NUM_DIMENSIONS):
                self.dict_shared_new_position(i)(j) = self.dict_shared_new_position(i)(j) + self.dict_velocity(i)(j)
    
                # adjust maximum position if necessary
                if self.dict_shared_new_position(i)(j) > self.bounds(i)(1):
                    self.dict_shared_new_position(i)(j) = self.bounds(i)(1)
    
                # adjust minimum position if neseccary
                if self.dict_shared_new_position(i)(j) < self.bounds(i)(0):
                    self.dict_shared_new_position(i)(j) = self.bounds(i)(0)



unity – Performance issue when particle system occupies most part of the screen

I’m using particle systems to create stars in my space sim project. The star is made off 2 particle systems: star surface (max particles: 500) and corona (max particles: 250), both use the Mobile/Particles/Additive shader, and a sphere mesh with Standard material. And it works fine and looks pretty nice, but there’s one problem:
When I get close to the star so it occupies the most part of the screen, fps drops significantly (from 60 to 30-40). This happens in editor and mobile (Samsung A8 2018), didn’t test PC standalone build yet but I’m pretty sure the result will be the same.
Disabling the sphere mesh doesn’t affect the performance. Disabling of one of the particle systems does improve performance. When the camera is relatively far away from the particles, performance is fine. Changing the scale doesn’t seem to matter, whether it’s a big star with real size radius 10 million units or a small star with radius 1 unit.
The problem occurs when the particles occupy the most part of the screen space. Changing the shaders to other available ones does change the result FPS but whatever shader I use the performance drop is still there.

So, the question is: are there some tips, workarounds or something? Or do I have to write a custom shader? Or changing shaders won’t help anyway?
I’m using built-in render pipeline, by the way. Tried URP and while fps is a bit higher in general, there’s still a big drop (to 40-45 fps).

unity – script + particle system don’t work unless some other game object is selected in the inspector

I have an object “SEA” emitting particles, controlled by a script using emissionRate, emissionSpeed etc.

When the particles collide with the SKY GameObject, another GameObject called “CLOUD” is instantiated. It contains a “RAIN” script and a “WATER” script. On instantiate, CLOUD is supposed to start emitting new particles, reducing the amount of stored water accordingly.

The issue is nothing happens (no emission, no water decrease) unless I manually click on another game object in the Inspector (could be anything, a text, a 3D Object etc.). This way the particle system starts working and the water starts depleting correctly every second.

I tried different approaches:

  1. disable and re-enable the CLOUD gameobject (in awake and start).

    void Awake()
    {
        cloudPrefab.gameObject.SetActive(false);
    }
    
    void Start()
    {
        cloudPrefab.gameObject.SetActive(true);
    }
    
  2. switch the focus on another object. This way it works (partially) but there is a huge decrease in performance, so it’s not a good solution.

    void OnParticleCollision(GameObject other)
    {
        int numCollisionEvents = psEvap.GetCollisionEvents(other, collisionEvents);
        int i = 0;
    
        while (i < numCollisionEvents)
        {
            Vector3 pos = collisionEvents(i).intersection;
            Vector3 force = collisionEvents(i).velocity;// * 10;
            Instantiate(cloudPrefab, pos, Quaternion.identity);
            Selection.activeObject = other;
    
            i++;
        }
    }
    
  3. create a InvokeRepeating method that selects a different object every
    x sec. It doesn’t work + same decrease in performance.

    void Start()
    {
        InvokeRepeating("selectSomething", 1, 1);
    
    }
    void selectSomething()
    {
        Selection.activeObject = daysText;
    }
    

I’m really out of options. I think this could be a bug in Unity.

enter image description here
enter image description here
enter image description here

public class Rain : MonoBehaviour
{
    public ParticleSystem psRain;
    public List<ParticleCollisionEvent> collisionEvents;
    public int attackValue = 1;
    Water water;

    //(Range(0f, 500f))
    //public float emissionRate = 30;

    //(Range(1f, 50f))
    //public float emissionSpeed = 1;

    //(Range(1.0f, 100f))
    //public float particleLife;

    //public GameObject cloudPrefab;

 
    void Start()
    {

        psRain = GetComponent<ParticleSystem>();
        collisionEvents = new List<ParticleCollisionEvent>();
        water = GetComponent<Water>();

        //emissionRate = 1;
        //emissionSpeed = 5;
        //evaporationPoint = water.waterMax / 1000;
    }


    void Update()
    {
        //SceneView.FrameLastActiveSceneView();
        //SceneView.FrameLastActiveSceneView();



        //var main = psRain.main;
        //var emission = psRain.emission;

        //main.maxParticles = Mathf.RoundToInt(emissionRate * 1000);
        //main.startSpeed = emissionSpeed;
        //particleLife = 20.0f;
        //main.startLifetime = particleLife;

        if (water.waterCurrent > 0)
        {

            //emission.rateOverTime = emissionRate;
            psRain.Play();
            water.waterCurrent -= psRain.particleCount;
            //Level.cluodsInGame += psEvap.particleCount/10;

        }

        if (water.waterCurrent <= 0)
        {
            psRain.Stop();
        }
    }

    void OnParticleCollision(GameObject other)
    {
        int numCollisionEvents = psRain.GetCollisionEvents(other, collisionEvents);
        int i = 0;

        while (i < numCollisionEvents)
        {
            Water waterSource = other.GetComponent<Water>();

            if (waterSource != null)
            {
                Vector3 pos = collisionEvents(i).intersection;
                Vector3 force = collisionEvents(i).velocity;// * 10;
                //rb.AddForce(force);
                waterSource.TakeDamage(attackValue);

            }
            i++;
        }
    }

    int GetAliveParticles()
    {
        ParticleSystem.Particle() particles = new ParticleSystem.Particle(psRain.particleCount);
        return psRain.GetParticles(particles);
    }
}



public class Water : MonoBehaviour
{
    public float waterMax;
    public float waterCurrent;

    public TMP_Text waterText;
    bool isDead;



    void Start()
    {
        if (tag == "water")
        {
            waterCurrent = waterMax;
        }

        if (tag == "sea")
        {
            waterCurrent = waterMax;
            //waterCurrent = float.PositiveInfinity;

        }

        if (tag == "cloud")
        {
            waterCurrent = 10000;
        }

        //if (tag == "sky")
        //{
        //    waterText.gameObject.SetActive(false);

        //}
    }


    void Update()
    {
        waterText.text = waterCurrent.ToString();

        if (waterCurrent <= 0)
        {
            waterCurrent = 0;
        }
    }

    public void TakeDamage(int amount)
    {
        waterCurrent += amount;

        if (waterCurrent <= 0 && !isDead)
        {
            //StartCoroutine(Death());
        }
    }
}

directx11 – ID3D11DeviceContext:::CopyResource is bottleneck in my particle system

I have a snow particle system and I use simplex noise for creating turbulence effect.
At first, I made calculations on the CPU, and the simplex noise calls obviously were the bottleneck.
The MAX_NUM_PARTICLES limit was 50k (to hold the 60 fps). There was a fatal drop for 75-100k.

That’s why I moved the calculation to compute shader like here.

Snow particle system is working, however, I got a weird result: the fps limit left the same, but it does not fall so critically — I can render 100-200k with 45 fps.

At first, I played with Dispatch params, but the fps was the same for 512, 1, 1 and 1, 1, 1 calls.
Second, I convinced that simplex noise calculations were not a problem just passing input coordinates into the output buffer.

Then I commented out different parts of the code and realized that ID3D11DeviceContext:::CopyResource is the bottleneck. I use RWStructuredBuffer buffer to gain compute shader results and, as I know, it requires additional buffer with D3D11_USAGE_STAGING usage and D3D11_CPU_ACCESS_READ flag. So think I can’t refuse to use it.

Please share your ideas What can I do about it?

Code part:

    // Create a system memory version of the buffer to read the results back from.
    outputDesc.Usage = D3D11_USAGE_STAGING;
    outputDesc.BindFlags = 0;
    outputDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;

    result = (device->CreateBuffer(&outputDesc, 0, &mRWOutputBuffer));
    if (FAILED(result))
        return false;

    D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc;
    uavDesc.Buffer.FirstElement = 0;
    uavDesc.Buffer.Flags = 0;
    uavDesc.Buffer.NumElements = m_pParticleSystem->GetInstaceCount();
    uavDesc.Format = DXGI_FORMAT_UNKNOWN;
    uavDesc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;

    result = device->CreateUnorderedAccessView(mRWBuffer, &uavDesc, &mRWUAV);
    if (FAILED(result))
        return false;

    m_pParticleSystem->FillConstantDataBuffer(deviceContext, mInputBuffer);

    // Enable Compute Shader
    deviceContext->CSSetShader(mComputeShader, nullptr, 0);

    deviceContext->CSSetShaderResources(0, 1, &mInputView);
    deviceContext->CSSetUnorderedAccessViews(0, 1, &mRWUAV, 0);


    // Dispatch
    deviceContext->Dispatch(512, 1, 1);

    // Unbind the input textures from the CS for good housekeeping
    ID3D11ShaderResourceView* nullSRV() = { NULL };
    deviceContext->CSSetShaderResources(0, 1, nullSRV);

    // Unbind output from compute shader ( we are going to use this output as an input in the next pass, 
    // and a resource cannot be both an output and input at the same time
    ID3D11UnorderedAccessView* nullUAV() = { NULL };
    deviceContext->CSSetUnorderedAccessViews(0, 1, nullUAV, 0);

    // Disable Compute Shader
    deviceContext->CSSetShader(nullptr, nullptr, 0);


    // Copy result **(FPS DROP HERE)**
    deviceContext->CopyResource(mRWOutputBuffer, mRWBuffer);

Thank you for your answer in advance.

algorithms – Measure divergence in Particle Swarm Optimization

I’d like to monitor divergence/diversity in my swarm during the particle swarm optimization algorithm to measure when the swarm search space is converging.

This would be used as one metric to be recorded during the run and potentially to terminate the PSO process when not much further progress is to be expected.

Is there a common metric for measuring PSO swarm divergence?

unity – The correct way to create radial particle system

I want to create a particle system. I have 3 different images of same size 50×50:

enter image description here
enter image description here
enter image description here

The goal is to make a system of particles flying around in a circle so that:

  • The particles will be directed as they move
  • The particles must be of the same size
  • The particle system must include a few types of textures.

Here’s what I have done:

enter image description here

This works ok. All I need is to make it with several textures. But when I simple change one texture to another one (once again, they are the same size), I see something like this:

enter image description here

What is wrong here? Second texture has the same size and the size angle

animation – Plotting the velocity and acceleration vector of a particle

I am a beginner to start working in Mathematica. I want to create an animation containing a particle moving along a circle with tangential speed 2t and its normal and tangential acceleration vectors which I calculated to be a(T)=2 and a(N)=4t^2. The best I could do was to find a code on wolfram and modify it a little, but I was unable to plot the increasing normal acceleration in the animation. Here is the code.

p = ParametricPlot({Cos(t), Sin(t)}, {t, 0, 2 Pi}, 
AspectRatio -> Automatic, PlotRange -> {{-6, 6}, {-6, 6}});
b(t_) = Last(FrenetSerretSystem({Cos(t), Sin(t)}, t));
c(t_) = {Cos(t ), Sin(t )};
Animate(Show(p, 
Graphics({Locator(c(t)), Thick, Blue, 
Arrow({c(t), c(t) + b(t)((1))}), Red, 
Arrow({c(t), c(t) + b(t)((2))})}), ImageSize -> Medium), {{t, 0}, 
0, 2 Pi})

How can I modify it to include the increasing normal acceleration vector?