Z-order-curve coordinates

前端 未结 2 433
猫巷女王i
猫巷女王i 2021-01-01 01:09

How could i access data which is being stored using Z-order with O(1) time complexity in array? I need fast access to each of element by their coordinates. I there any faste

2条回答
  •  星月不相逢
    2021-01-01 01:28

    You can calculate the z order curve value with the following code:

    uint32_t calcZOrder(uint16_t xPos, uint16_t yPos)
    {
        static const uint32_t MASKS[] = {0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF};
        static const uint32_t SHIFTS[] = {1, 2, 4, 8};
    
        uint32_t x = xPos;  // Interleave lower 16 bits of x and y, so the bits of x
        uint32_t y = yPos;  // are in the even positions and bits from y in the odd;
    
        x = (x | (x << SHIFTS[3])) & MASKS[3];
        x = (x | (x << SHIFTS[2])) & MASKS[2];
        x = (x | (x << SHIFTS[1])) & MASKS[1];
        x = (x | (x << SHIFTS[0])) & MASKS[0];
    
        y = (y | (y << SHIFTS[3])) & MASKS[3];
        y = (y | (y << SHIFTS[2])) & MASKS[2];
        y = (y | (y << SHIFTS[1])) & MASKS[1];
        y = (y | (y << SHIFTS[0])) & MASKS[0];
    
        const uint32_t result = x | (y << 1);
        return result;
    }
    

    It was taken from here Bit Twiddling Hacks

    From you 128x128 array (or any other size) you can calculate easily the z order curve value from any position. For example:

    xPos = 2, yPos = 3 -> z order curve value = 7
    

    The max array size for the example code is 65536*65536. Just use a power of 2 for ease, in that case the maximum wasted space is approx. 3/4

提交回复
热议问题