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