I created a checkerboard/chessboard in opengl, it has 100 boxes. Logically I'm representing that board in a 2D array (10 by 10). Now I want the user to click anywhere in the opengl window and i can determine which index the box belongs to in the array, so that i can do some processing. How can i achieve that?
I'm using LWJGL a java wrapper for opengl. I know i have to get the mouse coordinates and i know they are returned in Normalized Device Coordinates ( in the range of 1 to -1) How can I map NDC to indexes? I've been searching but didn't find much.
I know the NDC ranges for each boxes. That's because i drew them by giving vertices so i know where each box starts and ends in NDC. But entering the ranges and its respective indexes in the form of key-value pairs would be too troublesome.
Currently I'm trying to create a formula through basic arithmetic such that it transforms NDC and gives me indexes. Is this possible? or is there any other feasible approach?
For those who are thinking how i have made the checkerboard, I drew vertical lines from -1 to 1 at a regular distance of 0.2. Similar is the case for horizontal ones.
If you are drawing directly in screen space it is quite easy to compute the box indices from NDC coords:
index.x = (int) ((ndc.x/2.0f + 0.5f) * boardSize.x)
index.y = (int) ((ndc.y/2.0f + 0.5f) * boardSize.y)
if (index.x == boardSize.x) // in case ndc.x was exactly 1
--index.x;
if (index.y == boardSize.y) // in case ndc.y was exactly 1
--index.y;