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