summaryrefslogtreecommitdiff
path: root/src/simulation/senses.js
blob: 0a882c91f0e72930226628278ed476638a3c71d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
'use strict';


const frozen = {
  size: 1,
  read: (world, agent) => {
    if (agent.flags.frozen === true) {
      return [ 1 ];
    } else {
      return [ 0 ];
    }
  },
};


// add two arrays together element-wise with a scaling factor
function array_scalesum(a, s, b) {
  return a.map((x, i) => x + (s*b[i]));
}
// determine the square of the distance between two cells
function lattice_dist2(x0, y0, x1, y1) {
  if (x0 === x1 && y0 === y1) { return 1; } // not proper distance but avoids divide-by-zero errors c:
  return ((x0-x1)**2) + ((y0-y1)**2);
}
const hear = {
  size: 8,
  read: (world, agent) => {
    const {x, y} = agent;
    const lattice_sounds = world.lattice
      .map((row, cy) => row.map((cell, cx) => [ 1/lattice_dist2(x, y, cx, cy), cell ]))
      .flat()
      .filter(([scale, cell]) => cell.flags.emit !== undefined)
      .reduce(
        (acc, [scale, cell]) => array_scalesum(acc, scale, cell.flags.emit),
        [0, 0, 0, 0, 0, 0, 0, 0]
      );
    const agent_sounds = world.agents
      .filter(a => a.flags.emit !== undefined)
      .reduce(
        (acc, a) => array_scalesum(acc, 1/lattice_dist2(x, y, a.x, a.y), a.flags.emit),
        [0, 0, 0, 0, 0, 0, 0, 0]
      );

    return array_scalesum(lattice_sounds, 1, agent_sounds).map(ch => Math.tanh(ch));
  },
};


export const senses = [
  frozen, hear,
];