Grid9 C++ Implementation
The C++ implementation of Grid9 delivers maximum performance coordinate compression for high-throughput systems. With zero-allocation design and C++11 compatibility, it's perfect for real-time applications, embedded systems, and performance-critical software.
Key Features: Zero-allocation design • C++11 compatible • CMake build system • Header-only option • Template optimizations • SIMD-friendly • Thread-safe
Installation
CMake Integration
# Clone and build
git clone https://github.com/pedrof69/Grid9.git
cd Grid9/cpp
mkdir build && cd build
cmake ..
make -j$(nproc)
# Install system-wide
sudo make install
CMake Package Integration
# CMakeLists.txt
find_package(Grid9 REQUIRED)
add_executable(my_app main.cpp)
target_link_libraries(my_app Grid9::grid9)
Header-Only Usage
# Copy headers to your project
cp -r Grid9/cpp/include/grid9 /path/to/your/project/include/
# Include in your code
#include "grid9/UniformPrecisionCoordinateCompressor.h"
vcpkg Integration
# Install via vcpkg
vcpkg install grid9
# CMakeLists.txt with vcpkg
find_package(grid9 CONFIG REQUIRED)
target_link_libraries(my_app PRIVATE grid9::grid9)
Quick Start
Basic Usage
#include "grid9/UniformPrecisionCoordinateCompressor.h"
#include <iostream>
int main() {
using namespace grid9;
// Encode coordinates to Grid9 code
std::string code = UniformPrecisionCoordinateCompressor::encode(40.7128, -74.0060);
std::cout << "Grid9 Code: " << code << std::endl; // "Q7KH2BBYF"
// Decode Grid9 code to coordinates
auto coords = UniformPrecisionCoordinateCompressor::decode("Q7KH2BBYF");
std::cout << "Lat: " << coords.first << ", Lon: " << coords.second << std::endl;
// Result: Lat: 40.712779, Lon: -74.005988
// Human-readable format
std::string readable = UniformPrecisionCoordinateCompressor::encode(40.7128, -74.0060, true);
std::cout << "Human readable: " << readable << std::endl; // "Q7K-H2B-BYF"
return 0;
}
High-Performance Batch Processing
#include "grid9/CoordinateOperations.h"
#include <vector>
#include <chrono>
int main() {
using namespace grid9;
// Prepare large dataset
std::vector<std::pair<double, double>> coordinates;
coordinates.reserve(1000000);
for (int i = 0; i < 1000000; ++i) {
coordinates.emplace_back(
40.0 + (rand() % 1000) / 10000.0,
-74.0 + (rand() % 1000) / 10000.0
);
}
// Benchmark encoding
auto start = std::chrono::high_resolution_clock::now();
std::vector<std::string> codes = CoordinateOperations::batchEncode(coordinates);
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
std::cout << "Encoded " << codes.size() << " coordinates in "
<< duration.count() << " microseconds" << std::endl;
std::cout << "Rate: " << (codes.size() * 1000000.0 / duration.count())
<< " ops/second" << std::endl;
return 0;
}
Real-Time Systems Integration
#include "grid9/UniformPrecisionCoordinateCompressor.h"
#include <thread>
#include <atomic>
#include <queue>
class RealTimeLocationProcessor {
private:
std::atomic<bool> running{true};
std::queue<std::pair<double, double>> locationQueue;
std::mutex queueMutex;
public:
void processLocationUpdates() {
while (running.load()) {
std::pair<double, double> coords;
{
std::lock_guard<std::mutex> lock(queueMutex);
if (locationQueue.empty()) continue;
coords = locationQueue.front();
locationQueue.pop();
}
// Zero-allocation encoding for real-time performance
std::string code = grid9::UniformPrecisionCoordinateCompressor::encode(
coords.first, coords.second);
// Process the encoded location
handleLocationUpdate(code);
}
}
void addLocation(double lat, double lon) {
std::lock_guard<std::mutex> lock(queueMutex);
locationQueue.emplace(lat, lon);
}
private:
void handleLocationUpdate(const std::string& grid9Code) {
// Send to navigation system, log, etc.
}
};
API Reference
UniformPrecisionCoordinateCompressor
| Method | Description | Returns |
|---|---|---|
encode(double lat, double lon) |
Encode coordinates to Grid9 code | std::string |
encode(double lat, double lon, bool humanReadable) |
Encode with optional formatting | std::string |
decode(const std::string& code) |
Decode Grid9 code to coordinates | std::pair<double, double> |
calculateDistance(const std::string& code1, const std::string& code2) |
Calculate distance in meters | double |
getNeighbors(const std::string& code) |
Get adjacent Grid9 codes | std::vector<std::string> |
isValidEncoding(const std::string& code) |
Validate Grid9 code format | bool |
getActualPrecision(double lat, double lon) |
Get precision information | std::tuple<double, double, double> |
CoordinateOperations
| Method | Description | Returns |
|---|---|---|
batchEncode(const std::vector<std::pair<double, double>>&) |
Encode multiple coordinates | std::vector<std::string> |
batchDecode(const std::vector<std::string>&) |
Decode multiple codes | std::vector<std::pair<double, double>> |
findNearby(double lat, double lon, double radius) |
Find codes within radius | std::vector<std::string> |
Performance Optimizations
Encoding Speed
12M+ operations/second
Decoding Speed
14M+ operations/second
Memory Usage
Zero heap allocations
Compiler Optimizations
# Optimized build flags
cmake -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_CXX_FLAGS="-O3 -march=native -flto" \
..
# For specific CPU targets
cmake -DCMAKE_CXX_FLAGS="-O3 -mavx2 -msse4.2" ..
Template Specializations
// Specialized for common coordinate types
template<>
class FastCoordinateEncoder<float> {
public:
static inline std::string encode(float lat, float lon) noexcept {
// Optimized single-precision implementation
return grid9::UniformPrecisionCoordinateCompressor::encode(
static_cast<double>(lat), static_cast<double>(lon));
}
};
// Usage for single-precision coordinates
std::string code = FastCoordinateEncoder<float>::encode(40.7128f, -74.0060f);
Advanced Integration
Embedded Systems
// Minimal resource usage for embedded systems
#define GRID9_NO_EXCEPTIONS // Disable exception handling
#define GRID9_STATIC_ONLY // Static allocation only
#include "grid9/UniformPrecisionCoordinateCompressor.h"
class EmbeddedLocationTracker {
private:
static constexpr size_t MAX_LOCATIONS = 100;
char locationBuffer[MAX_LOCATIONS][10]; // Fixed-size buffer
size_t locationCount = 0;
public:
bool addLocation(double lat, double lon) {
if (locationCount >= MAX_LOCATIONS) return false;
std::string code = grid9::UniformPrecisionCoordinateCompressor::encode(lat, lon);
std::strcpy(locationBuffer[locationCount], code.c_str());
locationCount++;
return true;
}
const char* getLocation(size_t index) const {
return (index < locationCount) ? locationBuffer[index] : nullptr;
}
};
Multi-Threading
#include <thread>
#include <future>
#include <algorithm>
class ParallelLocationProcessor {
public:
static std::vector<std::string> encodeParallel(
const std::vector<std::pair<double, double>>& coordinates) {
const size_t numThreads = std::thread::hardware_concurrency();
const size_t chunkSize = coordinates.size() / numThreads;
std::vector<std::future<std::vector<std::string>>> futures;
for (size_t i = 0; i < numThreads; ++i) {
size_t start = i * chunkSize;
size_t end = (i == numThreads - 1) ? coordinates.size() : start + chunkSize;
futures.push_back(std::async(std::launch::async, [&coordinates, start, end]() {
std::vector<std::string> results;
results.reserve(end - start);
for (size_t j = start; j < end; ++j) {
results.push_back(grid9::UniformPrecisionCoordinateCompressor::encode(
coordinates[j].first, coordinates[j].second));
}
return results;
}));
}
// Combine results
std::vector<std::string> allResults;
for (auto& future : futures) {
auto results = future.get();
allResults.insert(allResults.end(), results.begin(), results.end());
}
return allResults;
}
};
Game Engine Integration
// Integration with Unreal Engine or similar
class UE4LocationComponent : public UActorComponent {
private:
FString cachedGrid9Code;
FVector lastEncodedLocation;
public:
UFUNCTION(BlueprintCallable, Category = "Grid9")
FString GetGrid9Code() {
FVector currentLocation = GetOwner()->GetActorLocation();
// Only re-encode if location changed significantly
if (FVector::Dist(currentLocation, lastEncodedLocation) > 100.0f) {
double lat = currentLocation.Y / 100000.0; // Convert UE4 units to lat
double lon = currentLocation.X / 100000.0; // Convert UE4 units to lon
std::string code = grid9::UniformPrecisionCoordinateCompressor::encode(lat, lon);
cachedGrid9Code = FString(code.c_str());
lastEncodedLocation = currentLocation;
}
return cachedGrid9Code;
}
};
Testing and Validation
Unit Tests
# Build with tests (requires Google Test)
cmake -DWITH_TESTS=ON ..
make -j$(nproc)
# Run tests
ctest --verbose
# Run specific test
./build/grid9_test --gtest_filter="*EncodeDecode*"
Performance Benchmarks
#include <benchmark/benchmark.h>
static void BM_Grid9Encode(benchmark::State& state) {
for (auto _ : state) {
std::string result = grid9::UniformPrecisionCoordinateCompressor::encode(
40.7128, -74.0060);
benchmark::DoNotOptimize(result);
}
}
BENCHMARK(BM_Grid9Encode);
static void BM_Grid9Decode(benchmark::State& state) {
std::string code = "Q7KH2BBYF";
for (auto _ : state) {
auto result = grid9::UniformPrecisionCoordinateCompressor::decode(code);
benchmark::DoNotOptimize(result);
}
}
BENCHMARK(BM_Grid9Decode);
BENCHMARK_MAIN();
Requirements
- C++11 or later ✓
- CMake 3.12+ for building
- No external runtime dependencies
- Optional: Google Test for unit tests
- Optional: Google Benchmark for performance tests
Compiler Support
- GCC 5.0+ ✓
- Clang 3.8+ ✓
- MSVC 2017+ ✓
- Intel C++ Compiler ✓
Build Configuration
Custom CMake Options
# Available build options
cmake -DGRID9_BUILD_TESTS=ON \
-DGRID9_BUILD_BENCHMARKS=ON \
-DGRID9_ENABLE_SIMD=ON \
-DGRID9_HEADER_ONLY=OFF \
..
Cross-Compilation
# ARM64 cross-compilation
cmake -DCMAKE_TOOLCHAIN_FILE=toolchain-arm64.cmake \
-DCMAKE_BUILD_TYPE=Release \
..
# WASM compilation with Emscripten
emcmake cmake -DCMAKE_BUILD_TYPE=Release ..
Need help? Check out the full source code and examples on GitHub or open an issue.