I'm hoping to make a big and effective molecular simulator, but I'm having a problem.
When I add molecules or atoms to the javaFX screen, they update their position and once in a while some of the atoms disappear, because their old positions did not update the way they should.
The only way they update, is that in each frame(step), they start by updating the old position to what the current position was last frame(step). And this is the error, sometimes it updates to x,y,z = 0,0,0. Even though it should have been 421,225,14 etc.
The old positions are always updated to 0,0,0, when the error occurs.
I use 4 threads to run the program, with thread safe lists, that are not divided between the threads, that is, each thread has 1/4 of the screen to process.
This is the update method:
private void updateOldPositions() {
lastXPos = xPos;
lastYPos = yPos;
lastZPos = zPos;
}
This method is then not working, so the program adds infinite amounts of the same molecule, because it cant find the old positions of the molecule to remove.
They are all now x,y,z = 0,0,0.
cellLists.get((a.getLastXPos()+a.getLastYPos()+a.getLastZPos())/d).remove(a);
Anyone got an idea for what the problem is, can add link to git hub if you need to see more of the code. Thank you.
Related
I am building an effect which needs to "freeze" the camera texture for a few seconds on certain occasions, triggered by a pulse (Just like a "snapshot" effect where you trigger it and then the image doesn't move anymore for a few seconds - If you remember Pokemon snap on N64)
I am currently trying to build it using the Delay Frame patch. I render the scene using a scene render pass, then it goes through the delay frame in the first frame input, but the problem is I don't want to freeze the first frame I want to freeze a random phrase a T= X seconds, triggered by a user defined pulse.
Do you have any insight on how I should achieve that?
Thanks a lot, have a great day !
so what you can do is using the "Runtime patch " you can get how much time has passed since the effect has started so with that and a "greater then patch " you can make a trigger with the "pulse patch " to make the freeze.
I'm writing an evolution simulator application using PyQt4. I have 'creatures' and 'vegetation' on a QGraphics scene. The creatures eat the vegetation, which shrinks as it's eaten, and when it gets down to certain size, it dies and gets deleted from the scene. Creatures that starve also get deleted when they die.
The problem is, when I delete the vegetation items from the scene, I get a segmentation fault (not immediately, it takes varying amount of time). This didn't happen with the creatures, only when I added the vegetation, though they are conceptually the same as the creatures (class instances).
The specific loop where I delete the items is as follows (code is simplified with significant amount of code replaced with comments):
dead = set()
items = self.scene.items()
for item in items:
if isinstance(item, Creature):
# Do some calculation to specify what creature does
for item1 in self.scene.items():
# Look through other items on scene and define interactions
if isinstance(item1, Creature):
# Specify what to do if current item is being compared to another creature
if isinstance(item1, Vegetation):
# Specify what to do if current item is being compared to vegetation
# If creature dies, add to dead set
dead.add(item)
elif isinstance(item, Vegetation):
# Do same as for creature (see above)
# If vegetation dies, add to dead set
dead.add(item)
# Get rid of all dead items from scene
while dead:
deadItem = dead.pop()
self.scene.removeItem(deadItem)
del deadItem
If I comment out the self.scene.removeItem line, then the program doesn't crash.
It seems that the program is calling on a memory address that is no longer valid, but I have no idea what is causing it.
The whole application is quite long, which is why I haven't put it here, but if necessary I can add it.
I'm running Python 3.4.3 using PyQt4 on Windows.
So for anyone who is having similar problems to me, I have found a fix. It is to do with the boundingRect of the vegetation and creatures. When their QRectF() is being changed, the scene still uses the previous boundingRect() before the change. The fix was done by preparing the scene to update the new QRectF() of each item when they change, the code to do so was :
item.prepareGeometryChange()
or
item1.prepareGeometryChange()
depending on which organism had been changed. This line(s) of code was added just before their QRectF() was changed.
Thank you to #strubbly for mentioning about the boundingRect of the items.
I have a StackPane and a Group within it. The Group has the actual visual contents and can be panned and zoomed by the user. The Group has coordinate transformations.
I would like mouse and scroll events to behave the same even if they happen outside of the group (either because it's been zoomed out or because of holes in the Group graphics).
I cannot directly forward (mouse) events from the StackPane, since the coordinate systems differ.
I tried placing a grand transparent Rectangle behind the Group, but this leads to graphic system texture size overflows (= no good).
Now I'm thinking of having handlers in both the StackPane and the Group, passing on to coordinate-corrected separate method within the Group. Works, but would there exist a neater mechanism that I have not realized?
The way I solved this:
In the Group constructor I set up handlers for its parent:
runLater {
val pv= parent.value
assert( pv != null )
..some local var's here..
pv.onMousePressed = (ev: MouseEvent) => if (ev.primaryButtonDown) {
...
The runLater takes care that the Group does not need to be attached to its parent (or given the potential parent's handle as a constructor parameter). Once the runLater-block gets executed, the parenthood is established.
I find this a rather neat approach. It allows all the event handling to be within the Group, but still takes use of the parent's larger real estate. No code needs to be in two places. Coordinate transforms are always the same, since it's the parent's event that gets called (not the Group's).
I'm using Scala, but the same approach should work in any JVM language.
Note: Beginning the handler with an if would not compile in the current ScalaFX. It's a small glitch of ScalaFX and can be easily fixed (ask me for details).
Just my two cents : I got the same problem in JavaFx 8, and I solved it by replacing my Group by a Pane. No change done, and it works like a charm. Could be useful to know.
"The current vertex declaration does not include all the elements required by the current vertex shader. TextureCoordinate0 is missing."
I get this error when I try to use a spriteFont to draw my FPS on the screen, on the line where I call spriteBatch.End()
My effect doesn't even use texture coordinates.
But I have found the root of the problem, just not how to fix it.
I have a separate thread that builds the geometry (an LOD algorithm) and somehow this seems to be why I have the problem.
If I make it non-threaded and just update my mesh per frame I don't get an error.
And also if I keep it multithreaded but don't try to draw text on the screen it works fine.
I just can't do both.
To make it even more strange, it actually compiles and runs for a little bit. But always crashes.
I put a Thread.Sleep in the method that builds the mesh so that it happens less often and I saw that the more I make this thread sleep, and the less it gets called, the longer it will run on average before crashing.
If it sleeps for 1000ms it runs for maybe a minute. If it sleeps for 10ms it doesn't even show one frame before crashing. This makes me believe that it has to do with a certain line of code being executed on the mesh building thread at the same time you are drawing text on the screen.
It seems like maybe I have to lock something when drawing the text, but I have no clue.
Any ideas?
My information comes from the presentation "Understanding XNA Framework Performance" from GDC 2008. It says:
GraphicsDevice is somewhat thread-safe
Cannot render from more than one thread at a time
Can create resources and SetData while another thread renders
ContentManager is not thread-safe
Ok to have multiple instances, but only one per thread
My guess is that you're breaking one of these rules somewhere. Or you're modifying a buffer that is being used to render without the appropriate locking.
This question is messy, i dont need a working solution, i need some psuedo code.
How would i solve this maze? This is a homework question. I have to get from point green to red. At every fork i need to 'spawn a thread' and go that direction. I need to figure out how to get to red but i am unsure how to avoid paths i already have taken (finishing with any path is ok, i am just not allowed to go in circles).
Heres an example of my problem, i start by moving down and i see a fork so one goes right and one goes down (or this thread can take it, it doesnt matter). Now lets ignore the rest of the forks and say the one going right hits the wall, goes down, hits the wall and goes left, then goes up. The other thread goes down, hits the wall then goes all the way right. The bottom path has been taken twice, by starting at different sides.
How do i mark this path has been taken? Do i need a lock? Is this the only way? Is there a lockless solution?
Implementation wise i was thinking i could have the maze something like this. I dont like the solution because there is a LOT of locking (assuming i lock before each read and write of the haveTraverse member). I dont need to use the MazeSegment class below, i just wrote it up as an example. I am allowed to construct the maze however i want. I was thinking maybe the solution requires no connecting paths and thats hassling me. Maybe i could split the map up instead of using the format below (which is easy to read and understand). But if i knew how to split it up i would know how to walk it thus the problem.
How do i walk this maze efficiently?
The only hint i receive was dont try to conserve memory by reusing it, make copies. However that was related to a problem with ordering a list and i dont think the hint was a hint for this.
class MazeSegment
{
enum Direction { up, down, left, right}
List<Pair<Direction, MazeSegment*>> ConnectingPaths;
int line_length;
bool haveTraverse;
}
MazeSegment root;
class MazeSegment
{
enum Direction { up, down, left, right}
List<Pair<Direction, MazeSegment*>> ConnectingPaths;
bool haveTraverse;
}
void WalkPath(MazeSegment segment)
{
if(segment.haveTraverse) return;
segment.haveTraverse = true;
foreach(var v in segment)
{
if(v.haveTraverse == false)
spawn_thread(v);
}
}
WalkPath(root);
Parallel Breadth-First Search
Search for parallel or multithread bread first traversal, which is basically what you're doing. Each time you come to a fork in your maze (where you can take one of several paths), you create a new worker thread to continue the search down each of the possible paths and report back which one gets you to the end.
It's similar to "simple" breadth first searches, except the subtrees can be searched in parallel.
If this were a pure tree data structure, you wouldn't need to lock, but since it's a graph traversal you will need to keep track of your visited nodes. So, the code which sets the "visited" flag of each node will need to be protected with a lock.
Here's a good example program. It uses audio feedback, so be sure your speakers are on.
http://www.break.com/games/maze15.html
Off hand, given your structure above, I could see solving this by adding an 'int Seen' to each MazeSegement instead of 'bool haveTraverse'. You could then use a interlocked increment on the 'Seen' variable as you're looping over the ConnectedPaths and only spawn a thread to take the path if the 'Seen' increment returns 1 (assuming Seen is initialized to 0).
So the code becomes something like
void WalkPath(MazeSegment segment)
{
foreach(var v in segment.ConnectedPaths)
{
if( Interlocked.Increment( &v.Path.Seen ) == 1)
spawn_thread(v.Path);
}
}
Other threads which might attempt to take the same path should get something >1. Because interlocked.increment would guarantee a thread-safe increment then we don't have to worry about 2 threads getting a result of '1' so only one thread should take a given path.
You can do this using the usual "read, calculate new value, compare-and-swap, repeat until CAS succeeds" method commonly found in lock-free programming.
All grid-squares in your maze start should hold a pointer representing the direction to move to reach the exit. Initially they all are "unknown".
Walk the maze starting at the exit. On each square reached, use compare and swap to replace "unknown" with the direction to the square this thread previously processed. If CAS fails, you've got a loop, prune that branch. If CAS succeeds, continue forward. When you assign a direction to the entrance, you now can follow the path to the exit.
Create a class (Worker) instances of which hold a path taken so far, and can only advance() through a straight corridor at given direction. At every intersection, drop the worker object which holds the path before intersection, and create two (or three) new objects, with a copy of that path and different turns taken.
Put these worker objects into a queue. Notice how every one of them is independent from another, so you may take several of them from the queue and advance() in parallel. You can simply create as many threads, or use a pool of threads according to the number of cores you have. Once any of the workers advance to the destination square, output the paths it holds, it is a solution.
Consider traversing the maze from exit to entry. In a real maze, blind alleys are intended to slow down motion form entry to exit, but rarely the other way around.
Consider adding a loop detection mechanism, e.g. by comparing intersections that make up your path with an intersection you encounter.
Consider using a hand-made linked list to represent the path. Note how inserting a new head to a linked list does not change the rest of it, so you can share the tail with other instances that don't modify it. This will reduce memory footprint and time needed to spawn a worker (only noticeable at rather large mazes).