Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help me evaluate this casting

Tags:

c++

opengl

I found this in the PowerVR mesh drawing code and I don't really know how to read it.

&((unsigned short*)0)[3 * mesh.sBoneBatches.pnBatchOffset[batchNum]]

What is going on here? Is this a reference to void cast as an unsigned short pointer and then offset by (3*mesh(etc...) + batchNum)? It's breaking my brain.

It's found in the context of a glDrawElements call:

glDrawElements(GL_TRIANGLES, i32Tris * 3, GL_UNSIGNED_SHORT, 
               &((unsigned short*)0)[3 * mesh.sBoneBatches.pnBatchOffset[batchNum]]);
like image 217
spencewah Avatar asked Nov 24 '25 09:11

spencewah


2 Answers

Let's go from the inside out.

(unsigned short*)0

This is casting 0 to an unsigned short pointer. This will be used for computing a memory offset, computed in terms of the size of an unsigned short.

3 * mesh.sBoneBatches.pnBatchOffset[batchNum]

This is, presumably, the offset in memory of some batch of triangles. A triangle is composed of 3 shorts, so it looks like they are storing an offset in terms of numbers of triangles, and then multiplying by 3 to get the number of shorts.

((unsigned short*)0)[3 * mesh.sBoneBatches.pnBatchOffset[batchNum]]

This is now using that 0 pointer to find the memory location of the given offset. This would normally return the value of that memory location, but they want a pointer to pass into glDrawElements, so the use the & operator to get a pointer to that memory location:

&((unsigned short*)0)[3 * mesh.sBoneBatches.pnBatchOffset[batchNum]]
like image 192
Brian Campbell Avatar answered Nov 27 '25 00:11

Brian Campbell


It's computing a byte offset -- 3 * mesh.sBoneBatches.pnBatchOffset[batchNum] is the index. Using 0 as the pointer means that the address will be just the offset value, nothing else.

like image 29
brool Avatar answered Nov 27 '25 00:11

brool



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!