Skip to content

Commit

Permalink
Improve Python visualizer (#42)
Browse files Browse the repository at this point in the history
* Misc lint
* Fix null target issue
* Improve Python visualizer
* Lint
  • Loading branch information
bjrtx authored Mar 9, 2024
1 parent f411b04 commit b9dbb8f
Show file tree
Hide file tree
Showing 13 changed files with 72 additions and 124 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,11 @@ public class CorridorRedirection : MonoBehaviour {
[SerializeField] private Transform start, end;
private float NormalizedDistance => Mathf.InverseLerp(start.position.z, end.position.z, UserHead.position.z);

private void Start() => redirectionScript = this.GetComponent<WorldRedirection>();

private void Update() {
private void Start() => redirectionScript = GetComponent<WorldRedirection>();

private void Update() {
redirectionApplied = redirectionScript.GetAngularRedirection().eulerAngles.y;
if (redirectionApplied > redirectionAmount) {
redirectionScript.StopRedirection();
} else {
redirectionScript.StartRedirection();
}
redirectionScript.redirect = redirectionApplied < redirectionAmount;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,10 @@ public class CorridorRepresentation : MonoBehaviour {

private WorldRedirection script;

private void Start() {
script = this.GetComponent<WorldRedirection>();
}
private void Start() => script = GetComponent<WorldRedirection>();

private void Update() {
virtualCorridor.SetPositionAndRotation(physicalCorridor.position, physicalCorridor.rotation);
virtualCorridor.position = physicalCorridor.position + script.scene.GetHeadToHeadVector();
virtualCorridor.SetPositionAndRotation(physicalCorridor.position + script.scene.GetHeadToHeadVector(), physicalCorridor.rotation);
virtualCorridor.RotateAround(script.scene.physicalHead.position, Vector3.up, -script.scene.HeadToHeadRedirection.eulerAngles.y);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ GameObject:
- component: {fileID: 3345062529341880481}
- component: {fileID: 7088029602675669135}
- component: {fileID: 3621196646475796290}
- component: {fileID: 2164931620210237325}
- component: {fileID: 3527750865740220717}
m_Layer: 0
m_Name: ToolkitWorldRedirection
m_TagString: Untagged
Expand Down Expand Up @@ -54,13 +52,10 @@ MonoBehaviour:
physicalHead: {fileID: 0}
virtualHead: {fileID: 0}
physicalTarget: {fileID: 0}
physicalTargetPosition: {x: 0, y: 0, z: 0}
virtualTarget: {fileID: 0}
virtualTargetPosition: {x: 0, y: 0, z: 0}
origin: {fileID: 0}
targets:
- {fileID: 0}
radius: 5
applyDampening: 0
applySmoothing: 0
selectedTarget: {fileID: 0}
Expand All @@ -70,8 +65,14 @@ MonoBehaviour:
previousHeadPosition: {x: 0, y: 0, z: 0}
previousHeadRotation: {x: 0, y: 0, z: 0, w: 0}
previousRedirection: 0
strategyDirection: {x: 0, y: 0, z: 0}
parameters: {fileID: 0}
aggregateFunction: 0
enableHybridOverTime: 1
enableHybridRotational: 1
enableHybridCurvature: 1
redirect: 1
technique: 2
_technique: 0
strategy: 3
--- !u!114 &3621196646475796290
MonoBehaviour:
Expand All @@ -86,34 +87,6 @@ MonoBehaviour:
m_Name:
m_EditorClassIdentifier:
targetPrefab: {fileID: 84340963187888445, guid: 786584c1c713db54b9cad6864b80089b, type: 3}
active: {fileID: 0}
inactive: {fileID: 2100000, guid: fdc7faebe87ef18468772439a4b880b2, type: 2}
activeMaterial: {fileID: 0}
inactiveMaterial: {fileID: 0}
orbitResolution: 3
--- !u!114 &2164931620210237325
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 200869264966477082}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: f426d30751fd5b14c9c1093c441414b3, type: 3}
m_Name:
m_EditorClassIdentifier:
physicalHead: {fileID: 0}
world: {fileID: 0}
characteristics: 100
--- !u!114 &3527750865740220717
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 200869264966477082}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: a9825707130c9eb4a9c129292679e71c, type: 3}
m_Name:
m_EditorClassIdentifier:
parameters: {fileID: 11400000, guid: c39097e50bc3898498d2edf378be3a21, type: 2}
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
using UnityEngine;

using VHToolkit.Demo;

namespace VHToolkit.Calibration {

public class QuickCalibration : MonoBehaviour {
[SerializeField] private Transform physicalHead;
[SerializeField] private Transform world;

private void Update() {
private void Update() {
if (Input.GetKeyDown(KeyCode.Space)) {
Debug.Log("Resetting world position");
world.SetPositionAndRotation(new(physicalHead.position.x, 0f, physicalHead.position.z),
Quaternion.Euler(0f, physicalHead.rotation.eulerAngles.y, 0f));
// this.GetComponent<CorridorRedirection>().state = 0;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public class JsonLogging : MonoBehaviour {
private string fileName;
private readonly int bufferSize = 10; // number of records kept before writing to disk

private List<JsonRedirectionData> records = new();
private Queue<JsonRedirectionData> records = new();

private Interaction script;

Expand All @@ -61,7 +61,7 @@ private void Start() {
}

private void Update() {
void writeRecords<Data>(List<Data> records) {
void writeRecords<Data>(Queue<Data> records) {
if (records.Count > bufferSize) {
using var writer = new StreamWriter(fileName, append: true);
foreach (var record in records) {
Expand All @@ -71,15 +71,14 @@ void writeRecords<Data>(List<Data> records) {
}
}

records.Add(new JsonRedirectionData(script));
records.Enqueue(new JsonRedirectionData(script));
writeRecords(records);
}

public void CreateNewFile() {
Debug.Log("Create Json log file.");
Directory.CreateDirectory(logDirectoryPath);
fileName = $"{logDirectoryPath}{optionalFilenamePrefix}{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.jsonl";
records = new List<JsonRedirectionData>();
records = new Queue<JsonRedirectionData>();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ public override void Redirect(Scene scene) {
public class ResetBodyRedirection : BodyRedirectionTechnique {

public override void Redirect(Scene scene) {
foreach ((var limb, var t) in scene.limbs.Zip(scene.GetLimbInstantTranslation())) {
foreach (var (limb, t) in scene.limbs.Zip(scene.GetLimbInstantTranslation())) {
limb.virtualLimb.ForEach(vlimb => vlimb.Translate(t + t.magnitude * Toolkit.Instance.parameters.ResetRedirectionCoeff * (limb.physicalLimb.position - vlimb.position).normalized, relativeTo: Space.World));
};
}
Expand All @@ -172,7 +172,7 @@ public override void Redirect(Scene scene) {
public class NoBodyRedirection : BodyRedirectionTechnique {

public override void Redirect(Scene scene) {
foreach ((var limb, var t) in scene.limbs.Zip(scene.GetLimbInstantTranslation())) {
foreach (var (limb, t) in scene.limbs.Zip(scene.GetLimbInstantTranslation())) {
limb.virtualLimb.ForEach(vlimb => vlimb.Translate(t, relativeTo: Space.World));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,10 @@ namespace VHToolkit.Redirection {
/// <summary>
/// This is the base class for the visuo-haptic techniques managers such as BodyRedirection.
/// </summary>
public class Interaction : MonoBehaviour {
public class Interaction : MonoBehaviour {
public Scene scene;
public bool redirect = false;

public void StartRedirection() => redirect = true;

public void StopRedirection() => redirect = false;

public List<Transform> GetPhysicalLimbs() => scene.limbs.ConvertAll(limb => limb.physicalLimb);

public void AddPhysicalLimb(Transform physicalLimb, IEnumerable<Transform> virtualLimbs) => scene.limbs.Add(new(physicalLimb, virtualLimbs.ToList()));
Expand All @@ -24,5 +20,5 @@ public class Interaction : MonoBehaviour {
public List<Limb> GetLimbs() => scene.limbs;

public void SetLimbs(IEnumerable<Limb> limbs) => scene.limbs = limbs.ToList();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ float bearing(Transform t) => Vector3.Angle(
Vector3.ProjectOnPlane(t.position - scene.physicalHead.position, Vector3.up));
scene.selectedTarget = scene.targets.Where(t => t != null).MinBy(bearing);
if (scene.selectedTarget == null) {
Debug.LogWarning("Using SteerToMultipleTargets but scene.targets is empty.");
Debug.LogWarning("Using SteerToMultipleTargets but scene.targets is empty or all-null.");
return scene.physicalHead.forward;
}
return scene.selectedTarget.position - scene.physicalHead.position;
Expand All @@ -60,8 +60,6 @@ class SteerInDirection : WorldRedirectionStrategy {
/// </summary>
/// <param name="scene"></param>
/// <returns></returns>
public override Vector3 SteerTo(Scene scene) {
return scene.physicalHead.rotation * scene.strategyDirection;
}
public override Vector3 SteerTo(Scene scene) => scene.physicalHead.rotation * scene.strategyDirection;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ public override void OnInspectorGUI() {
base.OnInspectorGUI();

if (GUILayout.Button("Launch visualizer")) {
Socket socket = (Socket)target;
socket.LaunchVisualizer();
(target as Socket).LaunchVisualizer();
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@ private void StartSendingMessages() {

private void SendMessage(TcpClient client, WorldRedirectionData redirectionData) {
string json = JsonUtility.ToJson(redirectionData);
Debug.Log($"Sending: {json}");
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] messageBytes = System.Text.Encoding.ASCII.GetBytes(json + '\n');

Expand All @@ -121,7 +120,6 @@ private void Update() {
(script.redirect && scene.enableHybridRotational) ? Razzaque2001Rotational.GetRedirection(scene) : 0f,
(script.redirect && scene.enableHybridCurvature) ? Razzaque2001Curvature.GetRedirection(scene) : 0f,
(float)(DateTime.Now - startTime).TotalSeconds);
Debug.Log(redirectionData.ToString());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@ using UnityEngine;
public class TopViewCamera : MonoBehaviour {
public Transform trackedObject;

private void Update() => transform.SetPositionAndRotation(
new(trackedObject.position.x, transform.position.y, trackedObject.position.z),
transform.rotation
// Quaternion.Euler(90f, trackedObject.rotation.eulerAngles.y, 0f)
);
private void Update() => transform.position =
new(trackedObject.position.x, transform.position.y, trackedObject.position.z);
}
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,9 @@ private void UpdateTargetsOrbit(Scene scene, Vector3 leftTarget, Vector3 rightTa
}

private void MultipleTargets(Scene scene) {
FixTargetCounts(scene.targets.Count);
FixTargetCounts(scene.targets.Count(x => x != null));

foreach (var (first, second) in targets.Zip(scene.targets)) {
foreach (var (first, second) in targets.Zip(scene.targets.Where(x => x != null))) {
first.transform.position = second.position;

if (second == scene.selectedTarget) {
Expand Down
85 changes: 42 additions & 43 deletions python/RedirectionPlotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from gettext import translation
import json
import pathlib
import re
import matplotlib
import matplotlib.pyplot as plt

Expand All @@ -16,10 +15,10 @@

localedir = pathlib.Path(__file__).parent / 'locales'
translation('messages', localedir,languages=['fr_FR'], fallback=True).install()
_ = builtins.__dict__['_'] # convince linters '_' is defined
_ = builtins.__dict__['_'] # Convince linters '_' is defined


plt.ion() # turn on interactive mode
plt.ion() # Turn on interactive mode
fig = plt.figure(figsize=(10,6), constrained_layout=True)
ax1 = plt.subplot(211)
box = ax1.get_position()
Expand All @@ -35,43 +34,43 @@
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serversocket:
serversocket.bind(("localhost", 13000))
serversocket.listen(5)
clientsocket, __ = serversocket.accept()
with clientsocket.makefile() as file:
for line in file:
if not plt.get_fignums():
break
d = json.loads(line)
for k, l in {
"overTime": otrs, "rotational": rs, "curvature": cs, "overTimeSum": otrsSum,
"rotationalSum": rsSum, "curvatureSum": csSum, "time": ys, "maxSums": maxSums
}.items():
l.append(d[k])

ax1.clear()
ax2.clear()

ax1.set_ylim((0, 180))
ax1.set_title(_('Redirection amounts over time'), y=1.35)
ax1.set_ylabel(_('Redirection Applied to User (degrees)'))
labels=(_('Over time rotation'), _('Rotational'), _('Curvature'))
ax1.stackplot(
ys, otrsSum, rsSum, csSum, *zip(*maxSums),
labels=list(labels) + [l + '_max' for l in labels],
colors="rgbymc")
# ax1.plot(ys[-60:], hybrid[-60:], color='b', label='Hybrid', linewidth=0.5)

# ax2.set_xticks(list(map(int, ys[::10])))
# ax2.set_xlim((ys[-1] - 30, ys[-1]))
ax2.set_xlabel(_('Time from start (seconds)'), loc='right')
ax2.set_ylabel(_('Redirection per Second (degrees/s)'))
for series, color, label in zip([otrs, rs, cs], "rgb", labels):
ax2.plot(ys, series, color=color, label=label, linewidth=1)


ax1.legend(
loc='lower left',
bbox_to_anchor=(0, 1, 1, 0),
mode="expand",
ncols=3,
title=_("Redirection source"))
plt.pause(0.05)
with serversocket.accept()[0] as clientsocket:
with clientsocket.makefile() as file:
for line in file:
if not plt.get_fignums():
break
d = json.loads(line)
for k, l in {
"overTime": otrs, "rotational": rs, "curvature": cs, "overTimeSum": otrsSum,
"rotationalSum": rsSum, "curvatureSum": csSum, "time": ys, "maxSums": maxSums
}.items():
l.append(d[k])

ax1.clear()
ax2.clear()

ax1.set_ylim((0, 180))
ax1.set_title(_('Redirection amounts over time'), y=1.35)
ax1.set_ylabel(_('Redirection Applied to User (degrees)'))
labels=(_('Over time rotation'), _('Rotational'), _('Curvature'))
ax1.stackplot(
ys, otrsSum, rsSum, csSum, *zip(*maxSums),
labels=list(labels) + [l + '_max' for l in labels],
colors="rgbymc")
# ax1.plot(ys[-60:], hybrid[-60:], color='b', label='Hybrid', linewidth=0.5)

# ax2.set_xticks(list(map(int, ys[::10])))
# ax2.set_xlim((ys[-1] - 30, ys[-1]))
ax2.set_xlabel(_('Time from start (seconds)'), loc='right')
ax2.set_ylabel(_('Redirection per Second (degrees/s)'))
for series, color, label in zip([otrs, rs, cs], "rgb", labels):
ax2.plot(ys, series, color=color, label=label, linewidth=1)


ax1.legend(
loc='lower left',
bbox_to_anchor=(0, 1, 1, 0),
mode="expand",
ncols=3,
title=_("Redirection source"))
plt.pause(0.05)

0 comments on commit b9dbb8f

Please sign in to comment.