javascript中的高效粒子系统?(WebGL的)

Aus*_*ten 8 javascript performance particles webgl particle-system

我正在尝试编写一个程序,对粒子进行一些基本的重力物理模拟.我最初使用标准Javascript图形(带有2d上下文)编写程序,我可以通过这种方式获得大约25 fps w/10000粒子.我在WebGL中重写了这个工具,因为我假设我可以通过这种方式获得更好的结果.我也使用glMatrix库进行矢量数学运算.然而,通过这种实现,我只获得了大约15fps的10000粒子.

我目前是EECS本科生,我有一定的编程经验,但从来没有使用图形,我对如何优化Javascript代码几乎没有任何线索.关于WebGL和Javascript如何工作,我有很多不明白的地方.使用这些技术时,哪些关键组件会影响性能?是否有更有效的数据结构来管理我的粒子(我只是使用一个简单的数组)?对于使用WebGL的性能下降有什么解释?GPU和Javascript之间的延迟可能?

任何建议,解释或帮助一般将不胜感激.

我将尝试仅包含我的代码的关键区域以供参考.

这是我的设置代码:

gl = null;
try {
    // Try to grab the standard context. If it fails, fallback to experimental.
    gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
    gl.viewportWidth = canvas.width;
    gl.viewportHeight = canvas.height;
}
catch(e) {}

if(gl){
        gl.clearColor(0.0,0.0,0.0,1.0);
        gl.clearDepth(1.0);                 // Clear everything
        gl.enable(gl.DEPTH_TEST);           // Enable depth testing
        gl.depthFunc(gl.LEQUAL);            // Near things obscure far things

        // Initialize the shaders; this is where all the lighting for the
        // vertices and so forth is established.

        initShaders();

        // Here's where we call the routine that builds all the objects
        // we'll be drawing.

        initBuffers();
    }else{
        alert("WebGL unable to initialize");
    }

    /* Initialize actors */
    for(var i=0;i<NUM_SQS;i++){
        sqs.push(new Square(canvas.width*Math.random(),canvas.height*Math.random(),1,1));            
    }

    /* Begin animation loop by referencing the drawFrame() method */
    gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesBuffer);
    gl.vertexAttribPointer(vertexPositionAttribute, 2, gl.FLOAT, false, 0, 0);
    requestAnimationFrame(drawFrame,canvas);
Run Code Online (Sandbox Code Playgroud)

绘制循环:

function drawFrame(){
    // Clear the canvas before we start drawing on it.
    gl.clear(gl.COLOR_BUFFER_BIT);

    //mvTranslate([-0.0,0.0,-6.0]);
    for(var i=0;i<NUM_SQS;i++){
        sqs[i].accelerate();
        /* Translate current buffer (?) */
        gl.uniform2fv(translationLocation,sqs[i].posVec);
        /* Draw current buffer (?) */;
        gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
    }
    window.requestAnimationFrame(drawFrame, canvas);
}
Run Code Online (Sandbox Code Playgroud)

这是Square继承的类:

function PhysicsObject(startX,startY,size,mass){
    /* Class instances */
    this.posVec = vec2.fromValues(startX,startY);
    this.velVec = vec2.fromValues(0.0,0.0);
    this.accelVec = vec2.fromValues(0.0,0.0);
    this.mass = mass;
    this.size = size;

    this.accelerate = function(){
            var r2 = vec2.sqrDist(GRAV_VEC,this.posVec)+EARTH_RADIUS;
            var dirVec = vec2.create();
            vec2.set(this.accelVec,
                G_CONST_X/r2,
                G_CONST_Y/r2
            );

        /* Make dirVec unit vector in direction of gravitational acceleration */
        vec2.sub(dirVec,GRAV_VEC,this.posVec)
        vec2.normalize(dirVec,dirVec)
        /* Point acceleration vector in direction of dirVec */
        vec2.multiply(this.accelVec,this.accelVec,dirVec);//vec2.fromValues(canvas.width*.5-this.posVec[0],canvas.height *.5-this.posVec[1])));

        vec2.add(this.velVec,this.velVec,this.accelVec);
        vec2.add(this.posVec,this.posVec,this.velVec);
    };
}
Run Code Online (Sandbox Code Playgroud)

这些是我正在使用的着色器:

 <script id="shader-fs" type="x-shader/x-fragment">
        void main(void) {
        gl_FragColor = vec4(0.7, 0.8, 1.0, 1.0);
        }
    </script>

    <!-- Vertex shader program -->

    <script id="shader-vs" type="x-shader/x-vertex">
        attribute vec2 a_position;

        uniform vec2 u_resolution;

        uniform vec2 u_translation;

        void main() {
        // Add in the translation.
        vec2 position = a_position + u_translation;
        // convert the rectangle from pixels to 0.0 to 1.0
        vec2 zeroToOne = position / u_resolution;

        // convert from 0->1 to 0->2
        vec2 zeroToTwo = zeroToOne * 2.0;

        // convert from 0->2 to -1->+1 (clipspace)
        vec2 clipSpace = zeroToTwo - 1.0;

        gl_Position = vec4(clipSpace*vec2(1,-1), 0, 1);
        }
    </script>
Run Code Online (Sandbox Code Playgroud)

我为这个啰嗦道歉.同样,任何正确方向的建议或推动都将是巨大的.

Mar*_*kus 6

你不应该单独绘制原语.尽可能一次性地绘制它们.创建一个ArrayBuffer,它包含所有粒子的位置和其他必要属性,然后通过一次调用gl.drawArrays绘制整个缓冲区.我无法给出确切的说明,因为我在移动设备上但是在opengl中搜索vbo,交错数组和粒子肯定会帮助您找到示例和其他有用的资源.

我用10fps渲染5m静态点.动态点将会变慢,因为您必须不断向显卡发送更新的数据,但10000点的速度会快于15fps.

编辑:

您可能希望使用gl.POINT而不是TRIANGLE_STRIP.这样,您只需为每个方块指定位置和gl_PointSize(在顶点着色器中).gl.POINT呈现为正方形!

您可以查看这两个点云渲染器的来源:

  • https://github.com/asalga/XB-PointStream
  • http://potree.org/wp/download/(通过我,以下文件可能对您有所帮助:WeightedPointSizeMaterial.js,pointSize.vs,colouredPoint.fs)

    • 你能指点我描述这种技术的资源吗?我似乎只能找到详细说明如何纹理对象的资源.我对片段着色器和纹理着色器之间的连接以及着色器的输入和输出有点模糊.再次感谢您的时间和帮助. (2认同)

    gma*_*man 5

    这取决于您想要做什么。当你说“重力”时,你的意思是某种带有碰撞的物理模拟,还是只是意味着velocity += acceleration; position += velocity

    如果是后者,那么您可以在着色器中完成所有数学运算。例子在这里

    https://www.khronos.org/registry/webgl/sdk/demos/google/articles/index.html

    这些粒子完全在着色器中完成。设置后唯一的输入是time. 每个“粒子”由 4 个顶点组成。每个顶点包含

    • local_position(对于单位四边形)
    • 纹理坐标
    • 寿命
    • 起始位置
    • 起始时间
    • 速度
    • 加速度
    • 起始大小
    • 结束大小
    • 方向(四元数)
    • 色彩倍增器

    给定时间,您可以计算粒子的本地时间(自开始以来的时间)

     local_time = time - starting_time;
    
    Run Code Online (Sandbox Code Playgroud)

    然后你可以计算一个位置

     base_position = start_position + 
                     velocity * local_time + 
                     acceleration * local_time * local_time;
    
    Run Code Online (Sandbox Code Playgroud)

    即加速度*时间^2。然后将 local_position 添加到该 base_position 以获得渲染四边形所需的位置。

    您还可以计算粒子生命周期内 0 到 1 的 lerp

     lerp = local_time / lifetime;
    
    Run Code Online (Sandbox Code Playgroud)

    这为您提供了一个可用于 lerp 所有其他值的值

     size = mix(start_size, end_size, lerp);
    
    Run Code Online (Sandbox Code Playgroud)

    如果粒子的大小为 0 如果它超出了它的生命周期

     if (lerp < 0.0 || lerp > 1.0) {
       size = 0.0;
     }
    
    Run Code Online (Sandbox Code Playgroud)

    这将使 GPU 无法绘制任何内容。

    使用渐变纹理(1xN 像素纹理),您可以轻松地让粒子随时间改变颜色。

     color = texture2D(rampTexture, vec4(lerp, 0.5));
    
    Run Code Online (Sandbox Code Playgroud)

    ETC...

    如果您跟踪着色器,您会看到其他类似处理的事情,包括旋转粒子(对于点精灵来说这会更困难)、在帧纹理上设置动画、执行 2D 和 3D 定向粒子。2D 粒子适用于烟雾、废气、火灾、爆炸。3D 粒子非常适合处理波纹(可能是轮胎痕迹),并且可以与 2D 粒子结合用于地面喷发,以隐藏仅 2D 粒子的一些 z 问题。ETC..

    还有单发(爆炸、喷发)和轨迹的例子。按“P”吸一口。按住“T”键查看踪迹。

    AFAIK 这些是非常高效的粒子,因为 JavaScript 几乎什么都不做。