How to create sphere using multiple objects

心已入冬 提交于 2019-12-18 09:37:58

问题


I have to draw sphere using multiple squares(i am also allowed to use triangles even, but i found some existing code for help in square, so i used it). I have successfully drawn multiple squares (5000).But i don't have to use any inbuit function to create sphere . My code is below :

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script class="WebGL">
        var gl;
        function createProgram(gl, vertexShader, fragmentShader)
        {
            var vs = gl.createShader(gl.VERTEX_SHADER);
            gl.shaderSource(vs, vertexShader);
            gl.compileShader(vs);

            if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS))
                alert(gl.getShaderInfoLog(vs));
            //////
            var fs = gl.createShader(gl.FRAGMENT_SHADER);
            gl.shaderSource(fs, fragmentShader);
            gl.compileShader(fs);

            if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS))
                alert(gl.getShaderInfoLog(fs));
            program = gl.createProgram();
            gl.attachShader(program, vs);
            gl.attachShader(program, fs);
            gl.linkProgram(program);
            if (!gl.getProgramParameter(program, gl.LINK_STATUS))
                alert(gl.getProgramInfoLog(program));
            return program;
        }
        function createShaderFromScriptElement(gl , shaderName)
        {
            var Shader = document.getElementById(shaderName).firstChild.nodeValue;
            return Shader;
        }
        function start()
        {
            var canvas = document.getElementById("canvas");
            gl = canvas.getContext("experimental-webgl");
            if (!gl) { alert("error while GL load"); }

              var vertexShader = createShaderFromScriptElement(gl, "2d-vertex-shader");
              var fragmentShader = createShaderFromScriptElement(gl, "2d-fragment-shader");

              var program = createProgram(gl, vertexShader, fragmentShader);

            gl.useProgram(program);
            var positionLocation = gl.getAttribLocation(program, "a_position");
            var colorLocation = gl.getUniformLocation(program, "u_color");
            var resolutionLocation = gl.getUniformLocation(program, "u_resolution");

            var buffer = gl.createBuffer();
            gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
            gl.uniform2f(resolutionLocation, 200, 200);

            gl.enableVertexAttribArray(positionLocation);
            gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
            for (var ii = 0; ii < 5000; ++ii)
            {
                // Setup a random rectangle
                setRectangle(gl, randomInt(300), randomInt(300), 10, 10);
                // Set a random color.
                gl.uniform4f(colorLocation, Math.random(), Math.random(), Math.random(), 1);
                // Draw the rectangle.
                gl.drawArrays(gl.TRIANGLES, 0, 6);
            }
            function randomInt(range)
            {
                return Math.floor(Math.random() * range);
            }

            // Fills the buffer with the values that define a rectangle.
            function setRectangle(gl, x, y, width, height)
            {
                var x1 = x;
                var x2 = x + width;
                var y1 = y;
                var y2 = y + height;
                gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
                   x1, y1,
                   x2, y1,
                   x1, y2,
                   x1, y2,
                   x2, y1,
                   x2, y2]), gl.STATIC_DRAW);
            }
        }
    </script>
    <script id="2d-vertex-shader" type="x-shader/x-vertex">
        attribute vec2 a_position;
        uniform vec2 u_resolution;

        void main() {
        // convert the rectangle from pixels to 0.0 to 1.0
        vec2 zeroToOne = a_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>

    <script id="2d-fragment-shader" type="x-shader/x-fragment">
        precision mediump float;
        uniform vec4 u_color;

        void main()
        {
        gl_FragColor = u_color;  // green
        }
    </script>
</head>
<body onload="start()">
    <div style="text-align: center">
        <canvas id="canvas" width="1000" height="800"></canvas>
    </div>
</body>
</html>

What i am asked is to draw sphere using multiple objects which i have no idea how to do.And my try was first to draw the multiple objects (5000 in my case) and then try for drawing sphere using it(i mean using these 5000 squares, my next step is to create sphere).

But i don't know how to proceed further to draw sphere using these squares ?

Which i am not able to understand how to do. Could some one please help me ?


回答1:


One of approaches is constructing sphere from rectangular tiles in vertex shader.

Generally, the thing is to cover [0, 2*M_PI] x [0, M_PI] region with tiles. Say, you have N tiles where N = m*k, m is amount of tiles in a row and k is amount of tiles in column.

You can create N unit squares and assign to each of them its unique position in m * k matrix. Then pass these positions and width/height of tiles (2*M_PI / m and M_PI / k) as uniforms to vertex shader (or as attributes).

In vertex shader knowing position of tile and its width/height compute vertice's coords on [0, 2*M_PI] x [0, M_PI] (they would be phi and ksi). And then compute actual vertex position on sphere:

coord.x = sin(ksi) * cos(phi);
coord.y = sin(ksi) * sin(phi);
coord.z = cos(ksi);

Also note you should set up perspective projection for this.

Choosing m and k is up to you. I recommend to start with square tiles. Here is the picture of result i got this way:



来源:https://stackoverflow.com/questions/33065204/how-to-create-sphere-using-multiple-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!