VoxelSim/simulation.cpp

74 lines
2.3 KiB
C++
Raw Permalink Normal View History

2025-01-26 07:38:56 +01:00
#include "simulation.h"
2025-01-27 20:29:50 +01:00
#include <cstring>
2025-01-26 07:38:56 +01:00
namespace simulation
{
2025-01-27 20:29:50 +01:00
int getCellOffset(
2025-01-26 07:38:56 +01:00
unsigned char x,
unsigned char y,
unsigned char z,
2025-01-27 20:29:50 +01:00
SimulationGrid* grid)
2025-01-26 07:38:56 +01:00
{
2025-01-27 20:29:50 +01:00
if (x < grid->x_max && y < grid->y_max && z < grid->z_max)
2025-01-26 07:38:56 +01:00
{
2025-01-27 20:29:50 +01:00
int offset = x + y * grid->x_max + z * (grid->y_max * grid->x_max);
2025-01-26 07:38:56 +01:00
return offset;
}
return -1;
}
void step(
double millisecondsSinceLastStep,
2025-01-27 20:29:50 +01:00
SimulationGrid* grid)
2025-01-26 07:38:56 +01:00
{
2025-01-27 20:29:50 +01:00
for (unsigned char x = 0; x < grid->x_max; x++)
2025-01-26 07:38:56 +01:00
{
2025-01-27 20:29:50 +01:00
for (unsigned char y = 0; y < grid->y_max; y++)
2025-01-26 07:38:56 +01:00
{
2025-01-27 20:29:50 +01:00
for (unsigned char z = 0; z < grid->z_max; z++)
2025-01-26 07:38:56 +01:00
{
2025-01-27 20:29:50 +01:00
int offset = getCellOffset(x, y, z, grid);
unsigned int material = grid->in[offset];
2025-01-26 07:38:56 +01:00
switch (material)
{
case WATER:
{
2025-01-27 20:29:50 +01:00
int downOffset = getCellOffset(x, y - 1, z, grid);
2025-01-26 07:38:56 +01:00
// Flow down if cell is empty
2025-01-27 20:29:50 +01:00
if (downOffset >= 0 && grid->out[downOffset] == 0)
2025-01-26 07:38:56 +01:00
{
2025-01-27 20:29:50 +01:00
grid->out[downOffset] = material;
grid->out[offset] = VACUUM;
} else
{
// Stay in the same location
grid->out[offset] = material;
2025-01-26 07:38:56 +01:00
}
2025-01-27 20:29:50 +01:00
break;
}
case MERCURY:
{
break;
2025-01-26 07:38:56 +01:00
}
default:
2025-01-27 20:29:50 +01:00
{
grid->out[offset] = material;
}
2025-01-26 07:38:56 +01:00
}
}
}
}
}
2025-01-27 20:29:50 +01:00
void prepareForNextStep(SimulationGrid* grid)
{
// Flip the buffers
unsigned int* inCells = grid->in;
grid->in = grid->out;
grid->out = inCells;
// Clear out buffer
size_t bufferSizeInBytes = sizeof(unsigned int) * grid->x_max * grid->y_max * grid->z_max;
std::memset(grid->out, VACUUM, bufferSizeInBytes);
}
2025-01-26 07:38:56 +01:00
}