Merge remote-tracking branch 'gui/main' into merge-gui-and-server

This commit is contained in:
lucas lelievre committed 2022-11-13 02:27:28 +01:00
commit ae94de39b1
430 files changed
+44297 -50

No files matched your search

@@ -0,0 +1,24 @@
package dev.slimevr.gui;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
public abstract class AbstractComponentListener implements ComponentListener {
@Override
public void componentResized(ComponentEvent e) {
}
@Override
public void componentMoved(ComponentEvent e) {
}
@Override
public void componentShown(ComponentEvent e) {
}
@Override
public void componentHidden(ComponentEvent e) {
}
}
@@ -0,0 +1,36 @@
package dev.slimevr.gui;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public abstract class AbstractWindowListener implements WindowListener {
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
}
@@ -0,0 +1,220 @@
package dev.slimevr.gui;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.JButton;
import javax.swing.border.EmptyBorder;
import java.awt.event.MouseEvent;
import java.util.EnumMap;
import io.eiren.util.ann.AWTThread;
import javax.swing.event.MouseInputAdapter;
import dev.slimevr.VRServer;
import dev.slimevr.autobone.AutoBoneListener;
import dev.slimevr.autobone.AutoBoneProcessType;
import dev.slimevr.autobone.AutoBone.Epoch;
import dev.slimevr.gui.swing.EJBox;
import dev.slimevr.poserecorder.PoseFrames;
import dev.slimevr.vr.processor.skeleton.SkeletonConfigOffsets;
public class AutoBoneWindow extends JFrame implements AutoBoneListener {
private EJBox pane;
private final transient VRServer server;
private final transient SkeletonConfigGUI skeletonConfig;
private JButton saveRecordingButton;
private JButton applyButton;
private JLabel processLabel;
private JLabel lengthsLabel;
public AutoBoneWindow(VRServer server, SkeletonConfigGUI skeletonConfig) {
super("Skeleton Auto-Configuration");
this.server = server;
this.skeletonConfig = skeletonConfig;
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));
add(
new JScrollPane(
pane = new EJBox(BoxLayout.PAGE_AXIS),
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
)
);
server.getAutoBoneHandler().addListener(this);
build();
}
@AWTThread
private void build() {
pane.add(new EJBox(BoxLayout.LINE_AXIS) {
{
setBorder(new EmptyBorder(i(5)));
add(new JButton("Start Recording") {
{
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (!isEnabled()) {
return;
}
server.getAutoBoneHandler().startRecording();
}
});
}
});
add(saveRecordingButton = new JButton("Save Recording") {
{
setEnabled(false);
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (!isEnabled()) {
return;
}
server.getAutoBoneHandler().saveRecording();
}
});
}
});
add(new JButton("Auto-Adjust") {
{
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (!isEnabled()) {
return;
}
server.getAutoBoneHandler().processRecording();
}
});
}
});
add(applyButton = new JButton("Apply Values") {
{
setEnabled(false);
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (!isEnabled()) {
return;
}
server.getAutoBoneHandler().applyValues();
// Update GUI values after applying
skeletonConfig.refreshAll();
}
});
}
});
}
});
pane.add(new EJBox(BoxLayout.LINE_AXIS) {
{
setBorder(new EmptyBorder(i(5)));
add(processLabel = new JLabel("Processing has not been started..."));
}
});
pane.add(new EJBox(BoxLayout.LINE_AXIS) {
{
setBorder(new EmptyBorder(i(5)));
add(lengthsLabel = new JLabel("No config changes"));
}
});
// Pack and display
pack();
setLocationRelativeTo(null);
setVisible(false);
}
@Override
public void onAutoBoneProcessStatus(
AutoBoneProcessType processType,
String message,
long current,
long total,
boolean completed,
boolean success
) {
if (message != null) {
if (total == 0) {
processLabel.setText(String.format("%s: %s", processType.name(), message));
} else {
processLabel
.setText(
String
.format(
"%s (%d/%d) [%.2f%%]: %s",
processType.name(),
current,
total,
(current / (double) total) * 100.0,
message
)
);
}
} else {
if (total != 0) {
processLabel
.setText(
String
.format(
"%s (%d/%d) [%.2f%%]",
processType.name(),
current,
total,
(current / (double) total) * 100.0
)
);
}
}
}
@Override
public void onAutoBoneRecordingEnd(PoseFrames recording) {
saveRecordingButton.setEnabled(true);
}
@Override
public void onAutoBoneEpoch(Epoch epoch) {
processLabel
.setText(
String
.format(
"PROCESS: Epoch %d/%d (%.2f%%) Error: %.4f (SD %.4f)",
epoch.epoch,
epoch.totalEpochs,
(epoch.epoch / (double) epoch.totalEpochs) * 100.0,
epoch.epochError.getMean(),
epoch.epochError.getStandardDeviation()
)
);
lengthsLabel.setText(server.getAutoBoneHandler().getLengthsString());
}
@Override
public void onAutoBoneEnd(EnumMap<SkeletonConfigOffsets, Float> configValues) {
applyButton.setEnabled(true);
}
}
@@ -0,0 +1,89 @@
package dev.slimevr.gui;
import dev.slimevr.gui.swing.EJBox;
import dev.slimevr.vr.trackers.CalibratingTracker;
import dev.slimevr.vr.trackers.Tracker;
import io.eiren.util.ann.AWTThread;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.MouseEvent;
public class CalibrationWindow extends JFrame {
public final Tracker tracker;
private JTextArea currentCalibration;
private JTextArea newCalibration;
private JButton calibrateButton;
public CalibrationWindow(Tracker t) {
super(t.getName() + " calibration");
this.tracker = t;
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.LINE_AXIS));
build();
}
public void currentCalibrationReceived(String str) {
java.awt.EventQueue.invokeLater(() -> {
currentCalibration.setText(str);
pack();
});
}
public void newCalibrationReceived(String str) {
java.awt.EventQueue.invokeLater(() -> {
calibrateButton.setText("Calibrate");
newCalibration.setText(str);
pack();
});
}
@AWTThread
private void build() {
Container pane = getContentPane();
pane.add(calibrateButton = new JButton("Calibrate") {
{
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
calibrateButton.setText("Calibrating...");
((CalibratingTracker) tracker)
.startCalibration(CalibrationWindow.this::newCalibrationReceived);
}
});
}
});
pane.add(new EJBox(BoxLayout.PAGE_AXIS) {
{
setBorder(new EmptyBorder(i(5)));
add(new JLabel("Current calibration"));
add(currentCalibration = new JTextArea(10, 25));
((CalibratingTracker) tracker)
.requestCalibrationData(CalibrationWindow.this::currentCalibrationReceived);
}
});
pane.add(new EJBox(BoxLayout.PAGE_AXIS) {
{
setBorder(new EmptyBorder(i(5)));
add(new JLabel("New calibration"));
add(newCalibration = new JTextArea(10, 25));
}
});
// Pack and display
pack();
setLocationRelativeTo(null);
setVisible(true);
java.awt.EventQueue.invokeLater(() -> {
toFront();
repaint();
});
}
}
@@ -0,0 +1,68 @@
package dev.slimevr.gui;
import com.melloware.jintellitype.HotkeyListener;
import com.melloware.jintellitype.JIntellitype;
import dev.slimevr.VRServer;
import dev.slimevr.config.KeybindingsConfig;
import io.eiren.util.OperatingSystem;
import io.eiren.util.ann.AWTThread;
import io.eiren.util.logging.LogManager;
public class Keybinding implements HotkeyListener {
private static final int RESET = 1;
private static final int QUICK_RESET = 2;
public final VRServer server;
public final KeybindingsConfig config;
@AWTThread
public Keybinding(VRServer server) {
this.server = server;
this.config = server.getConfigManager().getVrConfig().getKeybindings();
if (OperatingSystem.getCurrentPlatform() != OperatingSystem.WINDOWS) {
LogManager
.info(
"[Keybinding] Currently only supported on Windows. Keybindings will be disabled."
);
return;
}
try {
if (JIntellitype.getInstance() instanceof JIntellitype) {
JIntellitype.getInstance().addHotKeyListener(this);
String resetBinding = this.config.getResetBinding();
JIntellitype.getInstance().registerHotKey(RESET, resetBinding);
LogManager.info("[Keybinding] Bound reset to " + resetBinding);
String quickResetBinding = this.config.getQuickResetBinding();
JIntellitype.getInstance().registerHotKey(QUICK_RESET, quickResetBinding);
LogManager.info("[Keybinding] Bound quick reset to " + quickResetBinding);
}
} catch (Throwable e) {
LogManager
.info(
"[Keybinding] JIntellitype initialization failed. Keybindings will be disabled. Try restarting your computer."
);
}
}
@AWTThread
@Override
public void onHotKey(int identifier) {
switch (identifier) {
case RESET -> {
LogManager.info("[Keybinding] Reset pressed");
server.resetTrackers();
}
case QUICK_RESET -> {
LogManager.info("[Keybinding] Quick reset pressed");
server.resetTrackersYaw();
}
}
}
}
@@ -0,0 +1,89 @@
package dev.slimevr.gui;
import java.awt.*;
import java.text.AttributedCharacterIterator.Attribute;
import java.util.Map;
public class ScalableFont extends Font {
protected float scale = 1.0f;
protected int initSize;
protected float initPointSize;
public ScalableFont(Map<? extends Attribute, ?> attributes) {
super(attributes);
this.initSize = this.size;
this.initPointSize = this.pointSize;
}
public ScalableFont(Font font) {
super(font);
if (font instanceof ScalableFont sourceFont) {
this.initSize = sourceFont.getInitSize();
this.initPointSize = sourceFont.getInitSize2D();
this.size = this.initSize;
this.pointSize = this.initPointSize;
} else {
this.initSize = this.size;
this.initPointSize = this.pointSize;
}
}
public ScalableFont(Font font, float scale) {
super(font);
if (font instanceof ScalableFont sourceFont) {
this.initSize = sourceFont.getInitSize();
this.initPointSize = sourceFont.getInitSize2D();
} else {
this.initSize = this.size;
this.initPointSize = this.pointSize;
}
setScale(scale);
}
public ScalableFont(String name, int style, int size) {
super(name, style, size);
this.initSize = this.size;
this.initPointSize = this.pointSize;
}
public ScalableFont(String name, int style, int size, float scale) {
super(name, style, size);
this.initSize = this.size;
this.initPointSize = this.pointSize;
setScale(scale);
}
public int getInitSize() {
return initSize;
}
public float getInitSize2D() {
return initPointSize;
}
public float getScale() {
return scale;
}
private void setScale(float scale) {
this.scale = scale;
float newPointSize = initPointSize * scale;
this.size = (int) (newPointSize + 0.5);
this.pointSize = newPointSize;
}
}
@@ -0,0 +1,200 @@
package dev.slimevr.gui;
import dev.slimevr.VRServer;
import dev.slimevr.gui.swing.ButtonTimer;
import dev.slimevr.gui.swing.EJBagNoStretch;
import dev.slimevr.vr.processor.skeleton.Skeleton;
import dev.slimevr.vr.processor.skeleton.SkeletonConfigOffsets;
import io.eiren.util.StringUtils;
import io.eiren.util.ann.ThreadSafe;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.Map;
public class SkeletonConfigGUI extends EJBagNoStretch {
private final VRServer server;
private final VRServerGUI gui;
private final AutoBoneWindow autoBone;
private final Map<SkeletonConfigOffsets, SkeletonLabel> labels = new HashMap<>();
private JCheckBox precisionCb;
public SkeletonConfigGUI(VRServer server, VRServerGUI gui) {
super(false, true);
this.server = server;
this.gui = gui;
this.autoBone = new AutoBoneWindow(server, this);
setAlignmentY(TOP_ALIGNMENT);
server.humanPoseProcessor.addSkeletonUpdatedCallback(this::skeletonUpdated);
skeletonUpdated(null);
}
@ThreadSafe
public void skeletonUpdated(Skeleton newSkeleton) {
java.awt.EventQueue.invokeLater(() -> {
removeAll();
int row = 0;
add(new TimedResetButton("Reset All"), s(c(1, row, 2), 3, 1));
add(new JButton("Auto") {
{
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
autoBone.setVisible(true);
autoBone.toFront();
}
});
}
}, s(c(4, row, 2), 3, 1));
add(precisionCb = new JCheckBox("Precision adjust"), c(0, row, 2));
precisionCb.setSelected(false);
row++;
for (SkeletonConfigOffsets config : SkeletonConfigOffsets.values) {
add(new JLabel(config.label), c(0, row, 2));
add(new AdjButton("+", config, false), c(1, row, 2));
add(new SkeletonLabel(config), c(2, row, 2));
add(new AdjButton("-", config, true), c(3, row, 2));
// Only use a timer on configs that need time to get into
// position for
switch (config) {
case TORSO, LEGS_LENGTH -> add(
new TimedResetButton("Reset", config),
c(4, row, 2)
);
default -> add(new ResetButton("Reset", config), c(4, row, 2));
}
row++;
}
gui.refresh();
});
}
float proportionsIncrement(Boolean negative) {
float increment = 0.01f;
if (negative)
increment = -0.01f;
if (precisionCb.isSelected())
increment /= 2f;
return increment;
}
String getBoneLengthString(SkeletonConfigOffsets joint) { // Rounded to
// the
// nearest 0.5
return (StringUtils
.prettyNumber(
Math.round(server.humanPoseProcessor.getSkeletonConfig(joint) * 200) / 2.0f,
1
));
}
@ThreadSafe
public void refreshAll() {
java.awt.EventQueue
.invokeLater(
() -> labels.forEach((joint, label) -> label.setText(getBoneLengthString(joint)))
);
}
private void change(SkeletonConfigOffsets joint, float diff) {
// Update config value
float current = server.humanPoseProcessor.getSkeletonConfig(joint);
server.humanPoseProcessor.setSkeletonConfig(joint, current + diff);
server.humanPoseProcessor.getSkeletonConfig().save();
server.getConfigManager().saveConfig();
// Update GUI
labels.get(joint).setText(getBoneLengthString(joint));
}
private void reset(SkeletonConfigOffsets joint) {
// Update config value
server.humanPoseProcessor.resetSkeletonConfig(joint);
server.humanPoseProcessor.getSkeletonConfig().save();
server.getConfigManager().saveConfig();
// Update GUI
labels.get(joint).setText(getBoneLengthString(joint));
}
private void resetAll() {
// Update config value
server.humanPoseProcessor.resetAllSkeletonConfigs();
server.humanPoseProcessor.getSkeletonConfig().save();
server.getConfigManager().saveConfig();
// Update GUI
refreshAll();
}
private class SkeletonLabel extends JLabel {
public SkeletonLabel(SkeletonConfigOffsets joint) {
super(getBoneLengthString(joint));
labels.put(joint, this);
}
}
private class AdjButton extends JButton {
public AdjButton(String text, SkeletonConfigOffsets joint, boolean negative) {
super(text);
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
change(joint, proportionsIncrement(negative));
}
});
}
}
private class ResetButton extends JButton {
public ResetButton(String text, SkeletonConfigOffsets joint) {
super(text);
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
reset(joint);
}
});
}
}
private class TimedResetButton extends JButton {
public TimedResetButton(String text, SkeletonConfigOffsets joint) {
super(text);
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
ButtonTimer.runTimer(TimedResetButton.this, 3, text, () -> reset(joint));
}
});
}
public TimedResetButton(String text) {
super(text);
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
ButtonTimer
.runTimer(TimedResetButton.this, 3, text, SkeletonConfigGUI.this::resetAll);
}
});
}
}
}
@@ -0,0 +1,108 @@
package dev.slimevr.gui;
import com.jme3.math.FastMath;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import dev.slimevr.VRServer;
import dev.slimevr.gui.swing.EJBagNoStretch;
import dev.slimevr.util.ann.VRServerThread;
import dev.slimevr.vr.processor.TransformNode;
import dev.slimevr.vr.processor.skeleton.Skeleton;
import io.eiren.util.StringUtils;
import io.eiren.util.ann.ThreadSafe;
import io.eiren.util.collections.FastList;
import javax.swing.*;
import java.awt.*;
import java.util.List;
public class SkeletonList extends EJBagNoStretch {
private static final long UPDATE_DELAY = 50;
private final VRServerGUI gui;
private final List<NodeStatus> nodes = new FastList<>();
Quaternion q = new Quaternion();
Vector3f v = new Vector3f();
float[] angles = new float[3];
private long lastUpdate = 0;
public SkeletonList(VRServer server, VRServerGUI gui) {
super(false, true);
this.gui = gui;
setAlignmentY(TOP_ALIGNMENT);
server.addSkeletonUpdatedCallback(this::skeletonUpdated);
}
@ThreadSafe
public void skeletonUpdated(Skeleton newSkeleton) {
java.awt.EventQueue.invokeLater(() -> {
removeAll();
nodes.clear();
add(new JLabel("Joint"), c(0, 0, 2));
add(new JLabel("X"), c(1, 0, 2));
add(new JLabel("Y"), c(2, 0, 2));
add(new JLabel("Z"), c(3, 0, 2));
add(new JLabel("Pitch"), c(4, 0, 2));
add(new JLabel("Yaw"), c(5, 0, 2));
add(new JLabel("Roll"), c(6, 0, 2));
TransformNode[] allNodes = newSkeleton.getAllNodes();
for (int i = 0; i < allNodes.length; i++) {
nodes.add(new NodeStatus(allNodes[i], i + 1));
}
gui.refresh();
});
}
@VRServerThread
public void updateBones() {
if (lastUpdate + UPDATE_DELAY > System.currentTimeMillis())
return;
lastUpdate = System.currentTimeMillis();
java.awt.EventQueue.invokeLater(() -> {
for (NodeStatus node : nodes) {
node.update();
}
});
}
private class NodeStatus {
TransformNode n;
JLabel x;
JLabel y;
JLabel z;
JLabel a1;
JLabel a2;
JLabel a3;
public NodeStatus(TransformNode node, int n) {
this.n = node;
add(new JLabel(node.getName()), c(0, n, 2, GridBagConstraints.FIRST_LINE_START));
add(x = new JLabel("0"), c(1, n, 2, GridBagConstraints.FIRST_LINE_START));
add(y = new JLabel("0"), c(2, n, 2, GridBagConstraints.FIRST_LINE_START));
add(z = new JLabel("0"), c(3, n, 2, GridBagConstraints.FIRST_LINE_START));
add(a1 = new JLabel("0"), c(4, n, 2, GridBagConstraints.FIRST_LINE_START));
add(a2 = new JLabel("0"), c(5, n, 2, GridBagConstraints.FIRST_LINE_START));
add(a3 = new JLabel("0"), c(6, n, 2, GridBagConstraints.FIRST_LINE_START));
}
public void update() {
n.worldTransform.getTranslation(v);
n.worldTransform.getRotation(q);
q.toAngles(angles);
x.setText(StringUtils.prettyNumber(v.x, 2));
y.setText(StringUtils.prettyNumber(v.y, 2));
z.setText(StringUtils.prettyNumber(v.z, 2));
a1.setText(StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0));
a2.setText(StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0));
a3.setText(StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0));
}
}
}
@@ -0,0 +1,104 @@
package dev.slimevr.gui;
import com.jme3.math.FastMath;
import dev.slimevr.VRServer;
import dev.slimevr.config.FiltersConfig;
import dev.slimevr.filtering.TrackerFilters;
import dev.slimevr.gui.swing.EJBagNoStretch;
import io.eiren.util.StringUtils;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.event.MouseEvent;
public class TrackersFiltersGUI extends EJBagNoStretch {
private final VRServer server;
private final JLabel amountLabel;
TrackerFilters filterType;
float filterAmount;
FiltersConfig filtersConfig;
public TrackersFiltersGUI(VRServer server, VRServerGUI gui) {
super(false, true);
this.server = server;
filtersConfig = server
.getConfigManager()
.getVrConfig()
.getFilters();
int row = 0;
setAlignmentY(TOP_ALIGNMENT);
add(Box.createVerticalStrut(10));
filterType = server.getConfigManager().getVrConfig().getFilters().enumGetType();
JComboBox<String> filterSelect;
add(filterSelect = new JComboBox<>(), s(c(0, row, 2), 4, 1));
for (TrackerFilters f : TrackerFilters.values()) {
filterSelect.addItem(f.name());
}
if (filterType != null) {
filterSelect.setSelectedItem(filterType.toString());
}
filterSelect.addActionListener((e) -> {
filterType = TrackerFilters
.getByConfigkey(filterSelect.getSelectedItem().toString());
filtersConfig
.enumSetType(filterType);
filtersConfig
.updateTrackersFilters();
server.getConfigManager().saveConfig();
});
add(Box.createVerticalStrut(40));
row++;
filterAmount = FastMath
.clamp(
server.getConfigManager().getVrConfig().getFilters().getAmount(),
0.1f,
1
);
add(new JLabel("Amount"), c(0, row, 2));
add(new AdjButton("+", false), c(1, row, 2));
add(
amountLabel = new JLabel(StringUtils.prettyNumber(filterAmount * 100f) + "%"),
c(2, row, 2)
);
add(new AdjButton("-", true), c(3, row, 2));
}
void adjustAmount(boolean neg) {
if (neg) {
filterAmount = FastMath.clamp(filterAmount - 0.1f, 0.1f, 1);
} else {
filterAmount = FastMath.clamp(filterAmount + 0.1f, 0.1f, 1);
}
amountLabel.setText((StringUtils.prettyNumber(filterAmount * 100f)) + "%");
filtersConfig
.setAmount(filterAmount);
filtersConfig
.updateTrackersFilters();
server.getConfigManager().saveConfig();
}
private class AdjButton extends JButton {
public AdjButton(String text, boolean neg) {
super(text);
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
adjustAmount(neg);
}
});
}
}
}
@@ -0,0 +1,551 @@
package dev.slimevr.gui;
import com.jme3.math.FastMath;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import dev.slimevr.VRServer;
import dev.slimevr.config.TrackerConfig;
import dev.slimevr.gui.swing.EJBagNoStretch;
import dev.slimevr.gui.swing.EJBoxNoStretch;
import dev.slimevr.vr.trackers.*;
import io.eiren.util.StringUtils;
import io.eiren.util.ann.AWTThread;
import io.eiren.util.ann.ThreadSafe;
import io.eiren.util.collections.FastList;
import javax.swing.*;
import java.awt.*;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
public class TrackersList extends EJBoxNoStretch {
private static final long UPDATE_DELAY = 50;
private final VRServer server;
private final VRServerGUI gui;
private final List<TrackerPanel> trackers = new FastList<>();
Quaternion q = new Quaternion();
Vector3f v = new Vector3f();
float[] angles = new float[3];
private long lastUpdate = 0;
private boolean debug = false;
public TrackersList(VRServer server, VRServerGUI gui) {
super(BoxLayout.PAGE_AXIS, false, true);
this.server = server;
this.gui = gui;
setAlignmentY(TOP_ALIGNMENT);
server.addNewTrackerConsumer(this::newTrackerAdded);
}
private static int getTrackerSort(Tracker t) {
Tracker tracker = t.get();
if (tracker instanceof IMUTracker)
return 0;
if (tracker instanceof HMDTracker)
return 100;
if (tracker instanceof ComputedTracker)
return 200;
return 1000;
}
@AWTThread
public void setDebug(boolean debug) {
this.debug = debug;
build();
}
@AWTThread
private void build() {
removeAll();
trackers.sort(Comparator.comparingInt(tr -> getTrackerSort(tr.t)));
Class<? extends Tracker> currentClass = null;
EJBoxNoStretch line = null;
boolean first = true;
for (TrackerPanel tr : trackers) {
Tracker t = tr.t.get();
if (currentClass != t.getClass()) {
currentClass = t.getClass();
if (line != null)
line.add(Box.createHorizontalGlue());
line = null;
line = new EJBoxNoStretch(BoxLayout.LINE_AXIS, false, true);
line.add(Box.createHorizontalGlue());
JLabel nameLabel;
line.add(nameLabel = new JLabel(currentClass.getSimpleName()));
nameLabel.setFont(nameLabel.getFont().deriveFont(Font.BOLD));
line.add(Box.createHorizontalGlue());
add(line);
line = null;
}
if (line == null) {
line = new EJBoxNoStretch(BoxLayout.LINE_AXIS, false, true);
add(Box.createVerticalStrut(3));
add(line);
first = true;
} else {
line.add(Box.createHorizontalStrut(3));
first = false;
}
tr.build();
line.add(tr);
if (!first)
line = null;
}
validate();
gui.refresh();
}
@ThreadSafe
public void updateTrackers() {
if (lastUpdate + UPDATE_DELAY > System.currentTimeMillis())
return;
lastUpdate = System.currentTimeMillis();
java.awt.EventQueue.invokeLater(() -> {
for (TrackerPanel tr : trackers) {
tr.update();
}
});
}
@ThreadSafe
public void newTrackerAdded(Tracker t) {
java.awt.EventQueue.invokeLater(() -> {
trackers.add(new TrackerPanel(t));
build();
});
}
private class TrackerPanel extends EJBagNoStretch {
final Tracker t;
JLabel position;
JLabel rotation;
JLabel status;
JLabel url;
JLabel tps;
JLabel bat;
JLabel ping;
JLabel raw;
JLabel rawMag;
JLabel calibration;
JLabel magAccuracy;
JLabel adj;
JLabel adjYaw;
JLabel adjGyro;
JLabel correction;
JLabel signalStrength;
JLabel rotQuat;
JLabel rotAdj;
JLabel temperature;
JLabel accel;
@AWTThread
public TrackerPanel(Tracker t) {
super(false, true);
this.t = t;
}
@SuppressWarnings("unchecked")
@AWTThread
public TrackerPanel build() {
int row = 0;
Tracker tracker = t.get();
removeAll();
JLabel nameLabel;
add(
nameLabel = new JLabel(
t.getCustomName() != null ? t.getCustomName() : t.getDisplayName()
),
s(c(0, row, 2, GridBagConstraints.FIRST_LINE_START), 4, 1)
);
nameLabel.setFont(nameLabel.getFont().deriveFont(Font.BOLD));
row++;
if (t.userEditable()) {
TrackerConfig cfg = server.getConfigManager().getVrConfig().getTracker(t);
JComboBox<String> desSelect;
add(
desSelect = new JComboBox<>(),
s(c(0, row, 2, GridBagConstraints.FIRST_LINE_START), 2, 1)
);
desSelect.addItem("NONE");
for (TrackerPosition p : TrackerPosition.values) {
desSelect.addItem(p.name());
}
if (cfg.getDesignation() != null) {
TrackerPosition
.getByDesignation(cfg.getDesignation())
.ifPresentOrElse(
trackerPosition -> desSelect.setSelectedItem(trackerPosition.name()),
() -> desSelect.setSelectedItem("NONE")
);
}
desSelect.addActionListener(e -> {
if (desSelect.getSelectedItem() == "NONE") {
t.setBodyPosition(null);
} else {
TrackerPosition p = TrackerPosition
.valueOf(String.valueOf(desSelect.getSelectedItem()));
t.setBodyPosition(p);
}
server.trackerUpdated(t);
});
if (tracker instanceof IMUTracker imu) {
JComboBox<String> mountSelect;
add(
mountSelect = new JComboBox<>(),
s(c(2, row, 2, GridBagConstraints.FIRST_LINE_START), 2, 1)
);
for (TrackerMountingRotation p : TrackerMountingRotation.values) {
mountSelect.addItem(p.name());
}
TrackerMountingRotation selected = TrackerMountingRotation
.fromQuaternion(imu.getMountingRotation());
mountSelect
.setSelectedItem(
Objects
.requireNonNullElse(selected, TrackerMountingRotation.BACK)
.name()
);
mountSelect.addActionListener(e -> {
TrackerMountingRotation tr = TrackerMountingRotation
.valueOf(String.valueOf(mountSelect.getSelectedItem()));
imu.setMountingRotation(tr.quaternion);
server.trackerUpdated(t);
});
}
row++;
}
if (t.getDevice() != null && t.getDevice().getIpAddress() != null) {
add(new JLabel("URL:"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
add(
url = new JLabel(""),
c(1, row, 2, GridBagConstraints.FIRST_LINE_START)
);
row++;
}
if (t.hasRotation())
add(new JLabel("Rotation"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
if (t.hasPosition())
add(new JLabel("Position"), c(1, row, 2, GridBagConstraints.FIRST_LINE_START));
add(new JLabel("TPS"), c(3, row, 2, GridBagConstraints.FIRST_LINE_START));
if (tracker instanceof TrackerWithWireless) {
add(new JLabel("Ping"), c(2, row, 2, GridBagConstraints.FIRST_LINE_START));
add(new JLabel("Signal"), c(4, row, 2, GridBagConstraints.FIRST_LINE_START));
}
row++;
if (t.hasRotation())
add(
rotation = new JLabel("0 0 0"),
c(0, row, 2, GridBagConstraints.FIRST_LINE_START)
);
if (t.hasPosition())
add(
position = new JLabel("0 0 0"),
c(1, row, 2, GridBagConstraints.FIRST_LINE_START)
);
if (tracker instanceof TrackerWithWireless) {
add(ping = new JLabel(""), c(2, row, 2, GridBagConstraints.FIRST_LINE_START));
add(
signalStrength = new JLabel(""),
c(4, row, 2, GridBagConstraints.FIRST_LINE_START)
);
}
if (tracker instanceof TrackerWithTPS) {
add(tps = new JLabel("0"), c(3, row, 2, GridBagConstraints.FIRST_LINE_START));
} else {
add(new JLabel(""), c(3, row, 2, GridBagConstraints.FIRST_LINE_START));
}
row++;
add(new JLabel("Status:"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
add(
status = new JLabel(t.getStatus().toString().toLowerCase()),
c(1, row, 2, GridBagConstraints.FIRST_LINE_START)
);
if (tracker instanceof TrackerWithBattery) {
add(new JLabel("Battery:"), c(2, row, 2, GridBagConstraints.FIRST_LINE_START));
add(bat = new JLabel("0"), c(3, row, 2, GridBagConstraints.FIRST_LINE_START));
}
row++;
add(new JLabel("Raw:"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
add(
raw = new JLabel("0 0 0"),
s(c(1, row, 2, GridBagConstraints.FIRST_LINE_START), 3, 1)
);
if (debug && tracker instanceof IMUTracker) {
add(new JLabel("Quat:"), c(2, row, 2, GridBagConstraints.FIRST_LINE_START));
add(rotQuat = new JLabel("0"), c(3, row, 2, GridBagConstraints.FIRST_LINE_START));
}
row++;
if (debug && tracker instanceof IMUTracker) {
add(new JLabel("Raw mag:"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
add(
rawMag = new JLabel("0 0 0"),
s(c(1, row, 2, GridBagConstraints.FIRST_LINE_START), 3, 1)
);
add(new JLabel("Gyro fix:"), c(2, row, 2, GridBagConstraints.FIRST_LINE_START));
add(
new JLabel(String.format("0x%8x", tracker.hashCode())),
s(c(3, row, 2, GridBagConstraints.FIRST_LINE_START), 3, 1)
);
row++;
add(new JLabel("Cal:"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
add(
calibration = new JLabel("0"),
c(1, row, 2, GridBagConstraints.FIRST_LINE_START)
);
add(new JLabel("Mag acc:"), c(2, row, 2, GridBagConstraints.FIRST_LINE_START));
add(
magAccuracy = new JLabel("0°"),
c(3, row, 2, GridBagConstraints.FIRST_LINE_START)
);
row++;
add(new JLabel("Correction:"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
add(
correction = new JLabel("0 0 0"),
s(c(1, row, 2, GridBagConstraints.FIRST_LINE_START), 3, 1)
);
add(new JLabel("RotAdj:"), c(2, row, 2, GridBagConstraints.FIRST_LINE_START));
add(rotAdj = new JLabel("0"), c(3, row, 2, GridBagConstraints.FIRST_LINE_START));
row++;
add(new JLabel("Accel:"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
add(accel = new JLabel("0 0 0"), c(1, row, 2, GridBagConstraints.FIRST_LINE_START));
row++;
}
if (debug && t instanceof ReferenceAdjustedTracker) {
add(new JLabel("Att fix:"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
add(adj = new JLabel("0 0 0 0"), c(1, row, 2, GridBagConstraints.FIRST_LINE_START));
add(new JLabel("Yaw Fix:"), c(2, row, 2, GridBagConstraints.FIRST_LINE_START));
add(
adjYaw = new JLabel("0 0 0 0"),
c(3, row, 2, GridBagConstraints.FIRST_LINE_START)
);
row++;
add(new JLabel("Gyro Fix:"), c(0, row, 2, GridBagConstraints.FIRST_LINE_START));
add(
adjGyro = new JLabel("0 0 0 0"),
c(1, row, 2, GridBagConstraints.FIRST_LINE_START)
);
add(new JLabel("Temp:"), c(2, row, 2, GridBagConstraints.FIRST_LINE_START));
add(
temperature = new JLabel("?"),
c(3, row, 2, GridBagConstraints.FIRST_LINE_START)
);
}
setBorder(BorderFactory.createLineBorder(new Color(0x663399), 2, false));
TrackersList.this.add(this);
return this;
}
@SuppressWarnings("unchecked")
@AWTThread
public void update() {
if (position == null && rotation == null)
return;
Tracker tracker = t.get();
t.getRotation(q);
t.getPosition(v);
q.toAngles(angles);
if (position != null)
position
.setText(
StringUtils.prettyNumber(v.x, 1)
+ " "
+ StringUtils.prettyNumber(v.y, 1)
+ " "
+ StringUtils.prettyNumber(v.z, 1)
);
if (rotation != null)
rotation
.setText(
StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0)
+ " "
+ StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0)
+ " "
+ StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0)
);
status.setText(t.getStatus().toString().toLowerCase());
if (t.getDevice() != null && t.getDevice().getIpAddress() != null)
url.setText("udp:/" + t.getDevice().getIpAddress());
if (tracker instanceof TrackerWithTPS) {
tps.setText(StringUtils.prettyNumber(((TrackerWithTPS) tracker).getTPS(), 1));
}
if (tracker instanceof TrackerWithBattery twb) {
float level = twb.getBatteryLevel();
float voltage = twb.getBatteryVoltage();
if (level == 0.0f) {
bat.setText(String.format("%sV", StringUtils.prettyNumber(voltage, 2)));
} else if (voltage == 0.0f) {
bat.setText(String.format("%d%%", Math.round(level)));
} else {
bat
.setText(
String
.format(
"%d%% (%sV)",
Math.round(level),
StringUtils.prettyNumber(voltage, 2)
)
);
}
}
if (t instanceof ReferenceAdjustedTracker) {
ReferenceAdjustedTracker<Tracker> rat = (ReferenceAdjustedTracker<Tracker>) t;
if (adj != null) {
rat.attachmentFix.toAngles(angles);
adj
.setText(
StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0)
+ " "
+ StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0)
+ " "
+ StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0)
);
}
if (adjYaw != null) {
rat.yawFix.toAngles(angles);
adjYaw
.setText(
StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0)
+ " "
+ StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0)
+ " "
+ StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0)
);
}
if (adjGyro != null) {
rat.gyroFix.toAngles(angles);
adjGyro
.setText(
StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0)
+ " "
+ StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0)
+ " "
+ StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0)
);
}
}
if (tracker instanceof TrackerWithWireless) {
ping.setText(String.valueOf(((TrackerWithWireless) tracker).getPing()));
int signal = ((TrackerWithWireless) tracker).getSignalStrength();
if (signal == -1) {
signalStrength.setText("N/A");
} else {
// -40 dBm is excellent, -95 dBm is very poor
int percentage = (signal - -95) * (100 - 0) / (-40 - -95) + 0;
percentage = Math.max(Math.min(percentage, 100), 0);
signalStrength.setText(percentage + "% " + "(" + signal + " dBm" + ")");
}
}
tracker.getRotation(q);
q.toAngles(angles);
raw
.setText(
StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0)
+ " "
+ StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0)
+ " "
+ StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0)
);
if (tracker instanceof IMUTracker imu) {
if (rawMag != null) {
imu.rotMagQuaternion.toAngles(angles);
rawMag
.setText(
StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0)
+ " "
+ StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0)
+ " "
+ StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0)
);
}
if (calibration != null)
calibration.setText(imu.calibrationStatus + " / " + imu.magCalibrationStatus);
if (magAccuracy != null)
magAccuracy
.setText(
StringUtils
.prettyNumber(imu.magnetometerAccuracy * FastMath.RAD_TO_DEG, 1)
+ "°"
);
if (correction != null) {
imu.getCorrection(q);
q.toAngles(angles);
correction
.setText(
StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0)
+ " "
+ StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0)
+ " "
+ StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0)
);
}
if (rotQuat != null) {
imu.rotQuaternion.toAngles(angles);
rotQuat
.setText(
StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0)
+ " "
+ StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0)
+ " "
+ StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0)
);
}
if (rotAdj != null) {
imu.rotAdjust.toAngles(angles);
rotAdj
.setText(
StringUtils.prettyNumber(angles[0] * FastMath.RAD_TO_DEG, 0)
+ " "
+ StringUtils.prettyNumber(angles[1] * FastMath.RAD_TO_DEG, 0)
+ " "
+ StringUtils.prettyNumber(angles[2] * FastMath.RAD_TO_DEG, 0)
);
}
if (temperature != null) {
if (imu.temperature == 0.0f) {
// Can't be exact 0, so no info received
temperature.setText("?");
} else {
temperature.setText(StringUtils.prettyNumber(imu.temperature, 1) + "∘C");
}
}
if (accel != null) {
accel
.setText(
StringUtils.prettyNumber(imu.accelVector.x, 1)
+ " "
+ StringUtils.prettyNumber(imu.accelVector.y, 1)
+ " "
+ StringUtils.prettyNumber(imu.accelVector.z, 1)
);
}
}
}
}
}
@@ -0,0 +1,571 @@
package dev.slimevr.gui;
import dev.slimevr.Main;
import dev.slimevr.VRServer;
import dev.slimevr.config.WindowConfig;
import dev.slimevr.gui.swing.ButtonTimer;
import dev.slimevr.gui.swing.EJBagNoStretch;
import dev.slimevr.gui.swing.EJBox;
import dev.slimevr.gui.swing.EJBoxNoStretch;
import dev.slimevr.platform.windows.WindowsNamedPipeBridge;
import dev.slimevr.vr.processor.skeleton.SkeletonConfigToggles;
import dev.slimevr.vr.trackers.TrackerRole;
import io.eiren.util.MacOSX;
import io.eiren.util.OperatingSystem;
import io.eiren.util.StringUtils;
import io.eiren.util.ann.AWTThread;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static javax.swing.BoxLayout.LINE_AXIS;
import static javax.swing.BoxLayout.PAGE_AXIS;
public class VRServerGUI extends JFrame {
public static final String TITLE = "SlimeVR Server (" + Main.VERSION + ")";
public final VRServer server;
private final TrackersList trackersList;
private final TrackersFiltersGUI trackersFiltersGUI;
private final SkeletonList skeletonList;
private final EJBox pane;
private JButton resetButton;
private JButton floorClipButton;
private JButton skatingCorrectionButton;
private WindowConfig config;
@AWTThread
public VRServerGUI(VRServer server) {
super(TITLE);
this.config = server.getConfigManager().getVrConfig().getWindow();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
if (OperatingSystem.getCurrentPlatform() == OperatingSystem.OSX)
MacOSX.setTitle(TITLE);
try {
List<BufferedImage> images = new ArrayList<>(6);
images.add(ImageIO.read(VRServerGUI.class.getResource("/icon16.png")));
images.add(ImageIO.read(VRServerGUI.class.getResource("/icon32.png")));
images.add(ImageIO.read(VRServerGUI.class.getResource("/icon48.png")));
images.add(ImageIO.read(VRServerGUI.class.getResource("/icon64.png")));
images.add(ImageIO.read(VRServerGUI.class.getResource("/icon128.png")));
images.add(ImageIO.read(VRServerGUI.class.getResource("/icon256.png")));
setIconImages(images);
if (OperatingSystem.getCurrentPlatform() == OperatingSystem.OSX) {
MacOSX.setIcons(images);
}
} catch (IOException e1) {
e1.printStackTrace();
}
this.server = server;
setDefaultFontSize(config.getZoom());
// All components should be constructed to the current zoom level by
// default
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().setLayout(new BoxLayout(getContentPane(), PAGE_AXIS));
this.trackersList = new TrackersList(server, this);
trackersFiltersGUI = new TrackersFiltersGUI(server, this);
this.skeletonList = new SkeletonList(server, this);
JScrollPane scrollPane = (JScrollPane) add(
new JScrollPane(
pane = new EJBox(PAGE_AXIS),
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
)
);
scrollPane.getVerticalScrollBar().setUnitIncrement(16);
GraphicsConfiguration gc = getGraphicsConfiguration();
Rectangle screenBounds = gc.getBounds();
setMinimumSize(new Dimension(100, 100));
setSize(
Math.min(config.getWidth(), screenBounds.width),
Math.min(config.getHeight(), screenBounds.height)
);
int posx = config.getPosx();
if (posx == -1) {
posx = screenBounds.x + (screenBounds.width - getSize().width) / 2;
config.setPosx(posx);
}
int posy = config.getPosy();
if (posy == -1) {
posy = (screenBounds.height - getSize().height) / 2;
config.setPosy(posy);
}
setLocation(posx, posy);
// Resize and close listeners to save position and size betwen launcher
// starts
addComponentListener(new AbstractComponentListener() {
@Override
public void componentResized(ComponentEvent e) {
saveFrameInfo();
}
@Override
public void componentMoved(ComponentEvent e) {
saveFrameInfo();
}
});
build();
}
private static void processNewZoom(float zoom, Component comp) {
if (comp.isFontSet()) {
Font newFont = new ScalableFont(comp.getFont(), zoom);
comp.setFont(newFont);
}
if (comp instanceof Container cont) {
for (Component child : cont.getComponents())
processNewZoom(zoom, child);
}
}
private static void setDefaultFontSize(float zoom) {
java.util.Enumeration<Object> keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get(key);
if (value instanceof javax.swing.plaf.FontUIResource f) {
javax.swing.plaf.FontUIResource f2 = new javax.swing.plaf.FontUIResource(
f.deriveFont(f.getSize() * zoom)
);
UIManager.put(key, f2);
}
}
}
protected void saveFrameInfo() {
Rectangle b = getBounds();
config.setWidth(b.width);
config.setHeight(b.height);
config.setPosx(b.x);
config.setPosy(b.y);
server.getConfigManager().saveConfig();
}
public void refresh() {
// Pack and display
// pack();
setVisible(true);
java.awt.EventQueue.invokeLater(this::repaint);
}
@AWTThread
private void build() {
pane.removeAll();
pane.add(new EJBoxNoStretch(LINE_AXIS, false, true) {
{
setBorder(new EmptyBorder(i(5)));
add(Box.createHorizontalGlue());
add(resetButton = new JButton("RESET") {
{
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
reset();
}
});
}
});
add(Box.createHorizontalStrut(10));
add(new JButton("Fast Reset") {
{
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
resetFast();
}
});
}
});
add(Box.createHorizontalStrut(10));
add(floorClipButton = new JButton("Toggle Floor Clip") {
{
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
boolean[] state = server.humanPoseProcessor.getLegTweaksState();
setFloorClipEnabled(!state[0]);
}
});
}
});
setFloorClipEnabled(
server
.getConfigManager()
.getVrConfig()
.getSkeleton()
.getToggles()
.get(SkeletonConfigToggles.FLOOR_CLIP.configKey)
);
add(Box.createHorizontalStrut(10));
add(skatingCorrectionButton = new JButton("Toggle Skating Correction") {
{
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
boolean[] state = server.humanPoseProcessor.getLegTweaksState();
setSkatingReductionEnabled(!state[1]);
}
});
}
});
setSkatingReductionEnabled(
server
.getConfigManager()
.getVrConfig()
.getSkeleton()
.getToggles()
.get(SkeletonConfigToggles.SKATING_CORRECTION.configKey)
);
add(Box.createHorizontalGlue());
add(new JButton("Record BVH") {
{
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (!server.getBvhRecorder().isRecording()) {
setText("Stop Recording BVH...");
server.getBvhRecorder().startRecording();
} else {
server.getBvhRecorder().endRecording();
setText("Record BVH");
}
}
});
}
});
add(Box.createHorizontalGlue());
add(
new JButton(
"GUI Zoom (x" + StringUtils.prettyNumber(config.getZoom(), 2) + ")"
) {
{
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
guiZoom();
setText(
"GUI Zoom (x"
+ StringUtils.prettyNumber(config.getZoom(), 2)
+ ")"
);
}
});
}
}
);
add(Box.createHorizontalStrut(10));
add(new JButton("WiFi") {
{
addMouseListener(new MouseInputAdapter() {
@SuppressWarnings("unused")
@Override
public void mouseClicked(MouseEvent e) {
new WiFiWindow(VRServerGUI.this);
}
});
}
});
add(Box.createHorizontalStrut(10));
}
});
pane.add(new EJBox(LINE_AXIS) {
{
setBorder(new EmptyBorder(i(5)));
add(new EJBoxNoStretch(PAGE_AXIS, false, true) {
{
setAlignmentY(TOP_ALIGNMENT);
JLabel l;
add(l = new JLabel("Trackers list"));
l.setFont(l.getFont().deriveFont(Font.BOLD));
l.setAlignmentX(0.5f);
add(trackersList);
add(Box.createVerticalGlue());
}
});
add(new EJBoxNoStretch(PAGE_AXIS, false, true) {
{
setAlignmentY(TOP_ALIGNMENT);
JCheckBox debugCb;
add(debugCb = new JCheckBox("Show debug information"));
debugCb.setSelected(false);
debugCb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
trackersList.setDebug(debugCb.isSelected());
}
});
JLabel l;
add(l = new JLabel("Body proportions"));
l.setFont(l.getFont().deriveFont(Font.BOLD));
l.setAlignmentX(0.5f);
add(new SkeletonConfigGUI(server, VRServerGUI.this));
add(Box.createVerticalStrut(10));
if (server.hasBridge(WindowsNamedPipeBridge.class)) {
WindowsNamedPipeBridge br = server
.getVRBridge(WindowsNamedPipeBridge.class);
add(l = new JLabel("SteamVR Trackers"));
l.setFont(l.getFont().deriveFont(Font.BOLD));
l.setAlignmentX(0.5f);
add(l = new JLabel("Changes may require restart of SteamVR"));
l.setFont(l.getFont().deriveFont(Font.ITALIC));
l.setAlignmentX(0.5f);
add(new EJBagNoStretch(false, true) {
{
JCheckBox waistCb;
add(waistCb = new JCheckBox("Waist"), c(1, 1));
waistCb.setSelected(br.getShareSetting(TrackerRole.WAIST));
waistCb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
server
.queueTask(
() -> br
.changeShareSettings(
TrackerRole.WAIST,
waistCb.isSelected()
)
);
}
});
JCheckBox legsCb;
add(legsCb = new JCheckBox("Feet"), c(2, 1));
legsCb
.setSelected(
br.getShareSetting(TrackerRole.LEFT_FOOT)
&& br.getShareSetting(TrackerRole.RIGHT_FOOT)
);
legsCb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
server.queueTask(() -> {
br
.changeShareSettings(
TrackerRole.LEFT_FOOT,
legsCb.isSelected()
);
br
.changeShareSettings(
TrackerRole.RIGHT_FOOT,
legsCb.isSelected()
);
});
}
});
JCheckBox chestCb;
add(chestCb = new JCheckBox("Chest"), c(1, 2));
chestCb.setSelected(br.getShareSetting(TrackerRole.CHEST));
chestCb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
server
.queueTask(
() -> br
.changeShareSettings(
TrackerRole.CHEST,
chestCb.isSelected()
)
);
}
});
JCheckBox kneesCb;
add(kneesCb = new JCheckBox("Knees"), c(2, 2));
kneesCb
.setSelected(
br.getShareSetting(TrackerRole.LEFT_KNEE)
&& br.getShareSetting(TrackerRole.RIGHT_KNEE)
);
kneesCb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
server.queueTask(() -> {
br
.changeShareSettings(
TrackerRole.LEFT_KNEE,
kneesCb.isSelected()
);
br
.changeShareSettings(
TrackerRole.RIGHT_KNEE,
kneesCb.isSelected()
);
});
}
});
JCheckBox elbowsCb;
add(elbowsCb = new JCheckBox("Elbows"), c(1, 3));
elbowsCb
.setSelected(
br.getShareSetting(TrackerRole.LEFT_ELBOW)
&& br.getShareSetting(TrackerRole.RIGHT_ELBOW)
);
elbowsCb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
server.queueTask(() -> {
br
.changeShareSettings(
TrackerRole.LEFT_ELBOW,
elbowsCb.isSelected()
);
br
.changeShareSettings(
TrackerRole.RIGHT_ELBOW,
elbowsCb.isSelected()
);
});
}
});
JCheckBox handsCb;
add(handsCb = new JCheckBox("Hands"), c(2, 3));
handsCb
.setSelected(
br.getShareSetting(TrackerRole.LEFT_HAND)
&& br.getShareSetting(TrackerRole.RIGHT_HAND)
);
handsCb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
server.queueTask(() -> {
br
.changeShareSettings(
TrackerRole.LEFT_HAND,
handsCb.isSelected()
);
br
.changeShareSettings(
TrackerRole.RIGHT_HAND,
handsCb.isSelected()
);
});
}
});
}
});
add(Box.createVerticalStrut(10));
}
add(l = new JLabel("Trackers filtering"));
l.setFont(l.getFont().deriveFont(Font.BOLD));
l.setAlignmentX(0.5f);
add(trackersFiltersGUI);
add(Box.createVerticalStrut(10));
add(new JLabel("Skeleton data"));
add(skeletonList);
add(Box.createVerticalGlue());
}
});
}
});
pane.add(Box.createVerticalGlue());
refresh();
server.addOnTick(trackersList::updateTrackers);
server.addOnTick(skeletonList::updateBones);
}
// For now only changes font size, but should change fixed components size
// in
// the future too
private void guiZoom() {
if (config.getZoom() <= 1.0f) {
config.setZoom(1.5f);
} else if (config.getZoom() <= 1.5f) {
config.setZoom(1.75f);
} else if (config.getZoom() <= 1.75f) {
config.setZoom(2f);
} else if (config.getZoom() <= 2.0f) {
config.setZoom(2.5f);
} else {
config.setZoom(1f);
}
processNewZoom(config.getZoom() / WindowConfig.INITAL_ZOOM, pane);
refresh();
server.getConfigManager().saveConfig();
}
@AWTThread
private void resetFast() {
server.resetTrackersYaw();
}
@AWTThread
private void reset() {
ButtonTimer.runTimer(resetButton, 3, "RESET", server::resetTrackers);
}
@AWTThread
private void setSkatingReductionEnabled(Boolean value) {
if (value == null)
value = false;
skatingCorrectionButton.setBackground(value ? Color.GREEN : Color.RED);
skatingCorrectionButton
.setText("Skating Correction: " + (value ? "ON" : "OFF"));
server.setSkatingReductionEnabled(value);
}
@AWTThread
private void setFloorClipEnabled(Boolean value) {
if (value == null)
value = false;
floorClipButton.setBackground(value ? Color.GREEN : Color.RED);
// update the button
floorClipButton.setText("Floor clip: " + (value ? "ON" : "OFF"));
server.setFloorClipEnabled(value);
}
}
@@ -0,0 +1,194 @@
package dev.slimevr.gui;
import com.fazecast.jSerialComm.SerialPort;
import dev.slimevr.gui.swing.EJBox;
import dev.slimevr.serial.SerialListener;
import io.eiren.util.ann.AWTThread;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class WiFiWindow extends JFrame implements SerialListener {
private static String savedSSID = "";
private static String savedPassword = "";
private final VRServerGUI gui;
private JScrollPane scroll;
JTextField ssidField;
JPasswordField passwdField;
JTextArea log;
public WiFiWindow(VRServerGUI gui) {
super("WiFi Settings");
this.gui = gui;
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.LINE_AXIS));
this.gui.server.getSerialHandler().addListener(this);
build();
}
@AWTThread
private void build() {
if (!this.gui.server.getSerialHandler().openSerial()) {
JOptionPane
.showMessageDialog(
null,
"Unable to open a serial connection. Check that your drivers are installed and nothing is using the serial port already (like Cura or VScode or another slimeVR server)",
"SlimeVR: Serial connection error",
JOptionPane.ERROR_MESSAGE
);
}
}
@Override
@AWTThread
public void onSerialConnected(SerialPort port) {
Container pane = getContentPane();
pane.add(new EJBox(BoxLayout.PAGE_AXIS) {
{
add(
new JLabel(
"Tracker connected to "
+ port.getSystemPortName()
+ " ("
+ port.getDescriptivePortName()
+ ")"
)
);
add(new EJBox(BoxLayout.LINE_AXIS) {
{
add(new JButton("Reboot Tracker") {
{
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
gui.server.getSerialHandler().rebootRequest();
}
});
}
});
add(new JButton("INFO") {
{
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
gui.server.getSerialHandler().infoRequest();
}
});
}
});
add(new JButton("Factory Reset") {
{
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
gui.server.getSerialHandler().factoryResetRequest();
}
});
}
});
}
});
add(
scroll = new JScrollPane(
log = new JTextArea(10, 20),
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
)
);
log.setLineWrap(true);
scroll.setAutoscrolls(true);
add(new JLabel("Enter WiFi credentials:"));
add(new EJBox(BoxLayout.LINE_AXIS) {
{
add(new JLabel("Network name:"));
add(ssidField = new JTextField(savedSSID));
}
});
add(new EJBox(BoxLayout.LINE_AXIS) {
{
add(new JLabel("Network password:"));
passwdField = new JPasswordField(savedPassword);
passwdField.setEchoChar('\u25cf');
add(passwdField);
add(new JCheckBox("Show Password") {
{
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (isSelected())
passwdField.setEchoChar((char) 0);
else
passwdField.setEchoChar('\u25cf');
}
});
}
});
}
});
add(new JButton("Send") {
{
addMouseListener(new MouseInputAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
savedSSID = ssidField.getText();
savedPassword = new String(passwdField.getPassword());
gui.server.getSerialHandler().setWifi(savedSSID, savedPassword);
}
});
}
});
}
});
pack();
setLocationRelativeTo(null);
setVisible(true);
java.awt.EventQueue.invokeLater(() -> {
toFront();
repaint();
});
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
final WiFiWindow window = this;
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent windowEvent) {
gui.server.getSerialHandler().closeSerial();
dispose();
gui.server.getSerialHandler().removeListener(window);
}
});
}
@Override
@AWTThread
public void onSerialDisconnected() {
if (this.log == null)
return;
log.append("[SERVER] Serial port disconnected\n");
}
@Override
@AWTThread
public void onSerialLog(String str) {
if (this.log == null)
return;
log.append(str);
// log.setAutoscrolls(true);
if (scroll != null) {
JScrollBar vertical = scroll.getVerticalScrollBar();
if ((vertical.getValue() + str.length() + 200) > vertical.getMaximum()) {
vertical.setValue(vertical.getMaximum());
}
}
}
}
@@ -0,0 +1,51 @@
package dev.slimevr.gui.swing;
import javax.swing.*;
import java.util.Timer;
import java.util.TimerTask;
public class ButtonTimer {
private static final Timer timer = new Timer();
public static void runTimer(
AbstractButton button,
int seconds,
String defaultText,
Runnable runnable
) {
if (seconds <= 0) {
button.setText(defaultText);
runnable.run();
} else {
button.setText(String.valueOf(seconds));
timer.schedule(new ButtonTimerTask(button, seconds - 1, defaultText, runnable), 1000);
}
}
private static class ButtonTimerTask extends TimerTask {
private final AbstractButton button;
private final int seconds;
private final String defaultText;
private final Runnable runnable;
private ButtonTimerTask(
AbstractButton button,
int seconds,
String defaultText,
Runnable runnable
) {
this.button = button;
this.seconds = seconds;
this.defaultText = defaultText;
this.runnable = runnable;
}
@Override
public void run() {
runTimer(button, seconds, defaultText, runnable);
}
}
}
@@ -0,0 +1,11 @@
package dev.slimevr.gui.swing;
import java.awt.*;
public class EJBag extends EJPanel {
public EJBag() {
super(new GridBagLayout());
}
}
@@ -0,0 +1,32 @@
package dev.slimevr.gui.swing;
import java.awt.*;
public class EJBagNoStretch extends EJPanel {
public EJBagNoStretch(boolean stretchVertical, boolean stretchHorizontal) {
super(new EGridBagLayoutNoStretch(stretchVertical, stretchHorizontal));
}
private static class EGridBagLayoutNoStretch extends GridBagLayout {
private final boolean stretchVertical;
private final boolean stretchHorizontal;
public EGridBagLayoutNoStretch(boolean stretchVertical, boolean stretchHorizontal) {
this.stretchVertical = stretchVertical;
this.stretchHorizontal = stretchHorizontal;
}
@Override
public Dimension maximumLayoutSize(Container target) {
Dimension pref = preferredLayoutSize(target);
if (stretchVertical)
pref.height = Integer.MAX_VALUE;
if (stretchHorizontal)
pref.width = Integer.MAX_VALUE;
return pref;
}
}
}
@@ -0,0 +1,12 @@
package dev.slimevr.gui.swing;
import javax.swing.*;
public class EJBox extends EJPanel {
public EJBox(int layout) {
super();
setLayout(new BoxLayout(this, layout));
}
}
@@ -0,0 +1,40 @@
package dev.slimevr.gui.swing;
import javax.swing.*;
import java.awt.*;
public class EJBoxNoStretch extends EJPanel {
public EJBoxNoStretch(int layout, boolean stretchVertical, boolean stretchHorizontal) {
super();
setLayout(new BoxLayoutNoStretch(this, layout, stretchVertical, stretchHorizontal));
}
private static class BoxLayoutNoStretch extends BoxLayout {
private final boolean stretchVertical;
private final boolean stretchHorizontal;
public BoxLayoutNoStretch(
Container target,
int axis,
boolean stretchVertical,
boolean stretchHorizontal
) {
super(target, axis);
this.stretchVertical = stretchVertical;
this.stretchHorizontal = stretchHorizontal;
}
@Override
public Dimension maximumLayoutSize(Container target) {
Dimension pref = preferredLayoutSize(target);
if (stretchVertical)
pref.height = Integer.MAX_VALUE;
if (stretchHorizontal)
pref.width = Integer.MAX_VALUE;
return pref;
}
}
}
@@ -0,0 +1,105 @@
package dev.slimevr.gui.swing;
import javax.swing.*;
import java.awt.*;
public abstract class EJPanel extends JPanel {
public static boolean NEEDS_DOWNSCALE = false;
public static float DOWNSCALE_FACTOR = 0.75f;
public EJPanel() {
super();
}
public EJPanel(LayoutManager manager) {
super(manager);
}
public static void s(Component c, int width, int height) {
if (NEEDS_DOWNSCALE) {
width = (int) Math.ceil(width * DOWNSCALE_FACTOR);
height = (int) Math.ceil(height * DOWNSCALE_FACTOR);
}
c.setSize(width, height);
Dimension d = new Dimension(width, height);
c.setPreferredSize(d);
c.setMaximumSize(d);
c.setMinimumSize(d);
}
public static void minWidth(Component c, int width, int height) {
if (NEEDS_DOWNSCALE) {
height = (int) Math.ceil(height * DOWNSCALE_FACTOR);
width = (int) Math.ceil(width * DOWNSCALE_FACTOR);
}
c.setPreferredSize(new Dimension(Short.MAX_VALUE, height));
c.setMaximumSize(new Dimension(Short.MAX_VALUE, height));
c.setMinimumSize(new Dimension(width, height));
}
public static void minHeight(Component c, int width, int height) {
if (NEEDS_DOWNSCALE) {
height = (int) Math.ceil(height * DOWNSCALE_FACTOR);
width = (int) Math.ceil(width * DOWNSCALE_FACTOR);
}
c.setPreferredSize(new Dimension(width, Short.MAX_VALUE));
c.setMaximumSize(new Dimension(width, Short.MAX_VALUE));
c.setMinimumSize(new Dimension(width, height));
}
public static GridBagConstraints c(int x, int y) {
GridBagConstraints c = new GridBagConstraints();
c.gridx = x;
c.gridy = y;
return c;
}
public static GridBagConstraints c(int x, int y, int padding) {
GridBagConstraints c = new GridBagConstraints();
c.gridx = x;
c.gridy = y;
c.insets = new Insets(padding, padding, padding, padding);
return c;
}
public static GridBagConstraints c(int x, int y, int padding, int anchor) {
GridBagConstraints c = new GridBagConstraints();
c.gridx = x;
c.gridy = y;
c.insets = new Insets(padding, padding, padding, padding);
c.anchor = anchor;
return c;
}
public static GridBagConstraints c(int x, int y, Insets insets) {
GridBagConstraints c = new GridBagConstraints();
c.gridx = x;
c.gridy = y;
c.insets = insets;
return c;
}
public static GridBagConstraints s(GridBagConstraints c, int gridwidth, int gridheight) {
c.gridwidth = gridwidth;
c.gridheight = gridheight;
return c;
}
public static Insets i(int s) {
return new Insets(s, s, s, s);
}
public static Insets i(int h, int v) {
return new Insets(v, h, v, h);
}
public static Component padding(int width, int height) {
return Box.createRigidArea(new Dimension(width, height));
}
public static int fontSize(int baseSize) {
return NEEDS_DOWNSCALE ? (int) Math.ceil(baseSize * DOWNSCALE_FACTOR) : baseSize;
}
}
@@ -0,0 +1,8 @@
package dev.slimevr.gui.swing;
import javax.swing.*;
public class EJlabel extends JLabel {
}