var positions = [];
var trace = [];
var render = [];
var local = Entity.GetLocalPlayer();
function ImportGrenades()
{
    var grenades = Entity.GetEntitiesByClassID(9).concat(Entity.GetEntitiesByClassID(113).concat(Entity.GetEntitiesByClassID(100)));
    for (e in grenades)
    {
        pass = false;
        for (g in positions)
        {
            if (positions[g][0] == grenades[e])
            {
                pass = true;
                continue;
            }
        }
        if (pass)
            continue;

        positions.push([grenades[e], Globals.Curtime(), [Entity.GetRenderOrigin(grenades[e])], Globals.Curtime()]);
    }
}
function GrenadeWarning()
{
    var grenades = Entity.GetEntitiesByClassID(9).concat(Entity.GetEntitiesByClassID(114).concat(Entity.GetEntitiesByClassID(100)));

    if (!Entity.IsAlive(local)) { return; }
    
    for (g in grenades) {
        for (var i = 0; i < grenades.length; i++) {
            
            var g = grenades[i];
            var isInferno = Entity.GetClassID(g) === 100;
            var isHeGrenade = Entity.GetClassID(g) === 9;
            function DistanceInFeets (origin, destination) {
                var sub = [destination[0] - origin[0], destination[1] - origin[1], destination[2] - origin[2]];
                return Math.round(Math.sqrt(sub[0] ** 2 + sub[1] ** 2 + sub[2] ** 2) / 12);
            }
            var destination = Entity.GetRenderOrigin(g);
            var origin = Entity.GetEyePosition(local);
            var distance = DistanceInFeets(origin, destination);
            var screen = Render.WorldToScreen(destination);
            var isSafe = distance > (isInferno ? 15 : 20) || trace[1] < 0.61;
            if (distance > 256) { continue; }
            if (isHeGrenade && Entity.GetProp (g, "CBaseCSGrenadeProjectile", "m_nExplodeEffectTickBegin")) { continue; }
            font = Render.AddFont("Small fonts", 7, 100);
            const warning_stroke = true;
            Render.FilledCircle( screen[0], screen[1] + 39, 25, [ 153, 153, 244, 30 ])
            Render.Circle( screen[0], screen[1] + 39, 25, !isSafe && warning_stroke ? [ 240, 41, 41, 255 ] : [ 153, 153, 244, 255 ])
            Render.StringCustom (screen[0] - 10, screen[1] + 48, 0, Math.round(distance / 3.28) + " m", [ 0, 0, 0, 255 ], font);
            Render.StringCustom (screen[0] - 9, screen[1] + 49, 0, Math.round(distance / 3.28) + " m", [ 240, 240, 240, 255 ], font);
            Render.String (screen[0] - 8, screen[1] + 27, 0, isHeGrenade ? "I" : "K", [ 240, 240, 240, 255 ], 5);
        }
    }
}
function onDraw()
{
    ImportGrenades();
    GrenadeWarning();
}

Cheat.RegisterCallback("Draw", "onDraw");