#include "cm_world_sector_private.h"

void CM_LinkStaticModel(worldSectorAreaLink_t *areaLink)
{
    int32_t contentsMask;
    worldSector_t *sector;
    int32_t axis;
    float dist;
    float sectorMins[2];
    float sectorMaxs[2];

    areaLink->sightTraceEligible =
        CM_IsBigStaticModel(areaLink->linkMins, areaLink->linkMaxs);
    contentsMask = XModelGetContents(areaLink->model);

    sectorMins[0] = cm_worldMins[0];
    sectorMins[1] = cm_worldMins[1];
    sectorMaxs[0] = cm_worldMaxs[0];
    sectorMaxs[1] = cm_worldMaxs[1];
    sector = &cm_worldSectorRoot;

    while (1) {
        sector->staticModelContentsMask |= contentsMask;
        if (areaLink->sightTraceEligible != qfalse) {
            sector->sightTraceStaticModelContentsMask |= contentsMask;
        }

        axis = sector->axis;
        dist = sector->dist;

        if (dist < areaLink->linkMins[axis]) {
            sectorMins[axis] = dist;
            if (CM_LoadWorldSector(sector->children[0]) ==
                &cm_nullWorldSector) {
                break;
            }
            sector = CM_LoadWorldSector(sector->children[0]);
        } else {
            if (dist <= areaLink->linkMaxs[axis]) {
                break;
            }
            sectorMaxs[axis] = dist;
            if (CM_LoadWorldSector(sector->children[1]) ==
                &cm_nullWorldSector) {
                break;
            }
            sector = CM_LoadWorldSector(sector->children[1]);
        }
    }

    areaLink->nextInWorldSector = sector->staticModelLinkHead;
    sector->staticModelLinkHead = CM_StoreAreaLink(areaLink);
    CM_RebucketWorldSectorLinks(sector, sectorMins, sectorMaxs);
}
