]> gerrit.simantics Code Review - simantics/3d.git/blob - org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/common/AbstractVTKNodeMap.java
0866dde55e730b6acaa82fd71d9de56abe983e4a
[simantics/3d.git] / org.simantics.g3d.vtk / src / org / simantics / g3d / vtk / common / AbstractVTKNodeMap.java
1 /*******************************************************************************
2  * Copyright (c) 2012, 2013 Association for Decentralized Information Management in
3  * Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.g3d.vtk.common;
13
14 import java.util.ArrayDeque;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.Deque;
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Set;
24 import java.util.Stack;
25
26 import org.simantics.db.ReadGraph;
27 import org.simantics.db.Session;
28 import org.simantics.db.UndoContext;
29 import org.simantics.db.WriteGraph;
30 import org.simantics.db.common.request.ReadRequest;
31 import org.simantics.db.common.request.WriteRequest;
32 import org.simantics.db.exception.DatabaseException;
33 import org.simantics.db.layer0.util.Layer0Utils;
34 import org.simantics.db.service.UndoRedoSupport;
35 import org.simantics.g3d.ontology.G3D;
36 import org.simantics.g3d.scenegraph.RenderListener;
37 import org.simantics.g3d.scenegraph.base.INode;
38 import org.simantics.g3d.scenegraph.base.NodeListener;
39 import org.simantics.g3d.scenegraph.base.ParentNode;
40 import org.simantics.objmap.exceptions.MappingException;
41 import org.simantics.objmap.graph.IMapping;
42 import org.simantics.objmap.graph.IMappingListener;
43 import org.simantics.utils.datastructures.Callback;
44 import org.simantics.utils.datastructures.MapList;
45 import org.simantics.utils.datastructures.MapSet;
46 import org.simantics.utils.datastructures.Pair;
47 import org.simantics.utils.ui.ExceptionUtils;
48
49 import vtk.vtkProp;
50
51 public abstract class AbstractVTKNodeMap<DBObject,E extends INode> implements VTKNodeMap<DBObject,E>, IMappingListener, RenderListener, NodeListener, UndoRedoSupport.ChangeListener{
52
53         private static final boolean DEBUG = false;
54         
55         protected Session session;
56         protected IMapping<DBObject, INode> mapping;
57         protected VtkView view;
58         
59         private MapList<E, vtkProp> nodeToActor = new MapList<E, vtkProp>();
60         private Map<vtkProp,E> actorToNode = new HashMap<vtkProp, E>();
61
62         protected ParentNode<E> rootNode;
63         
64         protected UndoRedoSupport undoRedoSupport;
65         protected int undoOpCount = 0;
66         protected int redoOpCount = 0;
67         protected boolean runUndo = false;
68         protected boolean runRedo = false;
69         public AbstractVTKNodeMap(Session session, IMapping<DBObject,INode> mapping, VtkView view, ParentNode<E> rootNode) {
70                 this.session = session;
71                 this.mapping = mapping;
72                 this.view = view;
73                 this.rootNode = rootNode;
74                 view.addListener(this);
75                 mapping.addMappingListener(this);
76                 rootNode.addListener(this);
77                 
78                 undoRedoSupport = session.getService(UndoRedoSupport.class);
79                 undoRedoSupport.subscribe(this);
80                 try {
81                         UndoContext undoContext = undoRedoSupport.getUndoContext(session); 
82                         undoOpCount = undoContext.getAll().size();
83                         redoOpCount = undoContext.getRedoList().size();
84                 } catch(DatabaseException e) {
85                         e.printStackTrace();
86                 }
87         }
88
89         protected abstract void addActor(E node);
90         protected abstract void removeActor(E node);
91         protected abstract void updateActor(E node,Set<String> ids);
92         
93         public void repaint() {
94                 view.refresh();
95         }
96         
97         public void populate() {
98                 for (E node : rootNode.getNodes()) {
99                         receiveAdd(node, node.getParentRel(),true);
100                 }
101                 repaint();
102         }
103         
104         @Override
105         public E getNode(vtkProp prop) {
106                 return actorToNode.get(prop);
107         }
108         
109         @SuppressWarnings("unchecked")
110         @Override
111         public Collection<vtkProp> getRenderObjects(INode node) {
112                 return nodeToActor.getValues((E)node);
113         }
114         
115         protected <T extends vtkProp> void map(E node, Collection<T> props) {
116             for (vtkProp p : props) {
117                 nodeToActor.add(node, p);
118                 actorToNode.put(p, node);
119             }
120         }
121         
122         protected void removeMap(E node) {
123             Collection<vtkProp> coll = nodeToActor.getValuesUnsafe(node);
124             for (vtkProp p : coll) {
125                 actorToNode.remove(p);
126             }
127             nodeToActor.remove(node);
128         }
129         
130         @SuppressWarnings("unchecked")
131         @Override
132         public ParentNode<E> getRootNode() {
133                 return (ParentNode<E>)rootNode;
134         }
135         
136         
137         
138         @Override
139         public boolean isChangeTracking() {
140                 return changeTracking;
141         }
142         
143         @Override
144         public void setChangeTracking(boolean enabled) {
145                 changeTracking = enabled;
146         }
147         
148         private boolean changeTracking = true;
149         
150         protected Object syncMutex = new Object(); 
151         
152
153         private List<Pair<E,String>> added = new ArrayList<Pair<E,String>>();
154         private List<Pair<E,String>> removed = new ArrayList<Pair<E,String>>();
155         private MapSet<E, String> updated = new MapSet.Hash<E, String>();
156
157         private boolean rangeModified = false;
158         
159         public boolean isRangeModified() {
160         return rangeModified;
161     }
162         
163         @Override
164         public void onChanged() {
165                 try {
166                         UndoContext undoContext = undoRedoSupport.getUndoContext(session);
167                         int ucount = undoContext.getAll().size();
168                         int rcount = undoContext.getRedoList().size();
169                         if (DEBUG) System.out.println("Previous U:" + undoOpCount +" R:" + redoOpCount +" Current U:"+ucount+" R:"+rcount);
170                         if (ucount < undoOpCount) {
171                                 runUndo = true;
172                         } else {
173                                 runUndo = false;
174                         }
175                         if (!runUndo && rcount > 0)
176                                 runRedo = true;
177                         else
178                                 runRedo = false;
179                         undoOpCount = ucount;
180                         redoOpCount = rcount;
181                         
182                         if (DEBUG) System.out.println("Undo " + runUndo + " Redo " + runRedo);
183                 } catch (DatabaseException e) {
184                         // TODO Auto-generated catch block
185                         e.printStackTrace();
186                 }
187                 
188                 
189         }
190         
191         @SuppressWarnings("unchecked")
192         @Override
193         public void updateRenderObjectsFor(E node) {
194                 List<vtkProp> toDelete = new ArrayList<vtkProp>();
195                 view.lock();
196                 for (vtkProp prop : nodeToActor.getValues((E)node)) {
197                         if (prop.GetVTKId() != 0) {
198                                 view.getRenderer().RemoveActor(prop);
199                                 //prop.Delete();
200                                 toDelete.add(prop);
201                         }
202                         actorToNode.remove(prop);
203                 }
204                 view.unlock();
205                 nodeToActor.remove((E)node);
206                 Collection<vtkProp> coll = getActors((E)node);
207                 if (coll != null) {
208                         for (vtkProp prop : coll) {
209                                 nodeToActor.add((E)node,prop);
210                                 actorToNode.put(prop, (E)node);
211                                 toDelete.remove(prop);
212                         }
213                 }
214                 for (vtkProp p : toDelete)
215                         p.Delete();
216         }
217         
218         protected abstract  Collection<vtkProp> getActors(E node);
219         
220         @SuppressWarnings("unchecked")
221         private void receiveAdd(E node, String id, boolean db) {
222                 if (DEBUG) System.out.println("receiveAdd " + debugString(node)  + " " + id + " " + db);
223                 synchronized (syncMutex) {
224                         for (Pair<E, String> n : added) {
225                                 if (n.first.equals(node))
226                                         return;
227                         }
228                         if (changeTracking) {
229                                 mapping.rangeModified((E)node.getParent());
230                                 mapping.rangeModified((E)node);
231                         }
232                         added.add(new Pair<E, String>(node, id));
233                         rangeModified = true;
234                 }
235                 repaint();
236         }
237         
238         @SuppressWarnings("unchecked")
239         private void receiveRemove(E node, String id, boolean db) {
240                 if (DEBUG) System.out.println("receiveRemove " + debugString(node)  + " " + id + " " + db);
241                 synchronized (syncMutex) {
242                         for (Pair<E, String> n : removed) {
243                                 if (n.first.equals(node))
244                                         return;
245                         }
246                         if (changeTracking && !db) {
247                             mapping.rangeModified((E)node);
248                                 mapping.rangeModified((E)node.getParent());
249                         }
250                         removed.add(new Pair<E, String>(node, id));
251                         rangeModified = true;
252                 }
253                 repaint();
254         }
255         
256         @SuppressWarnings("unchecked")
257         private void receiveUpdate(E node, String id, boolean db) {
258                 if (DEBUG) System.out.println("receiveUpdate " + debugString(node)  + " " + id + " " + db);
259                 synchronized (syncMutex) {
260 //          for (Pair<E, String> n : updated) {
261 //              if (n.first.equals(node))
262 //                  return;
263 //          }
264                         if (changeTracking && !db)
265                                 mapping.rangeModified(node);
266                         //updated.add(new Pair<E, String>(node, id));
267                         updated.add(node, id);
268                         rangeModified = true;
269                 }
270                 repaint();
271         }
272         
273         private boolean graphUpdates = false;
274         private Set<E> graphModified = new HashSet<E>();
275         
276         private boolean requestCommit = false;
277         private String commitMessage = null;
278         
279         @Override
280         public void commit(String message) {
281                 requestCommit = true;
282                 commitMessage = message;
283         }
284         
285         protected void doCommit() {
286                 session.asyncRequest(new WriteRequest() {
287                         
288                         @Override
289                         public void perform(WriteGraph graph) throws DatabaseException {
290                                 if (DEBUG) System.out.println("Commit " + commitMessage);
291                                 if (commitMessage != null) {
292                                         Layer0Utils.addCommentMetadata(graph, commitMessage);
293                                         graph.markUndoPoint();
294                                         commitMessage = null;
295                                 }
296                                 commit(graph);
297                         }
298                         
299                 }, new Callback<DatabaseException>() {
300                         
301                         @Override
302                         public void run(DatabaseException parameter) {
303                                 if (parameter != null)
304                                         ExceptionUtils.logAndShowError("Cannot commit editor changes", parameter);
305                         }
306                 });
307         }
308         
309         protected void commit(WriteGraph graph) throws DatabaseException {
310                 synchronized(syncMutex) {
311                         if (DEBUG) System.out.println("Commit");
312                         graphUpdates = true;
313                         mapping.updateDomain(graph);
314                         graphUpdates = false;
315                         clearDeletes();
316                         if (DEBUG) System.out.println("Commit done");
317                 }
318         }
319         
320         
321         
322         @Override
323         public void domainModified() {
324                 if (graphUpdates)
325                         return;
326                 if (DEBUG)System.out.println("domainModified");
327                 session.asyncRequest(new ReadRequest() {
328                         
329                         @SuppressWarnings("unchecked")
330                         @Override
331                         public void run(ReadGraph graph) throws DatabaseException {
332                                 update(graph);
333                         }
334                 });
335                 
336         }
337         
338         protected void reset(ReadGraph graph) throws MappingException {
339                 if (DEBUG) System.out.println("Reset");
340                 
341                 synchronized (syncMutex) {
342                         graphUpdates = true;
343                         mapping.getRangeModified().clear();
344                         for (DBObject o : mapping.getDomain())
345                                 mapping.domainModified(o);
346                         mapping.updateRange(graph);
347                         graphModified.clear();
348                         graphUpdates = false;
349                 }
350         }
351         
352         private boolean useFullSyncWithUndo = false;
353         
354         protected void update(ReadGraph graph) throws DatabaseException {
355                 if (DEBUG) System.out.println("Graph update start");
356                 if (runUndo && useFullSyncWithUndo) {
357                         reset(graph);
358                 } else {
359                         synchronized (syncMutex) {
360                                 graphUpdates = true;
361                                 for (DBObject domainObject : mapping.getDomainModified()) {
362                                         @SuppressWarnings("unchecked")
363                                         E rangeObject = (E) mapping.get(domainObject);
364                                         if (rangeObject != null)
365                                                 graphModified.add(rangeObject);
366                                 }
367                                 mapping.updateRange(graph);
368                                 graphModified.clear();
369                                 syncDeletes();
370                                 clearDeletes();
371                                 graphUpdates = false;
372                         }
373                 }
374                 
375                 if (mapping.isRangeModified() && !runUndo && !runRedo)
376                         commit((String)null);
377                 if (DEBUG) System.out.println("Graph update done");
378         }
379         
380         @Override
381         public void rangeModified() {
382                 //System.out.println("rangeModified");
383
384         }
385         
386         @Override
387         public void postRender() {
388                 // Commit changes if
389                 // 1. Commit has been requested
390                 // 2. There are no pending changes that should be processed in preRender() 
391                 if (requestCommit && !rangeModified) { // FIXME : not thread safe.
392                         requestCommit = false;
393                         doCommit();
394                 }
395         }
396         
397         // Reusable containers for data synchronisation
398         List<Pair<E, String>> rem = new ArrayList<Pair<E,String>>();  // Removed objects
399         List<Pair<E, String>> add = new ArrayList<Pair<E,String>>();  // Added objects
400         MapSet<E, String> mod = new MapSet.Hash<E, String>();         // Modified objects
401         Set<E> propagation = new HashSet<E>();                        // Objects with propagated changes 
402         Stack<E> stack = new Stack<E>();                              // Stack for handling propagation
403         Set<E> delete = Collections.synchronizedSet(new HashSet<E>()); // Objects to be completely deleted
404         Set<E> deleteUC = new HashSet<E>();
405         
406         @Override
407         public synchronized void preRender() {
408                 updateCycle();
409         }
410         
411         
412         /**
413          * When objects are removed (either from Java or Graph), after remove processing the Java objects remain in mapping cache.
414          * This causes problems with Undo and Redo, which cause re-using the removed objects from mapping cache.
415          * 
416          * This code here synchronizes removed and added objects to collect deletable objects. (a deletable object is one which is removed but not added).  
417          * 
418          */
419         protected void syncDeletes() {
420                 deleteUC.clear();
421                 for (Pair<E, String> n : removed) {
422                         deleteUC.add(n.first);   
423                 }
424                 for (Pair<E, String> n : added) {
425                         deleteUC.remove(n.first);   
426                 } 
427                 if (DEBUG && deleteUC.size() > 0) {
428                         System.out.println("Delete sync");
429                         for (E n : delete) {
430                                 System.out.println(debugString(n));
431                         }
432                 }
433                 delete.addAll(deleteUC);
434                 deleteUC.clear();
435         }
436
437         /**
438          * Clears deletable objects from mapping cache.
439          */
440         protected void clearDeletes() {
441                 if (DEBUG && delete.size() > 0) System.out.println("Delete");
442                 for (E n : delete) {
443                         if (DEBUG) System.out.println(debugString(n));
444                         mapping.getRange().remove(n);
445                         stopListening(n);
446                 }
447                 delete.clear();
448         }
449         
450         protected String debugString(E n) {
451                 return n + "@" + Integer.toHexString(n.hashCode());
452         }
453         
454         protected boolean filterChange(List<Pair<E,String>> list,E n) {
455             for (int i = list.size()-1; i >= 0; i--) {
456             if (list.get(i).first == n) {
457                 list.remove(i);
458                 return true;
459             }
460         }
461             return false;
462         }
463         
464         @SuppressWarnings("unchecked")
465         protected void updateCycle() {
466                 rem.clear();
467                 add.clear();
468                 mod.clear();
469                 propagation.clear();
470                 
471                 
472                 synchronized (syncMutex) {
473                     // Check for overlapping additions and deletions, prevent deleting objects that are also added and vice versa.
474                     Deque<E> stack = new ArrayDeque<E>();
475                 for (Pair<E, String> n : added) {
476                     stack.add(n.first);
477                 }
478                 while (!stack.isEmpty()) {
479                     E n = stack.pop();
480                     boolean conflict = filterChange(removed, n);
481                     if (conflict) {
482                         System.out.println("Prevent removing " + n);
483                         //filterChange(added, n)
484                         if (filterChange(added, n))
485                             System.out.println("Prevent adding " + n);
486                     }
487                     if (n instanceof ParentNode) {
488                         ParentNode<INode> pn = (ParentNode<INode>)n;
489                         for (INode cn : pn.getNodes()) {
490                             stack.push((E)cn);
491                         }
492                     }
493                 }
494                 
495                         rem.addAll(removed);
496                         add.addAll(added);
497                         for (E e : updated.getKeys()) {
498                                 for (String s : updated.getValues(e)) {
499                                         mod.add(e, s);
500                                 }
501                         }
502                         syncDeletes();
503                         removed.clear();
504                         added.clear();
505                         updated.clear();
506                 }
507                 
508                 
509                 
510                 for (Pair<E, String> n : rem) {
511                         stopListening(n.first);
512                         removeActor(n.first);
513                 }
514                 
515                 for (Pair<E, String> n : add) {
516                         addActor(n.first);
517                         listen(n.first);
518                 }
519                 
520                 for (E e : mod.getKeys()) {
521                         Set<String> ids = mod.getValues(e);
522                         if (ids.contains(G3D.URIs.hasPosition) || ids.contains(G3D.URIs.hasOrientation)) {
523                                 if (!propagation.contains(e))
524                                         propagation.add(e);
525                         }
526                 }
527
528                 if (propagation.size() > 0) {
529                         stack.clear();
530                         stack.addAll(propagation);
531                         propagation.clear();
532                         while (!stack.isEmpty()) {
533                                 E node = stack.pop();
534                                 if (propagation.contains(node))
535                                         continue;
536                                 propagation.add(node);
537                                 for (NodeListener l : node.getListeners()) {
538                                         if (l == this) {
539                                                 //changeTracking = false;
540                                                 //l.propertyChanged(node, G3D.URIs.hasPosition);
541                                                 //changeTracking = true;
542                                         } else {
543                                                 l.propertyChanged(node, G3D.URIs.hasWorldPosition);
544                                         }
545                                 }
546                                 if (node instanceof ParentNode) {
547                                         stack.addAll(((ParentNode<E>)node).getNodes());
548                                 }
549                         }
550                 }
551                 
552 //      synchronized (syncMutex) {
553 //          rem.addAll(removed);
554 //          add.addAll(added);
555 //          //mod.addAll(updated);
556 //          for (E e : updated.getKeys()) {
557 //              for (String s : updated.getValues(e))
558 //                  mod.add(e, s);
559 //          }
560 //          
561 //          removed.clear();
562 //          added.clear();
563 //          updated.clear();
564 //      }
565                 
566                 for (E e : mod.getKeys()) {
567                         Set<String> ids = mod.getValues(e);
568                         updateActor(e,ids);
569                 }
570                 
571                 
572                 for (Pair<E, String> n : rem) {
573                         for (NodeListener l : nodeListeners)
574                                 l.nodeRemoved(null, n.first, n.second);
575                 }
576                 for (Pair<E, String> n : add) {
577                         for (NodeListener l : nodeListeners)
578                                 l.nodeAdded(n.first.getParent(), n.first, n.second);
579                 }
580 //      for (Pair<E, String> n : mod) {
581 //          for (NodeListener l : nodeListeners)
582 //              l.propertyChanged(n.first, n.second);
583 //      }
584                 for (E e : mod.getKeys()) {
585                         for (NodeListener l : nodeListeners)
586                                 for (String s : mod.getValues(e))
587                                         l.propertyChanged(e, s);
588                 }
589                 
590                 synchronized (syncMutex) {
591                         if (added.isEmpty() && removed.isEmpty() && updated.getKeys().size() == 0)
592                                 rangeModified = false;
593                 }
594         }
595         
596         @SuppressWarnings("unchecked")
597         private void listen(INode node) {
598                 node.addListener(this);
599                 if (node instanceof ParentNode<?>) {
600                         ParentNode<INode> parentNode = (ParentNode<INode>)node;
601                         for (INode n : parentNode.getNodes())
602                                 listen(n);
603                 }
604         }
605         
606         private void stopListening(INode node) {
607                 node.removeListener(this);
608                 if (node instanceof ParentNode<?>) {
609                         @SuppressWarnings("unchecked")
610                         ParentNode<INode> parentNode = (ParentNode<INode>)node;
611                         for (INode n : parentNode.getNodes())
612                                 stopListening(n);
613                 }
614         }
615         
616         @SuppressWarnings("unchecked")
617         @Override
618         public void propertyChanged(INode node, String id) {
619                 //receiveUpdate((E)node, id, graphUpdates);
620                 receiveUpdate((E)node, id, graphModified.contains(node));
621                 
622         }
623         
624         @SuppressWarnings("unchecked")
625         @Override
626         public <T extends INode> void nodeAdded(ParentNode<T> node, INode child,
627                         String rel) {
628                 if (DEBUG) System.out.println("Node added " + child + " parent " + node);
629                 //receiveAdd((E)child, rel ,graphUpdates);
630                 receiveAdd((E)child, rel ,graphModified.contains(node));
631         }
632         
633         @SuppressWarnings("unchecked")
634         @Override
635         public <T extends INode> void nodeRemoved(ParentNode<T> node, INode child,
636                         String rel) {
637                 if (DEBUG) System.out.println("Node removed " + child + " parent " + node);
638                 //receiveRemove((E)child, rel, graphUpdates);
639                 receiveRemove((E)child, rel, graphModified.contains(node));
640                 
641                 //FIXME : 1. sometimes removed structural models cause ObjMap to add their children again.
642                 //           removing the listener here prevents corruption of visual model, but better fix is needed.
643                 //        2. detach causes nodeRemoved event, which then causes other critical events to be missed. Took out th 
644                 //stopListening(child);
645         }
646         
647         @Override
648         public void delete() {
649                 if (undoRedoSupport != null)
650                         undoRedoSupport.cancel(this);
651                 
652                 changeTracking = false;
653                 view.removeListener(this);
654                 mapping.removeMappingListener(this);
655
656                 List<E> nodes = new ArrayList<E>(nodeToActor.getKeySize());
657                 nodes.addAll(nodeToActor.getKeys());
658                 for (E node : nodes) {
659                         node.removeListener(this);
660                         removeActor(node);
661                         node.cleanup();
662                 }
663                 for (vtkProp prop : actorToNode.keySet()) {
664                         if (prop.GetVTKId() != 0) 
665                                 prop.Delete();
666                 }
667                 actorToNode.clear();
668                 nodeToActor.clear();
669                 
670         }
671         
672         
673         private List<NodeListener> nodeListeners = new ArrayList<NodeListener>();
674         @Override
675         public void addListener(NodeListener listener) {
676                 nodeListeners.add(listener);
677                 
678         }
679         
680         @Override
681         public void removeListener(NodeListener listener) {
682                 nodeListeners.remove(listener);
683                 
684         }
685         
686         public IMapping<DBObject,INode> getMapping() {
687                 return mapping;
688         }
689         
690         
691 }