Skip to content

Instantly share code, notes, and snippets.

@sketchpunk
Created January 7, 2021 20:59
Show Gist options
  • Save sketchpunk/bcd3aea9f7728f410f3d2a77f706b3be to your computer and use it in GitHub Desktop.
Save sketchpunk/bcd3aea9f7728f410f3d2a77f706b3be to your computer and use it in GitHub Desktop.
Quad Tree Node ID
<html>
<script>
window.onload = function(){
let qID = 0;
qID = QuadTreeID.set( qID, 2, QuadTreeID.A );
qID = QuadTreeID.set( qID, 0, QuadTreeID.C );
qID = QuadTreeID.set( qID, 3, QuadTreeID.D );
qID = QuadTreeID.set( qID, 1, QuadTreeID.B );
qID = QuadTreeID.set( qID, 4, QuadTreeID.C );
QuadTreeID.debug( qID );
/* Max Level : 4
Bits : 0010 01 10 00 11 01
LVL: 0 : C-01
LVL: 1 : B-10
LVL: 2 : A-00
LVL: 3 : D-11
LVL: 4 : C-01 */
};
/*
32 Bytes
- 4 bytes for Total Levels
28
- Last bit defines negative,
so only have 26 bytes left.
26/2 = 13
Maximum level of LOD of 13 using ints
1,2,4,8
*/
class QuadTreeID{
static A = 0;
static B = 1;
static C = 2;
static D = 3;
static set( qid, lvl, quad ){
let shift = (lvl * 2) + 4; // How many bits to shift based on level
let i = quad << shift; // Quad ID at Bit Level
let mask = ~( (3 << shift) + 15 ); // Create Mask to clear out lvl and quad of old ID : ex. 111100110000
lvl = Math.max( lvl, qid & 15 ); // Grab the first 4 Bits which defines the level.
return (qid & mask) ^ lvl ^ i; // Rebuild ID with new level and Quadrant ID
}
static debug( id ){
let i, v, q, lvl = id & 15;
console.log( "Max Level : ", lvl );
let bits = "Bits : "; // ex output : BITS: 1000 10 11 01
let end = (id & 15) * 2 + 6;
for( i=0; i < end; i++ ) bits += ((id >> i) & 1) + (( (i & 1) && i > 2 )?" ":"");
console.log( bits );
for( i=0; i <= lvl; i++ ){
v = ( id >> ((i * 2) + 4) ) & 3;
switch( v ){
case this.A : q = "A-00"; break;
case this.B : q = "B-10"; break;
case this.C : q = "C-01"; break;
case this.D : q = "D-11"; break;
default: q = "X"; // error
}
console.log( "LVL:", i, " : ", q);
}
}
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment