Finding a better method to identify points exist "inside" of a cube in swift - swift

I want to find a way to check if points(vectors) in my scene are contained within a SCNBox I have displayed on screen. Currently I have an array of about 83000 SCNVector3's. So far, I do this by simply running a for loop on each point and checking against the SCNBox bounding box. If it falls within that bounding box I save the point to a separate array. My goal however is not 1 bounding box. I further subdivide the bounding box into equal sections. For each of those I then have to check each individual point again to see if they fall into each one of those individual bounding boxes. If they do, I save those boxes so that when I go to subdivide them again, I am not subdividing boxes that contain no points. This helps performance a little bit as large sections of boxes that don't have points are not needlessly checked. This works okay for a small amount of boxes however I need to subdivide the boxes into much larger amounts, sometimes in the hundreds to thousands of boxes. As you can imagine, it takes a long time to check all the boxes. Currently I am having to iterate through all the points every time for each box. Is there a faster approach to this?

Your question says is there a better way, so using the physics engine would be a more 'standard' approach IMO, but performance wise I wouldn't know without trying it myself. It seems you either check manually, or let the physics engine check it for you.
Try this post - it's similar and there are some examples. [67575481].
The physics engine checks nodes for nodes and it may have changed since I did this, but I had to generate node names for my nodes and check it that way. There may be other options now.
My example is a moving 'missile' that collides with a moving node containing 'some monster', so I wasn't dealing with the size you are.
83000 vectors, dunno, that seems like a lot. You'll still have to do the checks you do now, just differently.
Hope that helps...

Related

How do I make a Maze Generator on Scratch?

I am currently in High School, and I am in an APCSP (AP Computer Science Principles) class, which in my case is learning in Scratch programming. I am confused and have practically no idea what I'm doing. Scratch is very confusing and I feel like it's pointless to learn.
My question is this: Can anyone help me on how to make a Maze Generator on Scratch, as this is my project and it's giving me struggles.
Thank you.
It's actually possible to build with scratch but depends on what you are looking for. I assume you want to generate a simple maze like in old fashioned 8-bit games like boulder dash.
First decide on the size of your maze: for example 5 x 5 blocks.
If you want to create a maze, imagine drawing it on a grid on paper. Blocks are either "empty" or filled in. Our maze can be represented by numbers. The empty blocks are represented by a 0 and the filled blocks with a 1.
You could visualize that matrix like this if all blocks are empty:
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0
Adding a border wall while keeping the inside empty would look like:
1,1,1,1,1,
1,0,0,0,1,
1,0,0,0,1,
1,0,0,0,1,
1,1,1,1,1
Using a "list" variable to store this information would fit best within the possibilities of MIT Scratch.
In this case, you need to understand that each block in our maze is represented by a position in above matrix. You could draw numbers on a piece of paper in the shape and size of your grid / matrix as a reference to remember the position of each block if that makes it easier.
We also need to look at how our maze will relate to the Stage size. The width and height in pixels of a default scratch project is 480x360.
A 5 x 5 maze is divided in blocks of 480 / 5 = 96 width and 360 / 5 = 72 height. In other words, a block needs to be 96x72 pixels, based on a full screen maze.
Next step, is creating a sprite representing the visualization of the blocks of the maze. I would keep the first "costume" of our block sprite empty, and create a fully filled block to represent the walls of the maze.
After that, we need to programmatically create our maze. I made an example you can explore of random drawing of the blocks of a maze:
https://scratch.mit.edu/projects/278731659/
(You can change the rows & columns value to see it scale up, but remember the limit to the amount of clones the block sprite can have is 300)
This is just to get you started and by no means a complete solution. I just hope this helps you think in the right direction.
You can make this more advanced, by adding a function to explore and correct our randomly drawn grid to generate a walkable path from position x to position y. A rule you can program is for example: Every empty position in the grid should have at least two other empty positions in the spaces above, below, left and right of it.
There are many different ways to do this; whether this is with sprites and stamp or 2D lists and pen. Either way, the main component is the algorithm. This wikipedia page gives details on how maze generation works and few different algorithms. There is also a video series by The Coding Train here where he creates a maze generator with the 2D list method from above (this method is a bit harder on scratch, however). Either way, the best thing to do is to look at examples others have made, figure out how they work, and try to recreate them or make them better. Here's a good place to get started.
Scratch IS truly pointless! A simple maze generator would have you use the pen to draw predefined shapes (Such as a long hallway or intersection). You should also make (invisible) squares to separate everything and have the program draw in the squares.
I will put a link later that leads to a sample project that has the code.
Check out this video by griffpatch
https://www.youtube.com/watch?v=22Dpi5e9uz8
This was one of my projects, and the instructor provided this video for everyone to follow and expand from.

How to render voxel in an efficient way

For now, I use a 3D array to represent my voxels in different chunks. I want to render voxels which can be visible by the player, but the way I do it is totally not efficient:
I iterate over the whole 10*10*10 chunk and check on every voxel if there is a neighbor equal to Air. Then I render separatly each faces which can be visible. So I mostly check every voxels 6 times. And I do this for all chunks.
Is there a better way to proceed or an algorithm to reduce iterating?
I basicly don't know if it is better to work with 3D Array or Octree...
Thank.
I've been thinking through this problem recently, and since nobody has answered you I thought I'd mention some of the ideas I've come across.
Firstly, it's work noting that you only need to calculate which faces to render once, since that only changes if you remove or add a voxel, and then you only need to recalculate the voxels immediately around the place where you made the change. Just use a flag to mark for rendering and cache that until something changes. If you aren't already doing this, this will give you a big performance boost over calculating every frame.
I also recommend looking into this extremely fast raycasting algorythm:
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.42.3443&rep=rep1&type=pdf
You can use it for fast collision testing, and also for cull-testing. You can cast at grid nodes to see if any part of a face is visible.

Is there any regularity-detection tool for regions inside an image?

I'm working on MATLAB on some regions inside an image. I'm at a point in which I would like to be able to separate regions which exhibit some kind of regularity (e.g., being circle-ish or square-ish) from regions which does not resemble any known figure and which for my application are mere noise. I'll illustrate this using a descriptive MS Paint image:
Is there any tool that, most of the times (or even less, I know this can't be 100/100) will recognize the red thing as being different?
I'll deal with many shapes in a single image, so I don't mind if I carry on some red monsters along the way, as long as the majority of them is kicked out. Of course I know the indices of these regions, so I can manipulate them in MATLAB.
Many algorithms come to mind, e.g., getting the boundary and checking for its regularity/the number of times it changes curvature/..., checking for variations in vertical length through different columns (nearly 0 for the linear feature, really high for the red stuff), ...
However I was hoping in some help from a tool out there. It doesn't matter if this tool won't cover all cases (for example, will kick out circles), I've been very broad to get the maximum number of inputs from you guys - any tool will be inspiring and helpful (and, however, we can't expect a perfect answer for the deeper question - recognizing regular shapes - which seems more like a AI field of research). I also think that, while being broad, this is totally non-subjective so should fit in SO. Thank you.
Side note 1: I'll deal mostly with elongated, extended features like the top-right one, so circles are not that relevant.
Side note 2: To be 100% clear, I would need something (be it an already existant tool, or some ideas pointed out by you) that acts on the indices of the shapes, in terms of rows-columns into the original image, or on the boundary of the shape itself.
Side note 3: Apart from tools/suggestions/ideas, you are welcomed to write down some lines of code ;) I'm getting the regions as connected components from bwconncomp.
I had to solve a similar problem recently that involved counting the number of indentations on blobs within in an image (basically, the connected components returned by bwconncomp). The method I used was to look at curvature changes along the boundary calculated via the FFT. In your case, the red blobs would have a large number of curvature variations, whereas the black regions would not. It's a pretty easy calculation and relatively fast. The code is on github here:
https://github.com/mjsottile/blobdents
The file of interest is src/countindents.m. A short description of the approach is here:
http://arxiv.org/abs/1501.07692
I went for the easier road as suggested by #Mikhail in comments.
I found out regionprops has a really helpful tool called Solidity. Quoting docs,
Returns a scalar specifying the proportion of the pixels in the convex hull that are also in the region. Computed as Area/ConvexArea.
Convex hull is defined as the smallest convex polygon that can contain the region. So Solidity goes up to 1 if the shape is kind of regular and has no convexity changes; down to 0 for my red shape, which leaves space between itself and the convex polygon.
Of course it never reaches 0, lowest value should belong to a kind of +-shaped sign.

Matlab: Track point on object in video

I would like to track (if that is the right word for this) the movement of a point on an object and return the co-ordinates for the point in each frame to arrays for plotting. How would you go about doing this?
The point on the video is a certain color and so my first effort was to eliminate all other colors and change the part I wish to follow to black and everything else to white. Doing this left me with some areas in the background which are the same color but I wish to ignore them and just focus on the moving point. I do not know where to even begin with this or if I've even been trying to do the right thing so far?
Any help would be greatly appreciated! :)
Try searching for terms like 'tracking', 'morphological', 'computer vision', 'matlab'
Here's a project that I found that will probably get you started.
http://www.mathworks.com/matlabcentral/fileexchange/28757-tracking-red-color-objects-using-matlab
if your object of interests is of a certain specific color. You can always apply a color-filter. To give you a bit of a background, i was trying to track not a point on an object, but a moving object in one of the videos i have. (it was a ping-pong video and my goal was to track the ping-pong ball). My algorithm was simple and fast (as i did not want any of my filters to induce heavy computations at one single frame). The basic idea was to apply a color filter. Similar to other shape filters, if your target is of high similarity to the filter, the response will be distinctive enough for you to notice. In other words, if you minus two objects that are extremely similar, you will get 0, otherwise, it will be far greater than 0.

Jelly physics 3d

I want to ask about jelly physics ( http://www.youtube.com/watch?v=I74rJFB_W1k ), where I can find some good place to start making things like that ? I want to make simulation of cars crash and I want use this jelly physics, but I can't find a lot about them. I don't want use existing physics engine, I want write my own :)
Something like what you see in the video you linked to could be accomplished with a mass-spring system. However, as you vary the number of masses and springs, keeping your spring constants the same, you will get wildly varying results. In short, mass-spring systems are not good approximations of a continuum of matter.
Typically, these sorts of animations are created using what is called the Finite Element Method (FEM). The FEM does converge to a continuum, which is nice. And although it does require a bit more know-how than a mass-spring system, it really isn't too bad. The basic idea, derived from the study of continuum mechanics, can be put this way:
Break the volume of your object up into many small pieces (elements), usually tetrahedra. Let's call the entire collection of these elements the mesh. You'll actually want to make two copies of this mesh. Label one the "rest" mesh, and the other the "world" mesh. I'll tell you why next.
For each tetrahedron in your world mesh, measure how deformed it is relative to its corresponding rest tetrahedron. The measure of how deformed it is is called "strain". This is typically accomplished by first measuring what is known as the deformation gradient (often denoted F). There are several good papers that describe how to do this. Once you have F, one very typical way to define the strain (e) is:
e = 1/2(F^T * F) - I. This is known as Green's strain. It is invariant to rotations, which makes it very convenient.
Using the properties of the material you are trying to simulate (gelatin, rubber, steel, etc.), and using the strain you measured in the step above, derive the "stress" of each tetrahdron.
For each tetrahedron, visit each node (vertex, corner, point (these all mean the same thing)) and average the area-weighted normal vectors (in the rest shape) of the three triangular faces that share that node. Multiply the tetrahedron's stress by that averaged vector, and there's the elastic force acting on that node due to the stress of that tetrahedron. Of course, each node could potentially belong to multiple tetrahedra, so you'll want to be able to sum up these forces.
Integrate! There are easy ways to do this, and hard ways. Either way, you'll want to loop over every node in your world mesh and divide its forces by its mass to determine its acceleration. The easy way to proceed from here is to:
Multiply its acceleration by some small time value dt. This gives you a change in velocity, dv.
Add dv to the node's current velocity to get a new total velocity.
Multiply that velocity by dt to get a change in position, dx.
Add dx to the node's current position to get a new position.
This approach is known as explicit forward Euler integration. You will have to use very small values of dt to get it to work without blowing up, but it is so easy to implement that it works well as a starting point.
Repeat steps 2 through 5 for as long as you want.
I've left out a lot of details and fancy extras, but hopefully you can infer a lot of what I've left out. Here is a link to some instructions I used the first time I did this. The webpage contains some useful pseudocode, as well as links to some relevant material.
http://sealab.cs.utah.edu/Courses/CS6967-F08/Project-2/
The following link is also very useful:
http://sealab.cs.utah.edu/Courses/CS6967-F08/FE-notes.pdf
This is a really fun topic, and I wish you the best of luck! If you get stuck, just drop me a comment.
That rolling jelly cube video was made with Blender, which uses the Bullet physics engine for soft body simulation. The bullet documentation in general is very sparse and for soft body dynamics almost nonexistent. You're best bet would be to read the source code.
Then write your own version ;)
Here is a page with some pretty good tutorials on it. The one you are looking for is probably in the (inverse) Kinematics and Mass & Spring Models sections.
Hint: A jelly can be seen as a 3 dimensional cloth ;-)
Also, try having a look at the search results for spring pressure soft body model - they might get you going in the right direction :-)
See this guy's page Maciej Matyka, topic of soft body
Unfortunately 2d only but might be something to start with is JellyPhysics and JellyCar