package electrosphere.client.terrain.sampling;

import org.joml.Vector3d;
import org.joml.Vector3i;

import electrosphere.client.terrain.cache.ChunkData;
import electrosphere.engine.Globals;
import electrosphere.entity.Entity;
import electrosphere.entity.EntityUtils;

/**
 * Samples voxels
 */
public class ClientVoxelSampler {

    /**
     * Returned if a voxel is sampled from an invalid position
     */
    public static final int INVALID_POSITION = -1;
    
    /**
     * Gets the voxel type beneath an entity
     * @param entity The entity
     * @return The voxel type, INVALID_POSITION if the position queried is invalid
     */
    public static int getVoxelTypeBeneathEntity(Entity entity){
        return ClientVoxelSampler.getVoxelType(EntityUtils.getPosition(entity));
    }

    /**
     * Gets the voxel type at a given real-space position
     * @param realPos The real-space position
     * @return The voxel type id, INVALID_POSITION if the position queried is invalid
     */
    public static int getVoxelType(Vector3d realPos){
        int voxelId = 0;
        Vector3i chunkSpacePos = Globals.clientWorldData.convertRealToWorldSpace(realPos);
        Vector3i voxelSpacePos = Globals.clientWorldData.convertRealToVoxelSpace(realPos);
        if(Globals.clientTerrainManager.containsChunkDataAtWorldPoint(chunkSpacePos)){
            ChunkData chunkData = Globals.clientTerrainManager.getChunkDataAtWorldPoint(chunkSpacePos);
            voxelId = chunkData.getType(voxelSpacePos);
        } else {
            return INVALID_POSITION;
        }
        return voxelId;
    }

}
