2016-11-25 28 views
1

我已经充实了一个循环,为使用着色器的基于浏览器的可视化中的每个不同视图动态生成纹理大小。我知道为了将我的值传递给着色器而需要的最小像素数量;但是我需要将它们缩放到2的大小,然后确保它们的x和y尺寸也是2的幂,比例为1:1,2:1或1:2。现在我的循环是无限的,我想我需要继续增加2像素计数的总体功率,直到达到满足我的一个比例的大小。如何动态和高效地生成两个幂的纹理大小和尺寸

我的问题是:有没有更高效或直接的方法来实现我在这里要做的事情?

var motifMinBufferSize = 80000; 
var bufferSize; // the total number of texels that will be in the computation buffers (must be a power of two) 
var dimensions; 

function initValues() { 

    bufferSize = setBufferSize(); 
    dimensions = setPositionsTextureSize(); 
} 

function setBufferSize() { 

    var buffer = motifMinBufferSize; 

    // fill out the buffers to a power of two - necessary for the computation textures in the shaders 
    var powCount = 1; 
    var powOf2 = 2; 
    while (buffer > powOf2) { 
     powOf2 *= 2; 
     powCount++; 
    } 

    while (buffer < powOf2) { 
     buffer += 1; 
    } 
} 

function setPositionsTextureSize() { 

    var dimensions = { 
     texWidth : null, 
     texHeight : null 
    }; 
    var foundDimensions = false; 
    var powOf2 = 2; 

    while (foundDimensions === false) { 
     var candidateWidth = bufferSize/powOf2; 
     if (candidateWidth === powOf2 || candidateWidth/2 === powOf2 || candidateWidth*2 === powOf2) { 
      dimensions.texWidth = candidateWidth; 
      dimensions.textHeight = powOf2; 
      foundDimensions = true; 
     } else { 
      powOf2 *= 2; 
     } 
    } 
    return dimensions; 

} 

回答

1

缓冲区必须包含2^n个元素,因为缓冲区的宽度和高度都是2的幂。满足 至少motifMinBufferSize元素的要求的最小n使用对数计算:n = Math.ceil(Math.log2(motifMinBufferSize))

假设缓冲区的高度为2^h,缓冲区的宽度为2^w。我们知道w和h可以相差最多一个(由于缓冲区尺寸比率的限制)。我们也知道2^n = 2^w * 2^h这意味着n = w + h。由于w和h相差至多1,它们基本都是n的一半。因此,我们可以得到:

function getBufferDimensions(minBufferSize) { 
    var n = Math.ceil(Math.log2(minBufferSize)); 
    var w = Math.ceil(n/2); 
    var h = n - w; 

    return { 
    width: Math.pow(2, w), 
    height: Math.pow(2, h), 
    }; 
} 
+0

非常高雅 - 谢谢! – gromiczek

相关问题