AGX Dynamics 2.38.0.2
Loading...
Searching...
No Matches
ExampleApplicationController.h
Go to the documentation of this file.
1/*
2Copyright 2007-2024. Algoryx Simulation AB.
3
4All AGX source code, intellectual property, documentation, sample code,
5tutorials, scene files and technical white papers, are copyrighted, proprietary
6and confidential material of Algoryx Simulation AB. You may not download, read,
7store, distribute, publish, copy or otherwise disseminate, use or expose this
8material unless having a written signed agreement with Algoryx Simulation AB, or
9having been advised so by Algoryx Simulation AB for a time limited evaluation,
10or having purchased a valid commercial license from Algoryx Simulation AB.
11
12Algoryx Simulation AB disclaims all responsibilities for loss or damage caused
13from using this software, unless otherwise stated in written agreements with
14Algoryx Simulation AB.
15*/
16
17#ifndef AGXOSG_EXAMPLEAPPLICATIONCONTROLLER_H
18#define AGXOSG_EXAMPLEAPPLICATIONCONTROLLER_H
19
20#include <agx/config/AGX_USE_WEBSOCKETS.h>
21#include <agx/config/AGX_USE_WEBPLOT.h>
22
23#include <agxOSG/PickHandler.h>
24#include <agxOSG/VideoStream.h>
25#include <agx/Component.h>
26#include <agx/Journal.h>
27#include <agx/JournalReader.h>
28#include <agxNet/Socket.h>
29#include <agxNet/WebSocket.h>
30#include <agxNet/PortRange.h>
32#include <agxSDK/PickHandler.h>
33
34#include <agxPlot/System.h>
35
36#include <agx/PushDisableWarnings.h> // Disabling warnings. Include agx/PopDisableWarnings.h below!
37#include <osg/Geometry>
38#include <osg/PositionAttitudeTransform>
39#include <osg/LineWidth>
40#include <osgViewer/Viewer>
41#include <osg/ShapeDrawable>
42#include <agx/PopDisableWarnings.h> // End of disabled warnings.
43
44#include <agxData/BinaryData.h>
45
47#include <agxCollide/Trimesh.h>
48#include <queue>
49#include <agxCallable/CallableAccessor.h>
50
51#if AGX_USE_WEBSOCKETS()
52
53
54namespace agxOSG
55{
56 class ExampleApplication;
57
58 AGX_DECLARE_POINTER_TYPES(ExampleApplicationController);
59 class AGXOSG_EXPORT ExampleApplicationController : public agx::Component
60 {
61 private:
62 AGX_DECLARE_POINTER_TYPES(ControlChannelTCP);
63
64 public:
65 ExampleApplicationController(ExampleApplication *application);
66
67 void signalAutoStepping(bool flag);
68 void pushParameters();
69 void pushFrame();
70 void setEnableTickSignals(bool flag);
71 bool update(agx::Real timeoutMs = 0);
72 void signalRefresh();
73 void updateMouseSpringRenderer();
74
75 void signalJournalPlayback(agx::Journal *journal);
76 void signalJournalRecord(agx::Journal *journal);
77
79 bool needSceneLoading();
80 void performSceneLoading();
81
82 struct RenderFrame;
83 void updateRemoteViewers(const RenderFrame& frame);
84
85 void setOrbitCamera(agxCollide::Geometry* geometry, const agx::Vec3& eye, const agx::Vec3& center, const agx::Vec3& up, int trackerMode);
86
87 void init(const agx::String& token = "", agxNet::PortRangeRef portRange = nullptr);
88
89#if AGX_USE_WEBPLOT()
90 void initPlotCallbacks();
91#endif
92
93 void initDjangoSocket(const agx::String& address, const agx::String& token);
94 void initRemoteConnection();
95
96 agxNet::WebSocket::ControlChannel *getControlChannel();
97
98 protected:
99 virtual ~ExampleApplicationController();
100
101 private:
102 bool httpGetCurrentState(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
103 bool httpStartSimulation(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
104 bool httpStopSimulation(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
105 bool httpStepForward(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
106 bool httpStepBackward(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
107 bool httpLoadScene(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
108
109 bool httpListJournals(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
110
111 bool httpAddJournalBinding(agxIO::RemoteCommandServer* server, mg_connection* connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
112 bool httpRemoveJournalBinding(agxIO::RemoteCommandServer* server, mg_connection* connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
113 bool httpListJournalBindings(agxIO::RemoteCommandServer* server, mg_connection* connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
114 bool httpSaveCurrentJournalBindings(agxIO::RemoteCommandServer* server, mg_connection* connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
115
116 bool httpEnableRecording(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
117 bool httpDisableRecording(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
118
119 bool httpLoadJournal(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
120 bool httpUnloadJournal(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
121
122
123#if AGX_USE_WEBSOCKETS()
124 void webSocketClientConnected(agxNet::WebSocket* client);
125 void webSocketClientDisconnected(agxNet::WebSocket* client);
126#endif
127
128 void simulationTickCallback(agx::Clock *clock);
129
130
131 bool httpEnablePlaybackLoop(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
132 bool httpDisablePlaybackLoop(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
133
134 bool httpEnableRealTimeSync(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
135 bool httpDisableRealTimeSync(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
136
137 bool httpSetPlaybackPosition(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
138
139 bool httpAttachVideoStream(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
140// bool httpAttachRemoteViewer(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
141// bool httpAttachRemoteViewerSlave(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
142
143 bool httpAttachRemoteSolver(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
144 bool httpDetachRemoteSolver(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
145 bool httpAttachStatisticsViewer(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
146 bool httpGetControlChannel(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
147
148 bool httpGetRemoteViewChannel(agxIO::RemoteCommandServer *server, mg_connection *connection, const agxIO::RemoteCommandServer::QueryArgumentTable& arguments);
149
150 void buildStateMessage(agxJson::Value& eRoot);
151
152 #if AGX_USE_WEBSOCKETS()
153 void ccGetScene(ControlChannelTCP *channel, agxNet::TCPSocket *socket, agxNet::StructuredMessage *message);
154 void ccSetScene(ControlChannelTCP *channel, agxNet::TCPSocket *socket, agxNet::StructuredMessage *message);
155 void ccAttachRemoteViewer(agxNet::WebSocket::ControlChannel *channel, agxNet::WebSocket *socket, agxNet::StructuredMessage *message);
156 void ccRegisterUser(agxNet::WebSocket::ControlChannel *channel, agxNet::WebSocket *socket, agxNet::StructuredMessage *message);
157 void ccRegisterAttributeListener(agxNet::WebSocket::ControlChannel *channel, agxNet::WebSocket *socket, agxNet::StructuredMessage *message);
158 void ccUnregisterAttributeListener(agxNet::WebSocket::ControlChannel *channel, agxNet::WebSocket *socket, agxNet::StructuredMessage *message);
159 void ccRegisterCallableDataStream(agxNet::WebSocket::ControlChannel *channel, agxNet::WebSocket *socket, agxNet::StructuredMessage *message);
160 void ccFunctionCall(agxNet::WebSocket::ControlChannel *channel, agxNet::WebSocket *socket, agxNet::StructuredMessage *message);
161 void ccHeartbeat(agxNet::WebSocket::ControlChannel *channel, agxNet::WebSocket *socket, agxNet::StructuredMessage *message);
162 void ccEnableStructureSynchronization(agxNet::WebSocket::ControlChannel *channel, agxNet::WebSocket *socket, agxNet::StructuredMessage *message);
163 void ccGetTreeStructure(agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket, agxNet::StructuredMessage* message);
164 void ccGetTrimeshData(agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket, agxNet::StructuredMessage* message);
165 void ccGetShapeRenderData(agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket, agxNet::StructuredMessage* message);
166 void ccGetState(agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket, agxNet::StructuredMessage* message);
167 void ccExitApplication(agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket, agxNet::StructuredMessage* message);
168 void ccReloadScene(agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket, agxNet::StructuredMessage* message);
169 void ccLoadSceneCallback(agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket, agxNet::StructuredMessage* message, std::function<void ()> callback);
170 void onSceneLoad(agxNet::WebSocket* socket, agxNet::StructuredMessage* message, agxNet::StructuredMessage* response,
171std::function<void ()> callback);
172 void ccLoadScene(agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket, agxNet::StructuredMessage* message);
173 void ccKeyDown(agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket, agxNet::StructuredMessage* message);
174 void ccKeyUp(agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket, agxNet::StructuredMessage* message);
175 void ccMousePickStart(agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket, agxNet::StructuredMessage* message);
176 void ccMousePickDrag(agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket, agxNet::StructuredMessage* message);
177 void ccMousePickEnd(agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket, agxNet::StructuredMessage* message);
178 void ccPlay(agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket, agxNet::StructuredMessage* message);
179 void ccPause(agxNet::WebSocket::ControlChannel* channel, agxNet::WebSocket* socket, agxNet::StructuredMessage* message);
180
181 void registerPort(agx::UInt16 port, const agx::String& portName);
182 void unregisterPort(agx::UInt16 port, const agx::String& portName);
183 void djangoMessage(agxNet::WebSocket *, agx::UInt8* data, size_t numBytes);
184
185
186 void getConstraintData(agx::Constraint *constraint, agxJson::Value& eConstraint);
187 void getRigidBodyData(agx::RigidBody *body, agxJson::Value& eBody);
188
189 agxJson::Value& createArrayElement( agxJson::Value& eParent, const char* groupName );
190
191 AGX_DECLARE_POINTER_TYPES(StructureSynchronization);
192 class StructureSynchronization : public agx::Referenced
193 {
194 public:
195 StructureSynchronization(agx::Component *root);
196
197 void addSocket(agxNet::WebSocket *socket);
198
199 protected:
200 virtual ~StructureSynchronization();
201
202 private:
203 void addCallback(agx::Component *parent, agx::Object *child);
204 void removeCallback(agx::Component *parent, agx::Object *child);
205
206 agxNet::StructuredMessage *buildMessage(agx::Component *root);
207
208 private:
212 agxNet::WebSocketRefVector m_sockets;
213 };
214
215 typedef agx::HashTable<agx::Component *, StructureSynchronizationRef> StructureSynchronizationTable;
216 StructureSynchronizationTable m_structureSynchronizationTable;
217 #endif
218
219 private:
220 AGX_DECLARE_POINTER_TYPES(MouseSpringRenderer);
221 class MouseSpringRenderer : public agxData::FrameWriter
222 {
223 public:
224 MouseSpringRenderer(ExampleApplication *application);
225
226 void frameCallback(agxData::Frame *frame);
227 virtual void writeFrame(const agxData::Frame *frame) override;
228 virtual void endOfStream() override;
229
230 // Blah, hack
231 void update();
232
233 agxData::Track::FrameEvent::CallbackType *getFrameCallback() { return &m_frameCallback; }
234 protected:
235 virtual ~MouseSpringRenderer();
236
237 private:
238 bool init();
239
240 private:
241 // osgViewer::Viewer *m_viewer;
242 ExampleApplication *m_application;
243 osg::PositionAttitudeTransform *m_mouseAttachTransform;
244 osg::PositionAttitudeTransform *m_mousePositionTransform;
245 osg::Geometry *m_mouseSpringLine;
246 osg::ref_ptr< osg::Switch > m_mouseSpringSwitch;
247 agxData::FrameConstRef m_frame;
249 };
250
251 AGX_DECLARE_POINTER_TYPES(RemoteViewerThread);
252
253
254 private:
255 struct OrbitCamera
256 {
257 OrbitCamera() : enabled(false), mode(0) {}
258 OrbitCamera(agxCollide::Geometry *g, agx::Vec3 e, agx::Vec3 c, agx::Vec3 u, int m) : enabled(true), mode(m), geometry(g), eye(e), center(c), up(u) {}
259
260 bool enabled;
261 int mode;
262 agxCollide::Geometry *geometry;
263 agx::Vec3 eye;
264 agx::Vec3 center;
265 agx::Vec3 up;
266 };
267 OrbitCamera m_orbitCamera;
268
269 ExampleApplication *m_application;
270 bool m_initialized;
271 // agx::JournalRef m_journal;
272 agx::Clock::TickEvent::CallbackType m_simulationTickCallback;
273 bool m_enableTickCallback;
274 MouseSpringRendererRef m_mouseSpringRenderer;
275 agx::Timer m_rtTimer;
276 agx::Real m_rtSmoothedRatio;
277 agxData::TrackRef m_remoteViewerTrack;
278 agx::UInt16 m_remoteViewerPort;
279 bool m_remoteSimulationReceived;
280 std::string loadSceneFormat;
281 agx::Timer m_interactiveClientHeartbeatTimer;
282 agx::Real m_interactiveClientHeartbeatTimeOut;
283
284 RemoteViewerThreadRef m_remoteViewerThread;
285 agxNet::PortRangeRef m_portRange;
286
287
288
290 bool m_needSceneLoading;
291 bool m_hasLooping;
292
293
294 class ControlChannelTCP : public Referenced
295 {
296 public:
297 ControlChannelTCP(ExampleApplicationController *controller, agx::UInt16 port);
298
299 agx::UInt16 getPort() const;
300
301 agxNet::TCPSocket *createConnection(const agx::String& address, agx::UInt16 port);
302
303 bool service();
304
306
307 void registerMessageHandler(const agx::String& uri, MessageHandler callback);
308
309 protected:
310 virtual ~ControlChannelTCP();
311
312 private:
313 void receiveMessage(agxNet::TCPSocket *socket, const agxNet::StructuredMessage::PreHeader& preHeader);
314
315 private:
316 agx::UInt16 m_port;
317 agxNet::TCPServerSocketRef m_serverSocket;
318 agxNet::TCPSocketRefVector m_clientSockets;
319
320 typedef agx::HashTable<agx::String, MessageHandler> MessageHandlerTable;
321 MessageHandlerTable m_messageHandlerTable;
322 };
323
324
325 bool m_setupComplete;
326
327 #if AGX_USE_WEBSOCKETS()
328 agxNet::WebSocket::ControlChannelRef m_controlChannel;
329 agxNet::WebSocketRef m_djangoSocket;
330 void controlChannelSocketConnectedCallback(agxNet::WebSocket::ControlChannel *channel, agxNet::WebSocket *socket);
331 void controlChannelSocketDisconnectedCallback(agxNet::WebSocket::ControlChannel *channel, agxNet::WebSocket *socket);
332 agxNet::WebSocket::ControlChannel::SocketEvent::CallbackType m_controlChannelSocketConnectedCallback;
333 agxNet::WebSocket::ControlChannel::SocketEvent::CallbackType m_controlChannelSocketDisconnectedCallback;
334
335#if AGX_USE_WEBPLOT()
336 void plotSystemOutputAddedCallback(agxPlot::Output* output);
337 agxPlot::System::OutputAddedEvent::CallbackType m_plotSystemOutputAddedCallback;
338#endif
339
340 struct UserData
341 {
342 agxSDK::PickHandlerRef pickHandler;
343 agx::UInt64 id;
344 agxJson::Value data;
345 agx::Real pickDistance;
346 };
347
348 UserData& getUserData(agxNet::WebSocket *);
349
351 UserTable m_userTable;
352
353 typedef std::queue<agxNet::StructuredMessageRef> FrameMessageQueue;
354 FrameMessageQueue m_frameMessageQueue;
355 #endif
356
357 ControlChannelTCPRef m_controlChannelTCP;
358 agx::JournalReaderRef m_journalReader;
359
360#if AGX_USE_FFMPEG()
361 VideoStreamRef m_videoStream;
362#endif
363
364 agx::RigidBodyRefVector m_monitoredBodies;
365 agx::ConstraintRefVector m_monitoredConstraints;
366 bool m_djangoProxyResponse;
367 agxCallable::CallableAccessorRefVector m_dataStreamCallables;
368 agx::Callback m_sceneLoadCallback;
369 };
370
371 struct ExampleApplicationController::RenderFrame
372 {
373 osg::ref_ptr<osg::Image> image;
374 agx::UInt index;
375 agx::DateRef date;
376 };
377
378 class ExampleApplicationController::RemoteViewerThread : public agx::BasicThread, public agx::Referenced
379 {
380 public:
381 RemoteViewerThread(ExampleApplication *application);
382
383 void stop();
384
385 void pushFrame(const RenderFrame& frame);
386
387 agx::UInt16 getPort();
388
389 protected:
390 virtual ~RemoteViewerThread();
391
392 private:
393 virtual void run() override;
394
395 void connectCallback(agxNet::WebSocket *client);
396 void disconnectCallback(agxNet::WebSocket *client);
397 void messageReceiveCallback(agxNet::WebSocket *, agx::UInt8 *data, size_t numBytes);
398 void updatePickHandlers();
399
400 private:
401 agxNet::WebSocketServerRef m_serverSocket;
402 bool m_running;
403 agx::Condition m_condition;
404 agx::Mutex m_mutex;
405 RenderFrame m_currentFrame;
406 ExampleApplication *m_application;
407
409 PickHandlerTable m_pickHandlerTable;
410
412 };
413
414}
415
416#endif
417
418#endif /* AGXOSG_EXAMPLEAPPLICATIONCONTROLLER_H */
#define AGX_DECLARE_POINTER_TYPES(type)
Definition Referenced.h:254
#define AGXOSG_EXPORT
The geometry representation used by the collision detection engine.
Definition Geometry.h:92
The FrameWriter writes frames to an external target.
Definition FrameIO.h:169
THis class wraps the description of data that should be plotted.
Definition Output.h:35
Basic wrapper class aroud std::thread.
Definition Thread.h:83
Templated callback with three arguments.
Definition Callback.h:182
Generalized callback, using std::function.
Definition Callback.h:54
Clock class keeps representation of virtual/simulated time.
Definition Clock.h:38
A component is an object containing other objects, enabling hierarchical structuring.
Definition Component.h:39
The base class for a constraint.
Definition Constraint.h:89
T CallbackType
Definition Event.h:37
Inheritance with partial specialization due to bug with ref_ptr containers.
agx::Object is a refcounted object with a name.
Definition Object.h:59
Base class providing referencing counted objects.
Definition Referenced.h:120
The rigid body class, combining a geometric model and a frame of reference.
Definition RigidBody.h:52
The Timer class permits timing execution speed with the same refinement as the built in hardware cloc...
Definition Timer.h:75
Smart pointer for observed objects, that automatically set pointers to them to null when they deleted...
Smart pointer for handling referenced counted objects.
Definition ref_ptr.h:30
The agxOSG namespace provides functionality for visualizing AGX simulations with OpenSceneGraph.
AGXOSG_EXPORT bool setOrbitCamera(osgViewer::Viewer *viewer, osg::Group *node, const agx::Vec3 &eye, const agx::Vec3 &center, const agx::Vec3 &up, int trackerMode)
uint16_t UInt16
Definition Integer.h:31
std::condition_variable Condition
std::mutex Mutex
Definition Referenced.h:99
uint64_t UInt64
Definition Integer.h:33
uint64_t UInt
Definition Integer.h:27
double Real
Definition Real.h:42
uint8_t UInt8
Definition Integer.h:30
void AGXPHYSICS_EXPORT init()
Initialize AGX Dynamics API including thread resources and must be executed before using the AGX API.