# Research kit: run XR studies in a browser

Three ready-to-run experiments for VR headsets, phone or headset AR and ordinary screens, plus the shared parts every
study needs: consent, condition assignment, standard questionnaires, logging, and export to JSON and CSV. No server and
no build step. Open `research/` on the hosted site for the researcher page.

| Study | Topic | Devices | Design | Folder |
|---|---|---|---|---|
| Comfort Ride | Cybersickness: FOV restriction vs rest frame vs none | VR, screen | Between subjects | [comfort-ride/](comfort-ride/README.md) |
| How Far | Distance perception; contact shadow; ground texture | VR, AR, screen | Within (+ between) | [distance/](distance/README.md) |
| Pump Start-up | Training transfer; in-world cue vs step list | VR, screen | Between subjects | [procedure/](procedure/README.md) |

Why these topics, with references and sample sizes: [TOPICS.md](TOPICS.md). Ethics, consent, GDPR and a data
management plan to fill in: [ETHICS.md](ETHICS.md). **Read both before running a real study.**

## A session, from the participant's side

1. Information sheet and consent (`<study>/consent.html`); continue only after ticking the box.
2. Background questions (bands, "prefer not to say" everywhere), then any questionnaires before the task.
3. Choose **VR**, **AR** or **this screen** (only what the device supports is offered).
4. The task. Screens show a Stop button; headsets stop with B or Y, or by taking the headset off (Comfort Ride).
5. Questionnaires after the task (on the page; a headset's browser shows them after leaving VR).
6. The end screen shows the participant code and saves the results file; with an upload address set, it is sent too.

## Links and options

| Link | Effect |
|---|---|
| `comfort-ride/` | Participant link. The condition rotates through the list in each browser (balanced groups on a lab machine); the method is saved as `assignment`. |
| `?c=fov` | Fixes the condition (counterbalancing sheets, or one link per group on a recruitment platform). |
| `?pid=ABC123` | Uses an external code instead of a random one (pseudonymous: see ETHICS.md). |
| `?test=1` | Short version for trying and for automated tests; flagged `test_mode` and left out by the merge tool. |
| `?mode=vr` / `?mode=screen` | Shows only that start button (when the device supports it). |
| `?phase=retention&pid=…&c=…` | Pump Start-up delayed memory test (the end screen gives the participant this link). |
| `?ride=180` | Comfort Ride exposure in seconds (default 300). |
| `?distances=1,2,3` | How Far distances in metres (AR default 1 to 4 m, VR and screen 1.5 to 5.5 m). |
| `?lite` / `?ktx2` | Phone-size or headset-compressed assets (chosen automatically; saved in the file list for offline hosting). |

Everything that defines a stimulus (route, speeds, distances, timings) is in the `P` object at the top of each
`main.js` and is saved with every response (`summary.stimulus`). Change it there, change `version` in `createStudy`,
and say so in the preregistration.

## Data

One session = one JSON file `<study>_<phase>_<code>.json` (schema `vourla-research/1`) with: code, condition and how it
was assigned, device mode, consent version and time, every questionnaire (answers and scores), every trial, a timed
event log, a study summary, frame-rate statistics, and the `test_mode` and `emulated_xr` flags. The end screen also
offers a one-row **summary CSV** and a **trials CSV**.

- **Merge:** [tools/merge.html](tools/merge.html) reads any number of JSON files and writes one summary CSV (one row per
  session), one trials CSV and one events CSV, ready for R, SPSS, JASP or Python.
- **Lab machine:** every session is also kept in the browser; [tools/sessions.html](tools/sessions.html) lists them and
  downloads them all. Clear them after downloading (ETHICS.md section 5).
- **Analysis:** `python research/tools/analyze.py <study> summary.csv trials.csv` prints descriptives and first tests per
  condition (pandas; scipy and statsmodels if installed). A starting point for the preregistered plan, not a substitute.

Scores: SSQ subscales and total with the Kennedy et al. (1993) weights; IPQ 0 to 6 with SP2, INV3 and REAL1 reversed
(subtract 3 for the -3..+3 convention); SUS 0 to 100; raw NASA-TLX (mean of six 0 to 100 scales). Check each item list
against its source before publishing (references in `lib/questionnaires.js`).

### Collecting files from remote participants (optional upload)

By default nothing leaves the participant's browser: they download the file and send it (or the researcher collects
it on a lab machine). To have results sent automatically, set `submit` in the study's `createStudy({...})` call:

- `submit: { type: 'post', url: 'https://…' }` sends the JSON as the body of a POST (`text/plain`, so no CORS
  preflight). Any endpoint run or approved by the institution works. A free option is a **Google Apps Script** web app
  bound to a Google Sheet (use an institutional account with a data-processing agreement):

  ```js
  // Extensions > Apps Script, paste, Deploy > New deployment > Web app, access "Anyone". Use the /exec URL.
  function doPost(e) {
    const d = JSON.parse(e.postData.contents);
    SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].appendRow([new Date(), d.study, d.phase, d.pid, d.condition, d.completed, e.postData.contents]);
    return ContentService.createTextOutput('ok');
  }
  ```
- `submit: { type: 'netlify', form: 'results' }` posts to Netlify Forms (free tier: 100 submissions a month). Add
  `<form name="results" netlify hidden><input name="pid"><input name="study"><textarea name="data"></textarea></form>` to
  the study's `index.html` and turn on form detection in the Netlify site settings.

Neither upload has been tried against the real services from here (the cloud test session cannot reach them); both are
tested against a local endpoint. Try one session end to end before a real study, and name the service in the consent
text. If an upload fails, the end screen tells the participant to download the file instead.

## Hosting

Any static web host with **HTTPS** (WebXR needs it; `localhost` also works).

- **Download a study as a zip:** the "Download as zip" button on the researcher page, or
  `node research/tools/pack.mjs distance --out /tmp/zips`. The zip holds everything the study needs (its file list is
  `<study>/files.json`, made by `node research/tools/files.cjs`), opens at its root, and runs from any folder.
- **Netlify:** drag the unzipped folder onto app.netlify.com/drop (free), or keep using this repository's site.
- **GitHub Pages:** a public repository with the unzipped folder, Pages turned on.
- **University web server:** copy the folder; ask IT that `.js` is served as `text/javascript`.
- **Local lab without internet:** `npx serve` (or `python -m http.server`) in the unzipped folder on the lab PC and open
  `http://localhost:<port>/` there. A headset on the same network needs HTTPS: use the PC's browser, or a host above.

## Before a real study

1. Fill in `consent.html` and ETHICS.md section 5; get ethics approval.
2. Decide hypotheses, sample size, exclusions and analysis; preregister them.
3. Set `version`, `assignment` and (optional) `submit` in `main.js`; host the approved copy.
4. Pilot with 3 to 5 people on the devices you will use; read their files with merge.html.
5. Never use `?test=1` links for participants.

## For developers

```text
lib/study.js           createStudy: consent, ask(questionnaire), chooseMode, log, trial, frame, withdrawDialog, finish
lib/questionnaires.js  SSQ, FMS, IPQ, SUS, NASA-TLX (raw), background, travel sickness; with scoring
lib/xr.js              enterXR (VR/AR), controller buttons, in-headset rating panel and keypad, pauseBehindScreens
lib/zip.js             zip writer for the download button and tools/pack.mjs
tools/                 merge.html, sessions.html, analyze.py, files.cjs (file lists), pack.mjs (zips)
<study>/               index.html, main.js, consent.html, README.md, files.json, test/study.cjs
test/                  helpers (a participant who clicks real controls), package.cjs (zip runs from a bare folder), data.cjs (scoring and analysis)
```

The studies are built on the same kit as the demos (`shared/kit.js`, `v2/kit2.js`), so VR, AR, mouse, touch, controllers
and bare hands all work the same way. Each study's settings are fixed for every participant: the kit's comfort menu is
hidden and its screen vignette is off, because they would be uncontrolled variables.

Tests (no headset needed; each starts its own server):

```bash
cd tools/xrtest && npm install && cd ../..         # once
node research/test/data.cjs                         # scoring, CSV, merge and analysis on simulated data (~10 s)
node research/comfort-ride/test/study.cjs           # screen, emulated Quest 3, phone; ride, ratings, stop and delete
node research/distance/test/study.cjs               # screen, emulated Quest 3, emulated AR room, phone
node research/procedure/test/study.cjs              # screen + retention visit, emulated Quest 3, phone
node research/test/package.cjs                      # file lists current; each zip runs from a bare folder
```
