#include "cm_world_sector_private.h"

void CM_AreaEntities_r(worldSector_t *sector,
                       coduo_area_entities_work_t *state)
{
    svEntity_t *svEntity;
    const float *mins;
    const float *maxs;
    int32_t *entityList;

    if ((state->contentMask & sector->entityContentsMask) == 0) {
        return;
    }

    mins = state->mins;
    maxs = state->maxs;
    entityList = state->entityList;

    for (svEntity = CM_LoadEntityLink(sector->entityLinkHead);
         svEntity != NULL;
         svEntity = CM_LoadEntityLink(svEntity->nextInWorldSector)) {
        sharedEntity_t *gentity = SV_GEntityForSvEntity(svEntity);

        /*
         * Stock rejects only ordered greater-than comparisons
         * (0x0805e1bb..0x0805e26b). Unordered bounds therefore pass this
         * overlap gate instead of being rejected as they would be by a
         * positive <= conjunction.
         */
        if ((state->contentMask & gentity->contents) != 0 &&
            !(gentity->absMin[0] > maxs[0]) &&
            !(mins[0] > gentity->absMax[0]) &&
            !(gentity->absMin[1] > maxs[1]) &&
            !(mins[1] > gentity->absMax[1]) &&
            !(gentity->absMin[2] > maxs[2]) &&
            !(mins[2] > gentity->absMax[2])) {
            if (state->count == state->maxcount) {
                Com_DPrintf("CM_AreaEntities: MAXCOUNT\n");
                return;
            }

            entityList[state->count] =
                (int32_t)(svEntity - &sv_entityLinks[0]);
            state->count++;
        }
    }

    if (sector->dist < maxs[sector->axis]) {
        CM_AreaEntities_r(CM_LoadWorldSector(sector->children[0]), state);
    }

    if (mins[sector->axis] < sector->dist) {
        CM_AreaEntities_r(CM_LoadWorldSector(sector->children[1]), state);
    }
}
