Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
REveScene.cxx
Go to the documentation of this file.
1// @(#)root/eve7:$Id$
2// Authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007, 2018
3
4/*************************************************************************
5 * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
6 * All rights reserved. *
7 * *
8 * For the licensing terms see $ROOTSYS/LICENSE. *
9 * For the list of contributors see $ROOTSYS/README/CREDITS. *
10 *************************************************************************/
11
12#include <ROOT/REveScene.hxx>
13#include <ROOT/REveViewer.hxx>
14#include <ROOT/REveManager.hxx>
15#include <ROOT/REveTrans.hxx>
17#include <ROOT/REveClient.hxx>
18#include <ROOT/REveUtil.hxx>
19#include <ROOT/RWebWindow.hxx>
20
21#include <cassert>
22#include <map>
23#include <set>
24#include <string>
25
26#include <nlohmann/json.hpp>
27
28using namespace ROOT::Experimental;
29namespace REX = ROOT::Experimental;
30
31/** \class REveScene
32\ingroup REve
33Eve representation of TGLScene.
34The GLScene is owned by this class - it is created on construction
35time and deleted at destruction.
36
37Normally all objects are positioned directly in global scene-space.
38By setting the fHierarchical flag, positions of children get
39calculated by multiplying the transformation matrices of all parents.
40*/
41
42////////////////////////////////////////////////////////////////////////////////
43/// Constructor.
44
45REveScene::REveScene(const std::string& n, const std::string& t) :
46 REveElement(n, t)
47{
48 fScene = this;
49}
50
51////////////////////////////////////////////////////////////////////////////////
52/// Destructor.
53
61//------------------------------------------------------------------------------
62
63int REveScene::WriteCoreJson(nlohmann::json &j, Int_t rnr_offset)
64{
65 j["Mandatory"] = fMandatory;
66 j["IsOverlay"] = fIsOverlay;
67
68 return REveElement::WriteCoreJson(j, rnr_offset);
69}
70
71//------------------------------------------------------------------------------
72
73void REveScene::AddSubscriber(std::unique_ptr<REveClient> &&sub)
74{
75 assert(sub.get() != nullptr && fAcceptingChanges == kFALSE);
76
77 fSubscribers.emplace_back(std::move(sub));
78
79 // XXX Here should send out the package to the new subscriber,
80 // In principle can expect a new one in short time?
81 // Keep streamed data until next begin change, maybe.
82}
83
85{
86 auto pred = [&](std::unique_ptr<REveClient> &client) {
87 return client->fId == id;
88 };
89
90 fSubscribers.erase(std::remove_if(fSubscribers.begin(), fSubscribers.end(), pred), fSubscribers.end());
91}
92
93// Add Button in client gui with this command
94void REveScene::AddCommand(const std::string &name, const std::string &icon, const REveElement *element, const std::string &action)
95{
96 static const REveException eh("REveScene::AddCommand ");
97 if (element->GetElementId() && element->IsA())
98 {
99 fCommands.emplace_back(name, icon, element, action);
100 }
101 else
102 {
103 throw eh + "Element id and dictionary has to be defined";
104 }
105}
106
108{
109 if (fAcceptingChanges) return;
110
111 if (HasSubscribers()) {
113 /*
114 for (auto &&client : fSubscribers) {
115 REX::gEve->SceneSubscriberProcessingChanges(client->fId);
116 }
117 */
118 }
119}
120
122{
123 assert(fAcceptingChanges);
124
125 fChangedElements.push_back(element);
126}
127
129{
130 fRemovedElements.push_back(id);
131}
132
134{
135 if ( ! fAcceptingChanges) return;
136
138}
139
141{
142 fOutputJson.clear();
143 fOutputBinary.clear();
144
145 fElsWithBinaryData.clear();
147
148 nlohmann::json jarr = nlohmann::json::array();
149
150 nlohmann::json jhdr = {};
151 jhdr["content"] = "REveScene::StreamElements";
152 jhdr["fSceneId"] = fElementId;
153
154 if (!fCommands.empty()) {
155 jhdr["commands"] = nlohmann::json::array();
156 for (auto &&cmd : fCommands) {
157 nlohmann::json jcmd = {};
158 jcmd["name"] = cmd.fName;
159 jcmd["icon"] = cmd.fIcon;
160 jcmd["elementid"] = cmd.fElementId;
161 jcmd["elementclass"] = cmd.fElementClass;
162 jcmd["func"] = cmd.fAction; // SL: may be not needed on client side, can use name
163 jhdr["commands"].push_back(jcmd);
164 }
165 }
166
167 jarr.push_back(jhdr);
168
169 StreamJsonRecurse(this, jarr);
170 // for (auto &c : fChildren)
171 // {
172 // StreamJsonRecurse(c, jarr);
173 // }
174
176 Int_t off = 0;
177
178 for (auto &&e : fElsWithBinaryData)
179 {
180 auto rd_size = e->fRenderData->Write(&fOutputBinary[off], fOutputBinary.size() - off);
181 off += rd_size;
182 }
183 assert(off == fTotalBinarySize);
184
185 jarr.front()["fTotalBinarySize"] = fTotalBinarySize;
186
187 fOutputJson = jarr.dump();
188 REveUtil::AppendServerTime(fOutputJson); // stamped again just before each send
189}
190
191void REveScene::StreamJsonRecurse(REveElement *el, nlohmann::json &jarr)
192{
193 nlohmann::json jobj = {};
194 Int_t rd_size = el->WriteCoreJson(jobj, fTotalBinarySize);
195 jarr.push_back(jobj);
196
197 // If this is another scene, do not stream additional details.
198 // It should be requested / subscribed to independently.
199
200 if (el->fScene == el && el != this)
201 {
202 return;
203 }
204
205 if (rd_size > 0)
206 {
207 assert(rd_size % REveRenderData::kAlign == 0);
208
209 fTotalBinarySize += rd_size;
210 fElsWithBinaryData.push_back(el);
211 }
212
213 for (auto &&c : el->fChildren)
214 {
215 // Stream only objects element el is a mother of.
216 //
217 // XXXX This is spooky side effect of multi-parenting.
218 //
219 // In particular screwed up for selection.
220 // Selection now streams element ids and implied selected ids
221 // and secondary-ids as part of core json.
222 //
223 // I wonder how this screws up REveProjectionManager (should
224 // we hold a map of already streamed ids?).
225 //
226 // Do uncles and aunts and figure out a clean way for backrefs.
227
228 if (c->GetMother() == el)
229 {
230 StreamJsonRecurse(c, jarr);
231 }
232 }
233}
234
235////////////////////////////////////////////////////////////////////////////////
236/// Move every element whose only pending change is kCBTrans from the change
237/// list into `arr`, for REveManager::SendMotionChanges(). The remaining
238/// elements are streamed as ordinary, acknowledged scene changes.
239
240void REveScene::StreamMotionChanges(nlohmann::json &arr)
241{
242 if (fChangedElements.empty())
243 return;
244
245 List_t keep;
246
247 for (auto &el : fChangedElements) {
248 if (el->GetChangeBits() != REveElement::kCBTrans) {
249 keep.push_back(el);
250 continue;
251 }
252
253 nlohmann::json jobj = {};
254 // clang-format off
255 jobj["fElementId"] = el->GetElementId();
256 jobj["fSceneId"] = GetElementId();
257 // clang-format on
258 el->WriteTransJson(jobj);
259 arr.push_back(jobj);
260
261 el->ClearStamps();
262 }
263
264 fChangedElements.swap(keep);
265}
266
267////////////////////////////////////////////////////////////////////////////////
268//
269/// Prepare data for sending element changes
270//
271////////////////////////////////////////////////////////////////////////////////
272
274{
276
277 nlohmann::json jarr = nlohmann::json::array();
278
279 nlohmann::json jhdr = {};
280 jhdr["content"] = "ElementsRepresentaionChanges";
281 jhdr["fSceneId"] = fElementId;
282
283 jhdr["removedElements"] = nlohmann::json::array();
284 for (auto &re : fRemovedElements)
285 jhdr["removedElements"].push_back(re);
286
287 jhdr["numRepresentationChanged"] = fChangedElements.size();
288
289 // The blocks of the binary message, in the order of their offsets: the
290 // whole render data of an element, or, for kCBRenderEntries, the entries
291 // named in the set.
292 struct Block {
293 REveElement *fEl;
294 bool fFull;
295 std::set<std::string> fTags;
296 };
297 std::vector<Block> blocks;
298
299 auto writeFull = [&](REveElement *el, nlohmann::json &jobj) {
300 Int_t rd_size = el->WriteCoreJson(jobj, fTotalBinarySize);
301 if (rd_size) {
302 assert(rd_size % REveRenderData::kAlign == 0);
303 fTotalBinarySize += rd_size;
304 blocks.push_back({el, true, {}});
305 }
306 };
307
308 // kCBRenderEntries: the stamped entries, rebuilt, described and reserved.
309 // Returns false when their shapes changed or the element has no render
310 // data yet, and the element needs a full update instead.
311 auto writeEntries = [&](REveElement *el, nlohmann::json &jobj) -> bool {
312 const auto &tags = el->GetChangedEntryTags();
313 const REveRenderData *old_rd = el->GetRenderData();
314 if (!old_rd)
315 return false;
316 // The shape of an entry, see REveElement::BuildRenderEntries(). While it
317 // holds, the client keeps the entry's texture or attribute and replaces
318 // the contents only.
319 struct Shape {
321 int fItemSize;
322 size_t fNElements;
323 size_t fBytes;
325 int fW, fH;
326 std::vector<std::pair<UInt_t, UInt_t>> fRanges;
327 bool operator==(const Shape &o) const
328 {
329 return fType == o.fType && fItemSize == o.fItemSize && fNElements == o.fNElements && fBytes == o.fBytes &&
330 fTex == o.fTex && fW == o.fW && fH == o.fH && fRanges == o.fRanges;
331 }
332 };
333 auto shapes = [&](const REveRenderData *rd) {
334 std::map<std::string, Shape> m;
335 for (auto &t : tags)
336 if (auto e = rd->Find(t))
337 m[t] = {e->GetType(), e->GetItemSize(), e->NElements(), e->Bytes(),
338 e->GetTexFormat(), e->GetTexW(), e->GetTexH(), e->RefRanges()};
339 return m;
340 };
341 const auto before = shapes(old_rd);
342 const std::string rnr_func = old_rd->GetRnrFunc();
343 el->BuildRenderEntries(tags);
344 const REveRenderData *rd = el->GetRenderData();
345 if (!rd || rd->GetRnrFunc() != rnr_func || shapes(rd) != before)
346 return false;
347
348 nlohmann::json jrd = {};
349 jrd["rnr_offset"] = fTotalBinarySize;
350 jrd["rnr_func"] = rd->GetRnrFunc();
351 rd->WriteJson(jrd, tags);
352 jobj["render_data"] = jrd;
353
354 Int_t rd_size = rd->GetBinarySize(tags);
355 if (rd_size) {
356 assert(rd_size % REveRenderData::kAlign == 0);
357 fTotalBinarySize += rd_size;
358 blocks.push_back({el, false, tags});
359 }
360 return true;
361 };
362
363 for (auto &el: fChangedElements)
364 {
365 UChar_t bits = el->GetChangeBits();
366
367 nlohmann::json jobj = {};
368 jobj["fElementId"] = el->GetElementId();
369 jobj["changeBit"] = bits;
370
371 if (bits & kCBElementAdded || bits & kCBObjProps)
372 {
373 if (gDebug > 0 && bits & kCBElementAdded)
374 {
375 Info("REveScene::StreamRepresentationChanges", "new element change %s %d\n",
376 el->GetCName(), bits);
377 }
378
379 writeFull(el, jobj);
380 }
381 else
382 {
383 if (bits & kCBVisibility)
384 {
385 jobj["fRnrSelf"] = el->GetRnrSelf();
386 jobj["fRnrChildren"] = el->GetRnrChildren();
387 }
388
389 if (bits & kCBCoreJson) {
390 el->WriteCoreJson(jobj, -1);
391 }
392
393 if (bits & kCBTrans) {
394 el->WriteTransJson(jobj);
395 }
396
397 if ((bits & kCBRenderEntries) && !writeEntries(el, jobj)) {
398 // The shapes changed: send what kCBObjProps would. A stamped
399 // kCBObjProps resets the bounding box in AddStamp(), so the
400 // fallback resets it here.
401 jobj["changeBit"] = bits | kCBObjProps;
402 el->ResetBBox();
403 writeFull(el, jobj);
404 }
405 }
406
407 jarr.push_back(jobj);
408
409 el->ClearStamps();
410 }
411
412 fChangedElements.clear();
413 fRemovedElements.clear();
414
415 // render data for total change
417 Int_t off = 0;
418
419 for (auto &b : blocks) {
420 const int left = fOutputBinary.size() - off;
421 auto rd_size = b.fFull ? b.fEl->fRenderData->Write(&fOutputBinary[off], left)
422 : b.fEl->fRenderData->Write(&fOutputBinary[off], left, b.fTags);
423
424 off += rd_size;
425 }
426 assert(off == fTotalBinarySize);
427
428 jhdr["fTotalBinarySize"] = fTotalBinarySize;
429
430 nlohmann::json msg = { {"header", jhdr}, {"arr", jarr}};
431 fOutputJson = msg.dump();
432 REveUtil::AppendServerTime(fOutputJson); // stamped again just before each send
433
434 if (gDebug > 0)
435 Info("REveScene::StreamRepresentationChanges", "class: %s changes %s ...", GetCName(), msg.dump(1).c_str() );
436}
437
439{
440 for (auto && client : fSubscribers) {
441 if (!fOutputJson.empty()) {
443 if (gDebug > 0)
444 printf(" sending json, len = %d --> to conn_id = %d\n", (int) fOutputJson.size(), client->fId);
445 client->fWebWindow->Send(client->fId, fOutputJson);
446 }
447 if (fTotalBinarySize) {
448 if (gDebug > 0)
449 printf(" sending binary, len = %d --> to conn_id = %d\n", fTotalBinarySize, client->fId);
450 client->fWebWindow->SendBinary(client->fId, &fOutputBinary[0], fTotalBinarySize);
451 }
453 }
454 ClearOutput();
455}
456
457////////////////////////////////////////////////////////////////////////////////
458/// Drop the output of the last StreamElements() or
459/// StreamRepresentationChanges() once it has been sent, so that the next
460/// SendChangesToSubscribers() does not send it again. REveManager calls this
461/// after streaming a scene directly to one new connection.
462
464{
465 fOutputJson.clear();
466 fOutputBinary.clear();
468}
469
471{
472 if (gDebug > 0)
473 ::Info("REveScene::IsChanged","%s (changed_or_added=%d, removed=%d)", GetCName(),
474 (int) fChangedElements.size(), (int) fRemovedElements.size());
475
476 return ! (fChangedElements.empty() && fRemovedElements.empty());
477}
478
479
480/** \class REveSceneList
481\ingroup REve
482List of Scenes providing common operations on REveScene collections.
483*/
484
485////////////////////////////////////////////////////////////////////////////////
486/// Constructor.
487
488REveSceneList::REveSceneList(const std::string& n, const std::string& t) :
489 REveElement(n, t)
490{
491 SetChildClass(TClass::GetClass<REveScene>());
492}
493
494////////////////////////////////////////////////////////////////////////////////
495/// Destroy all scenes and their contents.
496/// The object with non-zero deny-destroy will still survive.
497
499{
500 auto i = fChildren.begin();
501 while (i != fChildren.end())
502 {
503 REveScene* s = (REveScene*) *(i++);
504 s->DestroyElements();
505 s->DestroyOrWarn();
506 }
507}
508
509////////////////////////////////////////////////////////////////////////////////
510/// Loop-wrapers over Scene children, element type checked on insertion.
511
513{
514 for (auto &c: fChildren)
515 {
516 static_cast<REveScene*>(c)->BeginAcceptingChanges();
517 }
518}
519
521{
522 for (auto &c: fChildren)
523 {
524 static_cast<REveScene*>(c)->EndAcceptingChanges();
525 }
526}
527
529{
530 for (auto &el : fChildren)
531 {
532 if (((REveScene*) el)->IsChanged())
533 return true;
534 }
535 return false;
536}
#define b(i)
Definition RSha256.hxx:100
#define c(i)
Definition RSha256.hxx:101
#define e(i)
Definition RSha256.hxx:103
unsigned char UChar_t
Unsigned Character 1 byte (unsigned char)
Definition RtypesCore.h:53
constexpr Bool_t kFALSE
Definition RtypesCore.h:109
constexpr Bool_t kTRUE
Definition RtypesCore.h:108
Bool_t operator==(const TDatime &d1, const TDatime &d2)
Definition TDatime.h:102
void Info(const char *location, const char *msgfmt,...)
Use this function for informational messages.
Definition TError.cxx:241
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize id
char name[80]
Definition TGX11.cxx:142
Int_t gDebug
Global variable setting the debug level. Set to 0 to disable, increase it in steps of 1 to increase t...
Definition TROOT.cxx:792
virtual void DestroyOrWarn()
Destroy this element. Prints a warning if deny-destroy is in force.
TClass * IsA() const
Return class for this element Return REveElement class in case dicitonary is not exisiting.
virtual void BuildRenderEntries(const std::set< std::string > &tags)
Bring the render data entries named in tags up to date for a kCBRenderEntries update,...
virtual void WriteTransJson(nlohmann::json &cj)
Write the main transformation and its motion for a kCBTrans update.
virtual Int_t WriteCoreJson(nlohmann::json &cj, Int_t rnr_offset)
Write core json.
const char * GetCName() const
virtual Bool_t GetRnrSelf() const
virtual void DestroyElements()
Destroy all children of this element.
const std::set< std::string > & GetChangedEntryTags() const
virtual Bool_t GetRnrChildren() const
ElementId_t GetElementId() const
std::list< REveElement * > List_t
virtual void RemoveElement(REveElement *el)
Remove el from the list of children.
REveRenderData * GetRenderData() const
REveException Exception-type thrown by Eve classes.
Definition REveTypes.hxx:42
REveSceneList * GetScenes() const
void SceneSubscriberWaitingResponse(unsigned cinnId)
REveViewerList * GetViewers() const
Render data of an element: a client maker name and a list of tagged entries, each a typed array with ...
int GetBinarySize() const
Size of the block in the scene blob, a multiple of kAlign.
void WriteJson(Json &rd) const
render_data.size and render_data.entries; offsets are block-relative.
const std::string & GetRnrFunc() const
REveSceneList(const REveSceneList &)=delete
void BeginAcceptingChanges()
Loop-wrapers over Scene children, element type checked on insertion.
void DestroyScenes()
Destroy all scenes and their contents.
std::vector< std::unique_ptr< REveClient > > fSubscribers
!
Definition REveScene.hxx:72
void AddCommand(const std::string &name, const std::string &icon, const REveElement *element, const std::string &action)
Definition REveScene.cxx:94
void AddSubscriber(std::unique_ptr< REveClient > &&sub)
Definition REveScene.cxx:73
void ClearOutput()
Drop the output of the last StreamElements() or StreamRepresentationChanges() once it has been sent,...
std::vector< char > fOutputBinary
!
Definition REveScene.hxx:76
~REveScene() override
Destructor.
Definition REveScene.cxx:54
void SceneElementRemoved(ElementId_t id)
void StreamRepresentationChanges()
Prepare data for sending element changes.
void StreamJsonRecurse(REveElement *el, nlohmann::json &jobj)
std::vector< SceneCommand > fCommands
!
Definition REveScene.hxx:79
void StreamMotionChanges(nlohmann::json &arr)
Move every element whose only pending change is kCBTrans from the change list into arr,...
Int_t WriteCoreJson(nlohmann::json &cj, Int_t rnr_offset) override
Write core json.
Definition REveScene.cxx:63
std::vector< ElementId_t > fRemovedElements
!
Definition REveScene.hxx:70
void SceneElementChanged(REveElement *element)
void RemoveSubscriber(unsigned int)
Definition REveScene.cxx:84
static void AppendServerTime(std::string &msg)
Append "server_time" to the JSON message msg, a non-empty object or array: as its last key,...
Definition REveUtil.cxx:63
static void StampServerTime(std::string &msg)
Set the "server_time" that AppendServerTime() put at the end of msg to now.
Definition REveUtil.cxx:76
void SceneDestructing(REveScene *scene)
Callback done from a REveScene destructor allowing proper removal of the scene from affected viewers.
const Int_t n
Definition legend1.C:16
Namespace for ROOT features in testing.
Definition TROOT.h:100
R__EXTERN REveManager * gEve
TMarker m
Definition textangle.C:8
Shape
Definition main.cpp:15