diff --git a/src/tools.c b/src/tools.c
index 73684c82662870d368f7dd360c84635654f06434..c2a20c933900a4cf002a6e332b2eeb6f0b144512 100644
--- a/src/tools.c
+++ b/src/tools.c
@@ -182,6 +182,16 @@ void pairs_all_density(struct runner *r, struct cell *ci, struct cell *cj) {
   float r2, hi, hj, hig2, hjg2, dx[3];
   struct part *pi, *pj;
 
+  const struct engine *restrict e = r->e;
+  
+  /* Get the sort ID. */
+  double shift[3] = {0.0, 0.0, 0.0};
+  const int sid = space_getsid(e->s, &ci, &cj, shift);
+  
+  /* Get the cutoff shift. */
+  double rshift = 0.0;
+  for (int k = 0; k < 3; k++) rshift += shift[k] * runner_shift[sid][k];
+  
   /* Implements a double-for loop and checks every interaction */
   for (int i = 0; i < ci->count; ++i) {
 
@@ -196,7 +206,7 @@ void pairs_all_density(struct runner *r, struct cell *ci, struct cell *cj) {
       /* Pairwise distance */
       r2 = 0.0f;
       for (int k = 0; k < 3; k++) {
-        dx[k] = ci->parts[i].x[k] - cj->parts[j].x[k];
+        dx[k] = (ci->parts[i].x[k] - shift[k]) - cj->parts[j].x[k];
         r2 += dx[k] * dx[k];
       }
 
@@ -223,7 +233,7 @@ void pairs_all_density(struct runner *r, struct cell *ci, struct cell *cj) {
       /* Pairwise distance */
       r2 = 0.0f;
       for (int k = 0; k < 3; k++) {
-        dx[k] = cj->parts[j].x[k] - ci->parts[i].x[k];
+        dx[k] = (cj->parts[j].x[k] + shift[k]) - ci->parts[i].x[k];
         r2 += dx[k] * dx[k];
       }