How to round points to an arbitrary grid on the surface of a cube?

I'm making a PCG game where I have points scattered or projected onto the surface of a cube, which is centered on origin with a "radius" of 1.

That surface is a grid and I want to associate each point to the center of each proper cell's grid.

After detecting which face the point is by taking max(x,y,z) I used that formula:

halfTileSize * floor (3dpositions * gridDivision)/gridDivision;


[EDIT: everything above work, everything below is useless, the problem was outside influence from obsolete code]

But it doesn't round the point to the correct grid cell on the surface. There is a problem where front and back don't return the same result, or it skips a row with some condition, and it also rounds to the wrong nearby cells.

I tried to replace the floor with:

3dpositions.xyz < 0 ? ceil(3dpositions * gridDivision) : floor(3dpositions * gridDivision)


That didn't work either. It seems to work fine on a 2d planes, which I used to conceptualize the formula, but in 3D I'm at loss as to why it wouldn't work, since I basically reduce the problem to 2D anyway...

Any help to create a formula that would round the points properly into the right cell?

• I've reworded your question. Usually when we "hash" data, we're running it through a one-way pseudo-random or cryptographic function to get a result that looks more randomly distributed (but still exactly reproducible given the same starting data). Here, you're not talking about performing this hashing operation on your points. The pseudo-randomness is in the points' original generated distribution, and you're trying to round or snap those points to a regular grid. – DMGregory Jan 26 '18 at 13:54
• Can you clarify? When you say "it doesn't round the point to the correct grid cell on the surface", what does it do instead? When you say "front and back don't return the same result", are you accounting for the fact that the projection from the original position will be different on those 2 surfaces? (I assume you mean the front and back face of the cube, right?) – user1118321 Jan 27 '18 at 4:26
• Well that's embarrassing, there is no problem, the first formula works perfectly, it was some old obsolete hack during research that messed up the result and the ternary test is actually useless too. I spend 3 days on a stupid mistake for something that trivial :( – user29244 Jan 28 '18 at 11:51
• If you found the answer, then post it as one and mark it as correct – Bálint Jan 28 '18 at 12:25
• Is it necessary since it's literally in the question? There was no problem there can't be answer, that's the embarrassment. Unless It's okay to copy paste the right formula. I'll do it and let the judge decide. – user29244 Jan 29 '18 at 5:15

halfTileSize * floor (3dpositions * gridDivision)/gridDivision;