000

Index Labels

Finding nearby stuff

.

A problem that crops up quite often in game programming is the need to find stuff that is "close to" other stuff. For example, you may want to find all enemies close to the player, all treasures close to a goblin, etc.

Most recently, I ran into this problem when I added support for merging navigation meshes to the Bitsquid engine.

To merge meshes, I need to find all the vertices that are "sufficiently close" (within some tolerance limit) in the meshes that I'm merging. These vertices should be considered "the same" in the merged mesh and need to be treated specially.

The naive algorithm for finding these coinciding vertices is to just do a double loop:

foreach (v1 in vertices)
foreach (v2 in vertices)
if (distance(v1, v2) < tolerance)
...

But since this algorithm is O(n^2) in the number of vertices, it is often prohibitively expensive.

To improve the performance you need some kind of data structure for accelerating spatial queries. There are lots of different possibilities. Real-Time Collision Detection by Christer Ericsson has a good coverage of them.

One of the simplest approaches is to use some kind of grid bucket system. You divide the world into a grid and for each grid cell you store a list of the vertices that fall in that cell. To check for "close" vertices you look through the list of vertices in your cell:

Depending on what your definition of "close" is (how big the search radius is compared to the grid size), you may need to search more cells. Note that if the search starts close enough to a grid corner you always have to search at least four cells, no matter how small the search radius is. (For a two-dimensional grid, a three-dimensional grid requires you to search eight cells.)

If you know what the search radius is going to be (for example, in my vertex merging case I always use the same merge distance) you can adapt the grid so that you never have to search more than four cells, by setting the grid size to be equal to the search diameter.

With a larger grid size you can sometimes get by with searching just one or two cells, depending on how close to a grid line the search starts, but there will always be some positions where you will have to look at four cells.

The fact that you at most have to look at four cells can be used to make an interesting variant of the algorithm. Instead of checking the four neighboring cells in the lookup, you can store the item in all four neighboring cells. That way you will only have to check a single cell when you do the lookup. This approach will make lookups four times faster, insertions four times slower and use four times as much memory. It can be a good optimization if you have a high ratio of lookups to insertions.

For my particular case (vertex merging) I only have one lookup per insertion, so this would not be a net win.

Designing the grid can be tricky.

How large should it be? You may need to do a pre-pass over your data to find the range, which isn't possible if you don't have all the data up front. (Letting the grid coordinates wrap around can solve this in some cases.)

How big should the cells be? If you make them too small, the grid will consume too much memory. If you make them too big, you may end up with lots of points that you need to check in each cell, which will make the algorithm slow.

What if the data is laid out on a diagonal? In this case most grid cells will be empty, wasting memory:

Most of these concerns can be fixed by not storing the grid in a traditional matrix, but instead use a hash that maps from grid coordinates to cell data:

struct GridCoordinate {
int x;
int y;
};

HashMap<GridCoordinate, CellData> grid;

// To insert an item
GridCoordinate gc;
gc.x = (int)floor(p.x / cell_size);
gc.y = (int)floor(p.y / cell_size);
grid[gc] = cell_data;

This way, you will only use memory for the cells that actually contain data and lookups are still O(1). You also don't have to care about how big the grid is or what happens if data ends up outside the grid. In fact, you only have one parameter left to worry about, the cell_size.

As mentioned above, a good heuristic is to use:

float cell_size = 1.0 * search_diameter;

That way you have to investigate exactly four cells in each lookup.

If the data is sparse compared to the search radius you can use a bigger cell size, which means that you don't always have to check all four neighbors. But note that the average number of cells you need to search in each lookup goes down slowly, while the cell area (and correspondingly the average number of items in each cell) grows quickly. So only use this optimization when you know that the data is sparse.

Multiplier Avg. cells to search Cell area
1.0 4.00 1.00
1.5 2.78 2.25
2.0 2.25 4.00
3.0 1.78 9.00
5.0 1.44 25.00
10.0 1.21 100.00

The final piece of this puzzle is what CellData should look like. It might be tempting to do something like:

typedef Vector<VertexId> CellData;

However, this would be highly inefficient. In many cases cells will only contain a few items and allocating a Vector for them is total overkill. Using a Vector will mean tons of pointer chasing, cache misses and data copying.

For me, a general rule of thumb when writing high performance C++ code is to avoid collections stored inside other collections. If you store collections in collections it is very easy to create innocuous looking code that does tons of data copying behind your back.

So what can you do instead. If you have a good MultiHashMap implementation, you can use that. Otherwise, you can do something like this:

struct CellData {
VertexId id;
unsigned next;
};
Array<CellData> items;

Here, items contains linked lists of the items in each cell, stored in a continuous array (which is the only sane way to store linked lists). The HashMap gives the first cell item. Then you follow the next references in the items list to find subsequent items in the same cell until next == UINT_MAX, which marks the end of the list.

This basic pattern: grid coordinates -> hash map -> linked list in array is my standard go-to solution for making spatial queries. It is straightforward, easy to understand and uses memory reasonably while providing O(1) lookups.

Blog Archive

Labels

.NET Programming 2D Drafting 3D 3D Animation 3D Art 3D Artist 3D CAD 3D Character 3D design 3D design tutorial 3D Drafting 3D effects 3D Engineering 3D Lighting 3D Materials 3D Modeling 3D models 3D Navigation 3D presentation 3D Printing 3D rendering 3D scanning 3D scene 3D simulation 3D Sketch Inventor 3D Texturing 3D visualization 3D Web App 3ds Max 4D Simulation ACC Accessibility Adaptive Clearing adaptive components Add-in Development Additive Layers Additive Manufacturing Adobe Suite Advanced CAD features Advanced Modeling advanced plot styles Advanced Sketch AEC Industry AEC Technology AEC Tools AEC Workflow affordable Autodesk tools AI AI animation AI Assistance AI collaboration AI Design AI Design Tools AI Experts AI for Revit AI Guide AI in 3D AI in Architecture AI in CAD AI in CNC AI in design AI in engineering AI in Manufacturing AI in Revit AI insights AI lighting AI rigging AI Strategies AI Tips AI Tools AI Tricks AI troubleshooting AI workflow AI-assisted AI-assisted rendering AI-Assisted Workflow AI-enhanced AI-powered templates Alpha Lock Animation Animation Curves Animation Layers animation pipeline animation tips Animation Tutorial Animation workflow annotation Annotation Scaling annotation standards Annotations Apps Script AR Architectural AI Architectural CAD architectural design Architectural Drafting Architectural Drawing architectural drawings architectural modeling architectural preservation Architectural Productivity architectural visualization Architectural Workflow Architecture architecture CAD architecture design Architecture Engineering Architecture Firm Architecture Productivity architecture projects architecture software architecture technology Architecture Tips architecture tools Architecture Visualization Architecture Workflow Arnold Renderer Arnold Shader Art Basics Art Collaboration Art Organization Art Tutorial Artificial Intelligence As-Built Model assembly techniques Asset Management Audit Best Practices augmented reality Auto Rig Maya AutoCAD AutoCAD advice AutoCAD AI tools AutoCAD API AutoCAD automation AutoCAD Basics AutoCAD Beginner AutoCAD Beginners AutoCAD Blocks AutoCAD Civil 3D AutoCAD Civil3D AutoCAD commands AutoCAD efficiency AutoCAD Expert Advice AutoCAD features AutoCAD Fields AutoCAD File Management AutoCAD Guide AutoCAD Hub AutoCAD Layer AutoCAD Layers AutoCAD learning AutoCAD Optimization AutoCAD print settings AutoCAD productivity AutoCAD scripting AutoCAD Scripts AutoCAD Sheet Set tips AutoCAD Teaching AutoCAD Techniques AutoCAD Templates AutoCAD tips AutoCAD tools AutoCAD training. AutoCAD tricks AutoCAD Tutorial AutoCAD workflow AutoCAD Xref Autodesk Autodesk 2025 Autodesk 2026 Autodesk 3ds Max Autodesk AI Autodesk AI Tools Autodesk Alias Autodesk AutoCAD Autodesk BIM Autodesk BIM 360 Autodesk Certification Autodesk Civil 3D Autodesk Cloud Autodesk community forums Autodesk Construction Cloud Autodesk Docs Autodesk Dynamo Autodesk features Autodesk for Education Autodesk Forge Autodesk FormIt Autodesk Fusion Autodesk Fusion 360 Autodesk help Autodesk InfraWorks Autodesk Inventor Autodesk Inventor Frame Generator Autodesk Inventor iLogic Autodesk Knowledge Network Autodesk License Autodesk Maya Autodesk mistakes Autodesk Navisworks Autodesk news Autodesk plugins Autodesk productivity Autodesk Recap Autodesk resources Autodesk Revit Autodesk Software Autodesk support ecosystem Autodesk Takeoff Autodesk Tips Autodesk training Autodesk tutorials Autodesk update Autodesk Upgrade Autodesk Vault Autodesk Video Autodesk Viewer AutoLISP Automate automate drawing updates Automate Printing automate publishing automate repetitive tasks Automated Design automated publishing Automated Sheets Automation Automation in AutoCAD Automation Tools Automation Tutorial automotive design automotive visualization B&W Printing Backup Basic Commands Basics batch drawing validation Batch Plot Batch Plotting Batch Printing Batch Rename Beginner beginner CAM Beginner Tips Beginner to Pro beginner tutorial beginners guide Bend Tools Best Practices Big Data BIM BIM 360 BIM Challenges BIM collaboration BIM Compliance BIM Coordination BIM Data BIM Design BIM Efficiency BIM for Infrastructure BIM Implementation BIM Library BIM Management BIM modeling BIM software BIM Standardization BIM Standards BIM technology BIM Tips BIM tools BIM Trends BIM workflow Block Editor Block Management Block Organization Blueprint Tips Boolean Operations Building design Building Design Software Building Efficiency Building Maintenance building modeling Building Systems Building Technology business tools ByLayer CAD CAD API CAD assembly CAD Automation CAD best practices CAD Blocks CAD CAM CAD Cleanup CAD collaboration CAD commands CAD comparison CAD consistency CAD Customization CAD Data Management CAD Design CAD drawing checks CAD efficiency CAD errors CAD Evolution CAD file management CAD File Size Reduction CAD Handover CAD Integration CAD Learning CAD libraries CAD line thickness CAD management CAD Migration CAD mistakes CAD modeling CAD Optimization CAD organization CAD Oversight CAD plugins CAD Productivity CAD project management CAD Projects CAD Rendering CAD Revisions CAD Scripting CAD Security CAD Sheet Management CAD sheet sets CAD Shortcuts CAD Skills CAD software CAD software 2026 CAD software training CAD standardization CAD standards CAD Tables CAD team CAD teams CAD technology CAD templates CAD Tips CAD Tools CAD Tracking CAD tricks CAD Tutorial CAD version control CAD workflow CAD workflow optimization CAD workflows CAM CAM Best Practices CAM for beginners CAM Optimization CAM simulation CAM strategies CAM Tips CAM tutorial CAM Workflow car design software Case Study central hub Central Hub Solutions centralized commands centralized documentation centralized management Centralized Sheet Set centralizing CAD CEO Guide CG Workflow CGI CGI design Character Animation Character Rig Character Rigging CI/CD cinematic lighting Civil 3D Civil 3D hidden gems Civil 3D productivity Civil 3D tips civil design software civil engineering Civil engineering software Clash Detection Class-A surfacing Clean Architecture clean CAD file Clean Code cleaning command Clear Output client engagement Cloth Simulation Cloud CAD cloud CAD storage Cloud Collaboration Cloud design platform Cloud Engineering Cloud Management Cloud Storage Cloud-Based CAD Cloud-First CMYK CNC CNC machining Coding Standards Coding Techniques Cognitive Load collaboration collaboration in CAD Collaboration Tips Collaboration Tools Collaborative CAD collaborative design Collaborative Drafting Color Coding color management Color Standards Color Theory command abbreviations Complex Projects Complex Renovation concept car conceptual workflow Connected Design construction Construction Analytics Construction Automation Construction BIM Construction Cloud construction documentation construction drawings construction management Construction Phases Construction Planning Construction Project Construction Projects Construction Scheduling Construction Technology construction tools construction tracking Contractor contractor tools Contractor Workflow Contraints corridor design Cost Effective Design cost estimation Create resizable blocks Creative Process Creative Teams creative tools CSS Filters CTB CTB STB Custom Hatch Custom Properties custom scripts custom tool palettes Custom visual styles Cutting Parameters Cybersecurity Data Backup Data Extraction data management Data Protection Data Reference Data Security Data Shortcut Data Sync Data Visualization deadline tracking Deep Work Demolition Dependency Rules Design Design Automation Design Best Practices Design Career Design Collaboration Design Communication Design Comparison Design consistency Design Coordination Design Documentation design efficiency Design Engineering design errors Design Hacks Design Handoff Design Innovation Design Intent design management Design Ops design optimization Design Options Design Organization Design Oversight Design Principles Design Process design productivity Design Quality design review Design Reviews design revisions Design Rules design software design software tips design standardization design standards Design System Design Systems Design Teams Design Techniques Design Technology design templates design tips Design Tools design tracking Design Tutorials Design Workflow design-to-construction Designer designer hacks Designer Tools Designer Workflow Development Workflow DevOps Digital Art Digital Art Techniques Digital Art Tips Digital Assets Digital Construction Digital Construction Technology Digital Content Digital Design Digital Documentation Digital Drafting digital drawing Digital engineering digital fabrication Digital Illustration Digital Library Digital Manufacturing digital marketing digital takeoff Digital Thread Digital Tools Digital Transformation Digital Twin Digital Twins digital workflow dimension dimension styles dimensioning Disaster Recovery document management Document Organization Documentation Documentation Control drafting drafting automation Drafting Best Practices Drafting Efficiency Drafting Guide Drafting productivity Drafting Shortcuts Drafting Standards Drafting Techniques Drafting Tips drafting tools Drafting Tricks Drafting Tutorials Drafting Workflow Drawing Drawing Accuracy Drawing Automation drawing consistency Drawing Coordination Drawing Depth Drawing for Beginners drawing management Drawing Organization drawing revisions Drawing Security Drawing standards Drawing Techniques drawing templates drawing tips Dref DST File DWG Compare DWG files DXF Export Dynamic Block Dynamic Block AutoCAD Dynamic Blocks dynamic data management Dynamic doors Dynamic Lists Dynamic windows Dynamics Dynamics Simulation Dynamo Dynamo automation early stage design eco design editing commands Educational Tech Efficiency efficient CAD efficient project management Electrical Systems Emerging Features Energy Analysis energy efficiency Energy Simulation Engineering Engineering Automation engineering CAD Engineering Collaboration Engineering Consultants engineering data Engineering Design Engineering Documentation Engineering Drawing engineering drawings engineering efficiency Engineering Guidelines Engineering Innovation Engineering Productivity engineering projects Engineering Skills engineering software Engineering Standards Engineering Teams Engineering Technology engineering tips engineering tools Engineering Tools 2025 Engineering Workflow Error Reduction Excel Excel Tips Export Workflow Express Tools External Reference Fabric Simulation facial animation Facial Rigging Facility Management Families Fast Structural Design faster delivery Field Documentation Fields Figma Best Practices Figma Tips file auditing File Management file naming File Optimization File Recovery Fire Flame flange tips flat pattern Fluid Effects Fluid Simulation Focus Tips Forge Development Forge Viewer FreeCAD Frontend Development Fusion 360 Fusion 360 API Fusion 360 guide Fusion 360 Tips Fusion 360 tutorial Future of Design Future Skills Game Design Game Development Game Effects Gamification Generative Design Geospatial Data GIS GitHub Actions Global design teams global illumination Google Apps Script Google Sheets GPU Acceleration grading optimization Graph Editor Graphic Design Graphic Design Tips Graphic Optimization Green Architecture green building Green Technology Grips Handoff Hatch Patterns HDRI health check Healthcare Facilities heavy CAD file Heavy CAD Files heritage building conservation hidden commands Hospital Design Hub Workflows HVAC HVAC Design Tools HVAC Engineering HVAC Optimization Hydraulic Modeling IK/FK Illustration Techniques Illustration Tips Illustration Tutorial iLogic Import Workflow Industrial Design Industry 4.0 Infrastructure Infrastructure as Code infrastructure design Infrastructure Monitoring Infrastructure Planning Infrastructure Technology InfraWorks innovation Insight Intelligent AutoCAD Hub Intelligent automation Intelligent Design intelligent modeling Intelligent Repetition Control Intelligent Sheet Management Intelligent Sheet Sets intelligent tools Intelligent Workflow Interactive Design interactive presentation Interior Design Inventor Inventor API Inventor Drawing Template Inventor Frame Generator Inventor Graphics Issues Inventor IDW Inventor Tips Inventor Tutorial IoT ISO 19650 ISO9001 joints Keyboard Shortcuts keyframe animation Keyframe generation Knowledge Management Landscape Design Large Assemblies Large Projects Laser Scan Layer Cleanup Layer Control layer conventions Layer Hierarchy Layer Isolation Layer Lock Layer Locking Layer Management Layer Naming Layer Organization Layer Rules layer standards Layer States Layered Architecture Layered Design Layered Process Audits Layered System Layered Systems Layering Techniques Layout Management layouts Leadership Lean Manufacturing Learn AutoCAD Learning Design Legacy CAD Legacy Drawings Library components Licensing light techniques Lighting Lighting and shading Lighting Techniques Line Weights lineweight Lineweight Tutorial Lineweights Linked Models Linking Drawings Liquid LISP Routines Locked Layers Machine Learning Machine Learning in CAD Machine Optimization Machining Efficiency machining productivity Macros maintenance command Manage multiple projects from a single hub with a centralized project management system that improves collaboration Management manual plotting manufacturing Manufacturing Innovation Manufacturing Technology Mapping Technology marketing visuals master sheet index Master Template Material Creation Material Libraries Matplotlib Maya Maya Animation Maya character animation Maya lighting Maya Python Maya Rigging Maya Shader Maya Tips Maya tutorial Maya Workflow measurement Mechanical Design Mechanical Engineering Media & Entertainment Mental Health MEP MEP Modeling Mesh-to-BIM Metal Fabrication Metal Structure milestone tracking Minimalism in Design Minimizing Mistakes modal analysis Model Clarity Model Management Model Optimization model space Modeling Secrets Modular Housing Monitoring Progress Motion capture Motion Design motion graphics motion simulation MotionBuilder Multi Office Workflow multi-axis machining Multi-Body Modeling Multi-Discipline Multi-Discipline Design Multi-Project Multi-Project Management Multi-Scale Drawings Multi-user Collaboration Multi-User Environment multileader multiple sheet sets naming convention Navisworks Navisworks Best Practices nCloth Net Zero Design New Construction Object Selection ObjectARX .NET API Office Templates Open Source CAD Optimization Organization Outsourcing OVERKILL OVERKILL AutoCAD Override Layers Page Setup Palette paper space Parallel Development parametric assembly Parametric Components Parametric Constraints parametric design parametric family Parametric Modeling particle effects particle systems PBR Workflow PDF PDF Export PDF Plotting PDF Publishing PDM system Personal Brand Phase Filters Phasing Photo Editing photorealism Photorealistic photorealistic render PlanGrid plot automation Plot Errors Plot Settings Plot Style Plot Style AutoCAD plot styles Plotting Plotting automation Plugin Tutorial Plumbing Design PM Tools point cloud Portfolio Post Construction Post-Processing Practice Drawing Pre-submission precision machining preconstruction workflow predictive analysis predictive animation Predictive Maintenance Predictive rigging Prefabrication Preloaded families Presentation-ready visuals Preventing Rework Print Accuracy Print Automation Printing Printing Quality Printing Tips Problem Solving Procedural animation procedural motion Procedural Rig Procedural Textures Process Improvement Product Design Product Development product lifecycle product rendering Product Visualization Productivity productivity and workflow efficiency. productivity tips productivity tools Professional 3D design Professional CAD Professional Development Professional Drafting Professional Drawings professional printing Professional Skills Professional Standards Professional Tips Professional Workflow Programming Programming Tips progress management Project Accuracy project automation Project Collaboration project consistency Project Coordination project dashboard Project Documentation project efficiency Project Goals Project Linking project management Project Management Tools project milestones Project Monitoring project organization Project Oversight project planning Project Progress project quality project timeline project tracking Project Visualization project workflow PTC Creo Publish Drawings PURGE PURGE AutoCAD Python Python Scripting Quality Control Rail Transit Rapid Prototyping Realism realistic rendering realistic scenes ReCap Redshift Shader reduce CAD errors reduce CAD file size Reduce Errors reduce manual updates Reducing redundancy Redundant Work Render Render Optimization Render Passes Render Quality Render Settings render tips Rendering rendering engine Rendering Engines Rendering Optimization rendering settings rendering software Rendering Techniques Rendering Tips Rendering Workflow RenderMan Renewable Energy Renovation Project Renovation Workflow repetition-free workflow repetitive drawing Repetitive Elements repetitive-free Reports Resizable Block restoration workflow Reusable Components Revision Control Revision Management Revision Tracking Revision Workflow Revit Revit add-ins Revit API Revit automation Revit Best Practices Revit Collaboration Revit Documentation Revit Family Revit integration Revit MEP Revit Performance Revit Phasing Revit plugin Revit Plugins Revit Scripting Revit skills Revit Standards Revit Strategies Revit Structure Revit Tags Revit Template Revit templates Revit Tips Revit tutorial Revit Workflow Ribbon Rigging Rigid Body robotics ROI Role Definition Room planning save hours of work Save Time save time CAD Scalability Scale Autodesk Schedules screen Scripts Sculpting Seamless Linking Secure Collaboration Self Improvement Sensor Data SEO SEO Guide Shader Networks Shaders Shared Files Sheet List Table sheet management Sheet Metal Sheet Metal Design Sheet Metal Tricks Sheet organization sheet set Sheet Set Automation Sheet Set Efficiency Sheet Set fields Sheet Set Index Sheet Set Management Sheet Set Manager Sheet Set Optimization Sheet Set Organization Sheet Set Properties Sheet Set Software Sheet Set Standards Sheet Set Strategy Sheet Set Tips Sheet Set Tools Sheet Sets sheet sets workflow Sheets shortcut keys Shortcuts Siemens NX Simulation simulation tools Sketch Sketching for Beginners Sketching Tricks Small Firms Smart Architecture Smart Block Smart Building Design Smart CAD smart CAD tools Smart City Smart Design smart dimensioning Smart Engineering Smart Factory Smart Infrastructur Smart Project Smart Sheet Management Smart Sheet Set Tools Smart Sheet Sets Smart Workflows Smoke Soft Body Software Architecture Software Compliance Software Design Software Development software ecosystem Software Engineering Software Hacks Software Management Software Performance Software Trends software troubleshooting Software Update Solar Energy Solar Panels SolidWorks Space planning Spreadsheet Automation Spreadsheet Tips SSM standard part libraries Standardization Standardize Standardized Layers standardized templates Startup Design static stress STB Steel Structure Design Stress-Free Structural Design Structural Modeling Structural Optimization subscription model Subscription Value surface finish Surface Modeling sustainability sustainable design Sustainable Manufacturing System Architecture system performance T-Spline task management team collaboration Team Efficiency Team Management Team Productivity Team Projects Team Scalability Team Training team training guide Tech Leadership Tech Teams Tech Tips Tech Tutorial technical documentation Technical Drafting Technical Drawing Technical Illustration technical support Technical Writing Template management Template Setup Template usage templates text settings text style Texture Mapping Texturing thermal analysis time efficiency Time Management time saving tools time savings time-saving time-saving tools Title Block title block automation Title Blocks Tool Libraries Tool Management Tool Palette Guide toolbar toolpath Toolpath Optimization Toolpaths Topography Track Track changes Troubleshooting Tutorial Tutorials UI Design UI UX Design UI UX Tips UI/UX UI/UX Workflow Unfolding Techniques urban planning User Interface (UI) UV Mapping UV Unwrap UX Best Practices UX Research UX Strategy UX UI Design UX Workflow V-Ray Vault Best Practices Vault Lifecycle Vault Mistakes Vector Plotting vehicle modeling version control VFX View Filters Viewport configuration viewports Virtual Environments virtual reality Visual Communication visual effects Visual Hierarchy Visual Organization visualization workflow VR VR Tools VRED Water Infrastructure Water Management Web Design Web Development WebGL Weight Painting What’s New in Autodesk Wind Energy Wind Turbines Workbook workflow Workflow Automation workflow efficiency Workflow Optimization Workflow Tips Worksets Worksharing Workspace XLS Xref Xref Management Xref Tips Xrefs เขียนแบบ