headshape = ft_read_headshape('spherical-head.stl');
helmet = ft_read_headshape('spherical-helmet.stl');

% the CTF coordinate system has X towards the nose and Y towards the left
headshape.coordsys = 'ctf';
helmet.coordsys = 'ctf';

%%

figure
ft_plot_mesh(headshape, 'facecolor', 'skin_light', 'axes', true)
ft_plot_mesh(helmet, 'facecolor', 'lightgray')
ft_headlight % or lighting phong; camlight

%%

nas = [+100 0 0];
ini = [-100 0 0];
lpa = [0 +100 0];
rpa = [0 -100 0];

headshape.fid.pos = [
  nas
  ini
  lpa
  rpa
  ];

headshape.fid.label = {
  'nas'
  'ini'
  'lpa'
  'rpa'
  };

% now with fiducials
figure
ft_plot_headshape(headshape, 'facecolor', 'skin_light', 'axes', true)
alpha 0.5 % slightly transparent
ft_headlight

%%

% this places a lot of electrodes, see https://doi.org/10.1016/s1388-2457(00)00527-7
cfg = [];
cfg.fiducial.nas   = nas;
cfg.fiducial.ini   = ini;
cfg.fiducial.lpa   = lpa;
cfg.fiducial.rpa   = rpa;
cfg.method = '1020';
cfg.feedback = 'yes';
elec = ft_electrodeplacement(cfg, headshape);

%%

chansel = ft_channelselection({'eeg1020', '-Fpz', '-Oz'}, elec.label);

cfg = [];
cfg.elec = elec;
cfg.channel = chansel;
cfg.outwardshift = 5; % in mm

cfg.template = 'fieldline_sensor.stl';
sensor = ft_sensorplacement(cfg, headshape);

cfg.template = 'fieldline_holder.stl';
holder = ft_sensorplacement(cfg, headshape);

cfg.template = 'fieldline_cuttingtool.stl';
cuttingtool = ft_sensorplacement(cfg, headshape);

%%

figure
ft_plot_headshape(headshape, 'facecolor', 'skin', 'facealpha', 1, 'axes', 1);
ft_plot_mesh(helmet, 'facecolor', 'lightgray')

for i=1:numel(sensor)
  ft_plot_headshape(sensor(i), 'facecolor', 'r', 'facealpha', 1);
  ft_plot_headshape(holder(i), 'facecolor', 'g', 'facealpha', 1);
  ft_plot_headshape(cuttingtool(i), 'facecolor', 'b', 'facealpha', 0.5);
end
ft_headlight


%%

mkdir spherical

for i=1:numel(sensor)
  disp(chansel{i});
  filename = sprintf('spherical/sensor-%s.stl', chansel{i});
  ft_write_headshape(filename, sensor(i), 'fileformat', 'stl');
  filename = sprintf('spherical/holder-%s.stl', chansel{i});
  ft_write_headshape(filename, sensor(i), 'fileformat', 'stl');
  filename = sprintf('spherical/cuttingtool-%s.stl', chansel{i});
  ft_write_headshape(filename, sensor(i), 'fileformat', 'stl');
end

