This C++ code snippit will generate a hexagonally close-packed set of spheres. It’s usefull when you are simulating a block of material and want its initial rest configuration to be at its most packed state.
The code contains two functions, addHCPSheet and addHCPCube; addHCPCube creates layers of sheets using the addHCPSheet function. The input to addHCPCube is the number of particles in each dimension of the cube, the sphere radius and the global 3D position of the cube.
The code is not optimal, I usually only use it to generate particles at the begining of the simulation so the overhead incurred by division operations is not that much.