Search Results

Search found 321 results on 13 pages for 'intersection'.

Page 5/13 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Algorithm to select groups of similar items in 2d array

    - by mafutrct
    There is a 2d array of items (in my case they are called Intersections). A certain item is given as a start. The task is to find all items directly or indirectly connected to this item that satisfy a certain function. So the basic algorithm is like this: Add the start to the result list. Repeat until no modification: Add each item in the array that satisfies the function and touches any item in the result list to the result list. My current implementation looks like this: private IList<Intersection> SelectGroup ( Intersection start, Func<Intersection, Intersection, bool> select) { List<Intersection> result = new List<Intersection> (); Queue<Intersection> source = new Queue<Intersection> (); source.Enqueue (start); while (source.Any ()) { var s = source.Dequeue (); result.Add (s); foreach (var neighbour in Neighbours (s)) { if (select (start, neighbour) && !result.Contains (neighbour) && !source.Contains (neighbour)) { source.Enqueue (neighbour); } } } Debug.Assert (result.Distinct ().Count () == result.Count ()); Debug.Assert (result.All (x => select (x, result.First ()))); return result; } private List<Intersection> Neighbours (IIntersection intersection) { int x = intersection.X; int y = intersection.Y; List<Intersection> list = new List<Intersection> (); if (x > 1) { list.Add (GetIntersection (x - 1, y)); } if (y > 1) { list.Add (GetIntersection (x, y - 1)); } if (x < Size) { list.Add (GetIntersection (x + 1, y)); } if (y < Size) { list.Add (GetIntersection (x, y + 1)); } return list; } (The select function takes a start item and returns true iff the second item satisfies.) This does its job and turned out to be reasonable fast for the usual array sizes (about 20*20). However, I'm interested in further improvements. Any ideas? Example (X satisfies in relation to other Xs, . does never satisfy): .... XX.. .XX. X... In this case, there are 2 groups: a central group of 4 items and a group of a single item in the lower left. Selecting the group (for instance by starting item [2, 2]) returns the former, while the latter can be selected using the starting item and sole return value [0, 3]. Example 2: .A.. ..BB A.AA This time there are 4 groups. The 3 A groups are not connected, so they are returned as separate groups. The bigger A and B groups are connected, but A does not related to B so they are returned as separate groups.

    Read the article

  • Sliding collision response

    - by dbostream
    I have been reading plenty of tutorials about sliding collision responses yet I am not able to implement it properly in my project. What I want to do is make a puck slide along the rounded corner boards of a hockey rink. In my latest attempt the puck does slide along the boards but there are some strange velocity behaviors. First of all the puck slows down a lot pretty much right away and then it slides for awhile and stops before exiting the corner. Even if I double the speed I get a similar behavior and the puck does not make it out of the corner. I used some ideas from this document http://www.peroxide.dk/papers/collision/collision.pdf. This is what I have: Update method called from the game loop when it is time to update the puck (I removed some irrelevant parts). I use two states (current, previous) which are used to interpolate the position during rendering. public override void Update(double fixedTimeStep) { /* Acceleration is set to 0 for now. */ Acceleration.Zero(); PreviousState = CurrentState; _collisionRecursionDepth = 0; CurrentState.Position = SlidingCollision(CurrentState.Position, CurrentState.Velocity * fixedTimeStep + 0.5 * Acceleration * fixedTimeStep * fixedTimeStep); /* Should not this be affected by a sliding collision? and not only the position. */ CurrentState.Velocity = CurrentState.Velocity + Acceleration * fixedTimeStep; Heading = Vector2.NormalizeRet(CurrentState.Velocity); } private Vector2 SlidingCollision(Vector2 position, Vector2 velocity) { if(_collisionRecursionDepth > 5) return position; bool collisionFound = false; Vector2 futurePosition = position + velocity; Vector2 intersectionPoint = new Vector2(); Vector2 intersectionPointNormal = new Vector2(); /* I did not include the collision detection code, if a collision is detected the intersection point and normal in that point is returned. */ if(!collisionFound) return futurePosition; /* If no collision was detected it is safe to move to the future position. */ /* It is not exactly the intersection point, but slightly before. */ Vector2 newPosition = intersectionPoint; /* oldVelocity is set to the distance from the newPosition(intersection point) to the position it had moved to had it not collided. */ Vector2 oldVelocity = futurePosition - newPosition; /* Project the distance left to move along the intersection normal. */ Vector2 newVelocity = oldVelocity - intersectionPointNormal * oldVelocity.DotProduct(intersectionPointNormal); if(newVelocity.LengthSq() < 0.001) return newPosition; /* If almost no speed, no need to continue. */ _collisionRecursionDepth++; return SlidingCollision(newPosition, newVelocity); } What am I doing wrong with the velocity? I have been staring at this for very long so I have gone blind. I have tried different values of recursion depth but it does not seem to make it better. Let me know if you need more information. I appreciate any help. EDIT: A combination of Patrick Hughes' and teodron's answers solved the velocity problem (I think), thanks a lot! This is the new code: I decided to use a separate recursion method now too since I don't want to recalculate the acceleration in each recursion. public override void Update(double fixedTimeStep) { Acceleration.Zero();// = CalculateAcceleration(fixedTimeStep); PreviousState = new MovingEntityState(CurrentState.Position, CurrentState.Velocity); CurrentState = SlidingCollision(CurrentState, fixedTimeStep); Heading = Vector2.NormalizeRet(CurrentState.Velocity); } private MovingEntityState SlidingCollision(MovingEntityState state, double timeStep) { bool collisionFound = false; /* Calculate the next position given no detected collision. */ Vector2 futurePosition = state.Position + state.Velocity * timeStep; Vector2 intersectionPoint = new Vector2(); Vector2 intersectionPointNormal = new Vector2(); /* I did not include the collision detection code, if a collision is detected the intersection point and normal in that point is returned. */ /* If no collision was detected it is safe to move to the future position. */ if (!collisionFound) return new MovingEntityState(futurePosition, state.Velocity); /* Set new position to the intersection point (slightly before). */ Vector2 newPosition = intersectionPoint; /* Project the new velocity along the intersection normal. */ Vector2 newVelocity = state.Velocity - 1.90 * intersectionPointNormal * state.Velocity.DotProduct(intersectionPointNormal); /* Calculate the time of collision. */ double timeOfCollision = Math.Sqrt((newPosition - state.Position).LengthSq() / (futurePosition - state.Position).LengthSq()); /* Calculate new time step, remaining time of full step after the collision * current time step. */ double newTimeStep = timeStep * (1 - timeOfCollision); return SlidingCollision(new MovingEntityState(newPosition, newVelocity), newTimeStep); } Even though the code above seems to slide the puck correctly please have a look at it. I have a few questions, if I don't multiply by 1.90 in the newVelocity calculation it doesn't work (I get a stack overflow when the puck enters the corner because the timeStep decreases very slowly - a collision is found early in every recursion), why is that? what does 1.90 really do and why 1.90? Also I have a new problem, the puck does not move parallell to the short side after exiting the curve; to be more exact it moves outside the rink (I am not checking for any collisions with the short side at the moment). When I perform the collision detection I first check that the puck is in the correct quadrant. For example bottom-right corner is quadrant four i.e. circleCenter.X < puck.X && circleCenter.Y puck.Y is this a problem? or should the short side of the rink be the one to make the puck go parallell to it and not the last collision in the corner? EDIT2: This is the code I use for collision detection, maybe it has something to do with the fact that I can't make the puck slide (-1.0) but only reflect (-2.0): /* Point is the current position (not the predicted one) and quadrant is 4 for the bottom-right corner for example. */ if (GeometryHelper.PointInCircleQuadrant(circleCenter, circleRadius, state.Position, quadrant)) { /* The line is: from = state.Position, to = futurePosition. So a collision is detected when from is inside the circle and to is outside. */ if (GeometryHelper.LineCircleIntersection2d(state.Position, futurePosition, circleCenter, circleRadius, intersectionPoint, quadrant)) { collisionFound = true; /* Set the intersection point to slightly before the real intersection point (I read somewhere this was good to do because of floting point precision, not sure exactly how much though). */ intersectionPoint = intersectionPoint - Vector2.NormalizeRet(state.Velocity) * 0.001; /* Normal at the intersection point. */ intersectionPointNormal = Vector2.NormalizeRet(circleCenter - intersectionPoint) } } When I set the intersection point, if I for example use 0.1 instead of 0.001 the puck travels further before it gets stuck, but for all values I have tried (including 0 - the real intersection point) it gets stuck somewhere (but I necessarily not get a stack overflow). Can something in this part be the cause of my problem? I can see why I get the stack overflow when using -1.0 when calculating the new velocity vector; but not how to solve it. I traced the time steps used in the recursion (initial time step is always 1/60 ~ 0.01666): Recursion depth Time step next recursive call [Start recursion, time step ~ 0.016666] 0 0,000985806527246773 [No collision, stop recursion] [Start recursion, time step ~ 0.016666] 0 0,0149596704364629 1 0,0144883449376379 2 0,0143155612984837 3 0,014224925727213 4 0,0141673917461608 5 0,0141265435314026 6 0,0140953966184117 7 0,0140704653746625 ...and so on. As you can see the collision is detected early in every recursive call which means the next time step decreases very slowly thus the recursion depth gets very big - stack overflow.

    Read the article

  • 3D Ball Physics Theory: collision response on ground and against walls?

    - by David
    I'm really struggling to get a strong grasp on how I should be handling collision response in a game engine I'm building around a 3D ball physics concept. Think Monkey Ball as an example of the type of gameplay. I am currently using sphere-to-sphere broad phase, then AABB to OBB testing (the final test I am using right now is one that checks if one of the 8 OBB points crosses the planes of the object it is testing against). This seems to work pretty well, and I am getting back: Plane that object is colliding against (with a point on the plane, the plane's normal, and the exact point of intersection. I've tried what feels like dozens of different high-level strategies for handling these collisions, without any real success. I think my biggest problem is understanding how to handle collisions against walls in the x-y axes (left/right, front/back), which I want to have elasticity, and the ground (z-axis) where I want an elastic reaction if the ball drops down, but then for it to eventually normalize and be kept "on the ground" (not go into the ground, but also not continue bouncing). Without kluging something together, I'm positive there is a good way to handle this, my theories just aren't getting me all the way there. For physics modeling and movement, I am trying to use a Euler based setup with each object maintaining a position (and destination position prior to collision detection), a velocity (which is added onto the position to determine the destination position), and an acceleration (which I use to store any player input being put on the ball, as well as gravity in the z coord). Starting from when I detect a collision, what is a good way to approach the response to get the expected behavior in all cases? Thanks in advance to anyone taking the time to assist... I am grateful for any pointers, and happy to post any additional info or code if it is useful. UPDATE Based on Steve H's and eBusiness' responses below, I have adapted my collision response to what makes a lot more sense now. It was close to right before, but I didn't have all the right pieces together at the right time! I have one problem left to solve, and that is what is causing the floor collision to hit every frame. Here's the collision response code I have now for the ball, then I'll describe the last bit I'm still struggling to understand. // if we are moving in the direction of the plane (against the normal)... if (m_velocity.dot(intersection.plane.normal) <= 0.0f) { float dampeningForce = 1.8f; // eventually create this value based on mass and acceleration // Calculate the projection velocity PVRTVec3 actingVelocity = m_velocity.project(intersection.plane.normal); m_velocity -= actingVelocity * dampeningForce; } // Clamp z-velocity to zero if we are within a certain threshold // -- NOTE: this was an experimental idea I had to solve the "jitter" bug I'll describe below float diff = 0.2f - abs(m_velocity.z); if (diff > 0.0f && diff <= 0.2f) { m_velocity.z = 0.0f; } // Take this object to its new destination position based on... // -- our pre-collision position + vector to the collision point + our new velocity after collision * time // -- remaining after the collision to finish the movement m_destPosition = m_position + intersection.diff + (m_velocity * intersection.tRemaining * GAMESTATE->dt); The above snippet is run after a collision is detected on the ball (collider) with a collidee (floor in this case). With a dampening force of 1.8f, the ball's reflected "upward" velocity will eventually be overcome by gravity, so the ball will essentially be stuck on the floor. THIS is the problem I have now... the collision code is running every frame (since the ball's z-velocity is constantly pushing it a collision with the floor below it). The ball is not technically stuck, I can move it around still, but the movement is really goofy because the velocity and position keep getting affected adversely by the above snippet. I was experimenting with an idea to clamp the z-velocity to zero if it was "close to zero", but this didn't do what I think... probably because the very next frame the ball gets a new gravity acceleration applied to its velocity regardless (which I think is good, right?). Collisions with walls are as they used to be and work very well. It's just this last bit of "stickiness" to deal with. The camera is constantly jittering up and down by extremely small fractions too when the ball is "at rest". I'll keep playing with it... I like puzzles like this, especially when I think I'm close. Any final ideas on what I could be doing wrong here? UPDATE 2 Good news - I discovered I should be subtracting the intersection.diff from the m_position (position prior to collision). The intersection.diff is my calculation of the difference in the vector of position to destPosition from the intersection point to the position. In this case, adding it was causing my ball to always go "up" just a little bit, causing the jitter. By subtracting it, and moving that clamper for the velocity.z when close to zero to being above the dot product (and changing the test from <= 0 to < 0), I now have the following: // Clamp z-velocity to zero if we are within a certain threshold float diff = 0.2f - abs(m_velocity.z); if (diff > 0.0f && diff <= 0.2f) { m_velocity.z = 0.0f; } // if we are moving in the direction of the plane (against the normal)... float dotprod = m_velocity.dot(intersection.plane.normal); if (dotprod < 0.0f) { float dampeningForce = 1.8f; // eventually create this value based on mass and acceleration? // Calculate the projection velocity PVRTVec3 actingVelocity = m_velocity.project(intersection.plane.normal); m_velocity -= actingVelocity * dampeningForce; } // Take this object to its new destination position based on... // -- our pre-collision position + vector to the collision point + our new velocity after collision * time // -- remaining after the collision to finish the movement m_destPosition = m_position - intersection.diff + (m_velocity * intersection.tRemaining * GAMESTATE->dt); UpdateWorldMatrix(m_destWorldMatrix, m_destOBB, m_destPosition, false); This is MUCH better. No jitter, and the ball now "rests" at the floor, while still bouncing off the floor and walls. The ONLY thing left is that the ball is now virtually "stuck". He can move but at a much slower rate, likely because the else of my dot product test is only letting the ball move at a rate multiplied against the tRemaining... I think this is a better solution than I had previously, but still somehow not the right idea. BTW, I'm trying to journal my progress through this problem for anyone else with a similar situation - hopefully it will serve as some help, as many similar posts have for me over the years.

    Read the article

  • 2D Rectangle Collision Response with Multiple Rectangles

    - by Justin Skiles
    Similar to: Collision rectangle response I have a level made up of tiles where the edges of the level are made up of collidable rectangles. The player's collision box is represented by a rectangle as well. The player can move in 8 directions. The player's velocity is equal in X and Y directions and constant. Each update, I am checking the player's collision against all tiles that are a certain distance away. When the player collides with a rectangle, I am finding the intersection depth and resolving along the most shallow axis followed by the other axis. This resolution happens for both axes simultaneously. See below for two examples of situations where I am having trouble. Moving up-left against the left wall In the scenario below, the player is colliding with two tiles. The tile intersection depth is equal on both axes for the top tile and more shallow in the X axis for the middle tile. Because the player is moving up the wall, the player should slide in an upward direction along the wall. This works properly as long as the rectangle with the more shallow depth is evaluated first. If the equal intersection depth rectangle is evaluated first, there is a chance the player becomes stuck. Moving up-left against the top wall Here is an identical scenario with the exception that the collision is with the top wall. The same problem occurs at the corners when intersection depth is equal for both axes. I guess my overall question is: How can I ensure that collision response occurs on tiles that have non-equal intersection depth before tiles that have equal intersection depth in order to get around the weirdness that occurs at these corners. Sean's answer in the linked question was good, but his solution required having different velocity components in a certain direction. My situation has equal velocities, so there's no good way to tell which direction to resolve at corners. I hope I have made my explanation clear.

    Read the article

  • What has the most efficient intersection test against an AABB tree - OBB, Cylinder or Capsule?

    - by identitycrisisuk
    I'm currently trying to find collisions in 3D between a tighter volume than an AABB and a tree of AABB volumes. I just need to know whether they are intersecting, no closest distance or collision response. An OBB, Cylinder or Capsule would all roughly fit these purposes but Cylinder and Capsule were the first thing I thought of, which I have found little information about detecting intersections online. Am I right in thinking that they would always be more complex to perform Separating Axis Tests on even though they might seem like simpler shapes? I figure by the time I get my head around SAT for curved shapes I could have done the thing with OBBs but I wanted to find out for sure.

    Read the article

  • How can I solve this SAT direct corner intersection edge case?

    - by ssb
    I have a working SAT implementation, but I am running into a problem where direct collisions at a corner do not work for tiled surfaces. That is, it clips on the surface when going in a certain direction because it gets hung up on one of the tiles, and so, for example, if I walk across a floor while holding both down and left, the player will stop when meeting the next shape because the player will be colliding with the right side rather than with the top of the floor tile. This illustration shows what I mean: The top block will translate right first and then up. I have checked here and here which are helpful, but this does not address what I should do in a situation where I don't have a tile-based world. My usage of the term "tile" before isn't really accurate since what I'm doing here is manually placing square obstacles next to each other, not assigning them spots on a grid. What can I do to fix this?

    Read the article

  • How to find control points for a BezierSegment given Start, End, and 2 Intersection Pts in C# - AKA

    - by softwarequestioneer
    Hi, I've been struggling looking for an understandable way to do this. I have four points, a StartPt, EndPoint, and Intersection points to represent the peak and valley in the bezier. The BezierSegment in C# requires start, controlPoint 1, controlPoint 2, endpoint - however I don't have any control points I only have these two points that lie along the bezier curves (i'm calling them intersection points above)... how can I calculate the two control points? Thanks in advance, this has been driving me crazy. There's some kind of explanation here: http://www.tinaja.com/glib/nubz4pts1.pdf but it's written in postscript and that language makes no sense to me at all - it's over my head.

    Read the article

  • Getting 2D Platformer entity collision Response Correct (side-to-side + jumping/landing on heads)

    - by jbrennan
    I've been working on a 2D (tile based) 2D platformer for iOS and I've got basic entity collision detection working, but there's just something not right about it and I can't quite figure out how to solve it. There are 2 forms of collision between player entities as I can tell, either the two players (human controlled) are hitting each other side-to-side (i. e. pushing against one another), or one player has jumped on the head of the other player (naturally, if I wanted to expand this to player vs enemy, the effects would be different, but the types of collisions would be identical, just the reaction should be a little different). In my code I believe I've got the side-to-side code working: If two entities press against one another, then they are both moved back on either side of the intersection rectangle so that they are just pushing on each other. I also have the "landed on the other player's head" part working. The real problem is, if the two players are currently pushing up against each other, and one player jumps, then at one point as they're jumping, the height-difference threshold that counts as a "land on head" is passed and then it registers as a jump. As a life-long player of 2D Mario Bros style games, this feels incorrect to me, but I can't quite figure out how to solve it. My code: (it's really Objective-C but I've put it in pseudo C-style code just to be simpler for non ObjC readers) void checkCollisions() { // For each entity in the scene, compare it with all other entities (but not with one it's already compared against) for (int i = 0; i < _allGameObjects.count(); i++) { // GameObject is an Entity GEGameObject *firstGameObject = _allGameObjects.objectAtIndex(i); // Don't check against yourself or any previous entity for (int j = i+1; j < _allGameObjects.count(); j++) { GEGameObject *secondGameObject = _allGameObjects.objectAtIndex(j); // Get the collision bounds for both entities, then see if they intersect // CGRect is a C-struct with an origin Point (x, y) and a Size (w, h) CGRect firstRect = firstGameObject.collisionBounds(); CGRect secondRect = secondGameObject.collisionBounds(); // Collision of any sort if (CGRectIntersectsRect(firstRect, secondRect)) { //////////////////////////////// // // // Check for jumping first (???) // // //////////////////////////////// if (firstRect.origin.y > (secondRect.origin.y + (secondRect.size.height * 0.7))) { // the top entity could be pretty far down/in to the bottom entity.... firstGameObject.didLandOnEntity(secondGameObject); } else if (secondRect.origin.y > (firstRect.origin.y + (firstRect.size.height * 0.7))) { // second entity was actually on top.... secondGameObject.didLandOnEntity.(firstGameObject); } else if (firstRect.origin.x > secondRect.origin.x && firstRect.origin.x < (secondRect.origin.x + secondRect.size.width)) { // Hit from the RIGHT CGRect intersection = CGRectIntersection(firstRect, secondRect); // The NUDGE just offsets either object back to the left or right // After the nudging, they are exactly pressing against each other with no intersection firstGameObject.nudgeToRightOfIntersection(intersection); secondGameObject.nudgeToLeftOfIntersection(intersection); } else if ((firstRect.origin.x + firstRect.size.width) > secondRect.origin.x) { // hit from the LEFT CGRect intersection = CGRectIntersection(firstRect, secondRect); secondGameObject.nudgeToRightOfIntersection(intersection); firstGameObject.nudgeToLeftOfIntersection(intersection); } } } } } I think my collision detection code is pretty close, but obviously I'm doing something a little wrong. I really think it's to do with the way my jumps are checked (I wanted to make sure that a jump could happen from an angle (instead of if the falling player had been at a right angle to the player below). Can someone please help me here? I haven't been able to find many resources on how to do this properly (and thinking like a game developer is new for me). Thanks in advance!

    Read the article

  • How can I find the nearest intersection via the Google Maps API?

    - by dusoft
    How can I find the closest intersection of the street I have coordinates of? For instance, say I have street A running from south to north that is crossed by street X on the north and by street Y on the south. Does the Google Maps API allow for finding coordinates of the nearest crossroad (either X or Y) of street A? I couldn't find it mentioned anywhere. PS: The only solution I am aware of is to guess the lowest number and the highest number of building on the street A and to draw polyline between them. I am not sure about this though.

    Read the article

  • Does Quartz2D test intersection of rect by line before drawing it.

    - by ddnv
    I'm drawing a big scheme that consist of a lot of lines. I do it in the drawRect: method of UIView. The scheme is larger than the layer of view and I check each line and draw it only if it intersects the visible rect. But at one moment I thought, should I do this? Maybe Quartz is already doing this test? So the question is: When I use function CGContextAddLineToPoint() does the Core Graphics tests this line for intersection with layer rect or it just draw it anyway?

    Read the article

  • Narrow-phase collision detection algorithms

    - by Marian Ivanov
    There are three phases of collision detection. Broadphase: It loops between all objecs that can interact, false positives are allowed, if it would speed up the loop. Narrowphase: Determines whether they collide, and sometimes, how, no false positives Resolution: Resolves the collision. The question I'm asking is about the narrowphase. There are multiple algorithms, differing in complexity and accuracy. Hitbox intersection: This is an a-posteriori algorithm, that has the lowest complexity, but also isn't too accurate, Color intersection: Hitbox intersection for each pixel, a-posteriori, pixel-perfect, not accuratee in regards to time, higher complexity Separating axis theorem: This is used more often, accurate for triangles, however, a-posteriori, as it can't find the edge, when taking last frame in account, it's more stable Linear raycasting: A-priori algorithm, useful for semi-realistic-looking physics, finds the intersection point, even more accurate than SAT, but with more complexity Spline interpolation: A-priori, even more accurate than linear rays, even more coplexity. There are probably many more that I've forgot about. The question is, in when is it better to use SAT, when rays, when splines, and whether there is anything better.

    Read the article

  • How to do buffered intersection checks on an IPoint?

    - by Quigrim
    How would I buffer an IPoint to do an intersection check using IRelationalOperator? I have, for arguments sake: IPoint p1 = xxx; IPoint p2 = yyy; IRelationalOperator rel1 = (IRelationalOperator)p1; if (rel.Intersects (p2)) // Do something But now I want to add a tolerance to my check, so I assume the right way to do that is by either buffering p1 or p2. Right? How do I add such a buffer? Note: the Intersects method I am using is an extension method I wrote to simplify my code. Here it is: /// <summary> /// Returns true if the IGeometry is intersected. /// This method negates the Disjoint method. /// </summary> /// <param name="relOp">The rel op.</param> /// <param name="other">The other.</param> /// <returns></returns> public static bool Intersects ( this IRelationalOperator relOp, IGeometry other) { return (!relOp.Disjoint (other)); }

    Read the article

  • How to buffer an IPoint or IGeometry? (How to do buffered intersection checks on an IPoint?)

    - by Quigrim
    How would I buffer an IPoint to do an intersection check using IRelationalOperator? I have, for arguments sake: IPoint p1 = xxx; IPoint p2 = yyy; IRelationalOperator rel1 = (IRelationalOperator)p1; if (rel.Intersects (p2)) // Do something But now I want to add a tolerance to my check, so I assume the right way to do that is by either buffering p1 or p2. Right? How do I add such a buffer? Note: the Intersects method I am using is an extension method I wrote to simplify my code. Here it is: /// <summary> /// Returns true if the IGeometry is intersected. /// This method negates the Disjoint method. /// </summary> /// <param name="relOp">The rel op.</param> /// <param name="other">The other.</param> /// <returns></returns> public static bool Intersects ( this IRelationalOperator relOp, IGeometry other) { return (!relOp.Disjoint (other)); }

    Read the article

  • DB Architecture : Linking to intersection or to main tables?

    - by Jean-Nicolas
    Hi, I'm creating fantasy football system on my website but i'm very confuse about how I should link some of my table. Tables The main table is Pool which have all the info about the ruling of the fantasy draft. A standard table User, which contains the usual stuff. Intersection table called pools_users which contains id,pool_id,user_id because a user could be in more than one pool, and a pool contains more than 1 user. The problem Table Selections = that's the table that is causing problem. That's the selection that the user choose for his pool. This is related to the Player table but thats not relevant for this problem. Should I link this table to the table Pools_users or should I link it with both main table Pool and User. This table contains id,pool_id,user_id,player_id,... What is the best way link my tables? When I want to retrieve my data, I normally want the information to be divided BY users. "This user have those selections, this one those selections, etc).

    Read the article

  • OpenGL render vs. own Phong Illumination Implementation

    - by Myx
    Hello: I have implemented a Phong Illumination Scheme using a camera that's centered at (0,0,0) and looking directly at the sphere primitive. The following are the relevant contents of the scene file that is used to view the scene using OpenGL as well as to render the scene using my own implementation: ambient 0 1 0 dir_light 1 1 1 -3 -4 -5 # A red sphere with 0.5 green ambiance, centered at (0,0,0) with radius 1 material 0 0.5 0 1 0 0 1 0 0 0 0 0 0 0 0 10 1 0 sphere 0 0 0 0 1 The resulting image produced by OpenGL. The image that my rendering application produces. As you can see, there are various differences between the two: The specular highlight on my image is smaller than the one in OpenGL. The diffuse surface seems to not diffuse in the correct way, resulting in the yellow region to be unneccessarily large in my image, whereas in OpenGL there's a nice dark green region closer to the bottom of the sphere The color produced by OpenGL is much darker than the one in my image. Those are the most prominent three differences that I see. The following is my implementation of the Phong illumination: R3Rgb Phong(R3Scene *scene, R3Ray *ray, R3Intersection *intersection) { R3Rgb radiance; if(intersection->hit == 0) { radiance = scene->background; return radiance; } R3Vector normal = intersection->normal; R3Rgb Kd = intersection->node->material->kd; R3Rgb Ks = intersection->node->material->ks; // obtain ambient term R3Rgb intensity_ambient = intersection->node->material->ka*scene->ambient; // obtain emissive term R3Rgb intensity_emission = intersection->node->material->emission; // for each light in the scene, obtain calculate the diffuse and specular terms R3Rgb intensity_diffuse(0,0,0,1); R3Rgb intensity_specular(0,0,0,1); for(unsigned int i = 0; i < scene->lights.size(); i++) { R3Light *light = scene->Light(i); R3Rgb light_color = LightIntensity(scene->Light(i), intersection->position); R3Vector light_vector = -LightDirection(scene->Light(i), intersection->position); // calculate diffuse reflection intensity_diffuse += Kd*normal.Dot(light_vector)*light_color; // calculate specular reflection R3Vector reflection_vector = 2.*normal.Dot(light_vector)*normal-light_vector; reflection_vector.Normalize(); R3Vector viewing_vector = ray->Start() - intersection->position; viewing_vector.Normalize(); double n = intersection->node->material->shininess; intensity_specular += Ks*pow(max(0.,viewing_vector.Dot(reflection_vector)),n)*light_color; } radiance = intensity_emission+intensity_ambient+intensity_diffuse+intensity_specular; return radiance; } Here are the related LightIntensity(...) and LightDirection(...) functions: R3Vector LightDirection(R3Light *light, R3Point position) { R3Vector light_direction; switch(light->type) { case R3_DIRECTIONAL_LIGHT: light_direction = light->direction; break; case R3_POINT_LIGHT: light_direction = position-light->position; break; case R3_SPOT_LIGHT: light_direction = position-light->position; break; } light_direction.Normalize(); return light_direction; } R3Rgb LightIntensity(R3Light *light, R3Point position) { R3Rgb light_intensity; double distance; double denominator; if(light->type != R3_DIRECTIONAL_LIGHT) { distance = (position-light->position).Length(); denominator = light->constant_attenuation + light->linear_attenuation*distance + light->quadratic_attenuation*distance*distance; } switch(light->type) { case R3_DIRECTIONAL_LIGHT: light_intensity = light->color; break; case R3_POINT_LIGHT: light_intensity = light->color/denominator; break; case R3_SPOT_LIGHT: R3Vector from_light_to_point = position - light->position; light_intensity = light->color*( pow(light->direction.Dot(from_light_to_point), light->angle_attenuation)); break; } return light_intensity; } I would greatly appreciate any suggestions as to any implementation errors that are apparent. I am wondering if the differences could be occurring simply because of the gamma values used for display by OpenGL and the default gamma value for my display. I also know that OpenGL (or at least tha parts that I was provided) can't cast shadows on objects. Not that this is relevant for the point in question, but it just leads me to wonder if it's simply display and capability differences between OpenGL and what I am trying to do. Thank you for your help.

    Read the article

  • Implementing set operations in TSQL

    - by dotneteer
    SQL excels at operating on dataset. In this post, I will discuss how to implement basic set operations in transact SQL (TSQL). The operations that I am going to discuss are union, intersection and complement (subtraction).   Union Intersection Complement (subtraction) Implementing set operations using union, intersect and except We can use TSQL keywords union, intersect and except to implement set operations. Since we are in an election year, I will use voter records of propositions as an example. We create the following table and insert 6 records into the table. declare @votes table (VoterId int, PropId int) insert into @votes values (1, 30) insert into @votes values (2, 30) insert into @votes values (3, 30) insert into @votes values (4, 30) insert into @votes values (4, 31) insert into @votes values (5, 31) Voters 1, 2, 3 and 4 voted for proposition 30 and voters 4 and 5 voted for proposition 31. The following TSQL statement implements union using the union keyword. The union returns voters who voted for either proposition 30 or 31. select VoterId from @votes where PropId = 30 union select VoterId from @votes where PropId = 31 The following TSQL statement implements intersection using the intersect keyword. The intersection will return voters who voted only for both proposition 30 and 31. select VoterId from @votes where PropId = 30 intersect select VoterId from @votes where PropId = 31 The following TSQL statement implements complement using the except keyword. The complement will return voters who voted for proposition 30 but not 31. select VoterId from @votes where PropId = 30 except select VoterId from @votes where PropId = 31 Implementing set operations using join An alternative way to implement set operation in TSQL is to use full outer join, inner join and left outer join. The following TSQL statement implements union using full outer join. select Coalesce(A.VoterId, B.VoterId) from (select VoterId from @votes where PropId = 30) A full outer join (select VoterId from @votes where PropId = 31) B on A.VoterId = B.VoterId The following TSQL statement implements intersection using inner join. select Coalesce(A.VoterId, B.VoterId) from (select VoterId from @votes where PropId = 30) A inner join (select VoterId from @votes where PropId = 31) B on A.VoterId = B.VoterId The following TSQL statement implements complement using left outer join. select Coalesce(A.VoterId, B.VoterId) from (select VoterId from @votes where PropId = 30) A left outer join (select VoterId from @votes where PropId = 31) B on A.VoterId = B.VoterId where B.VoterId is null Which one to choose? To choose which technique to use, just keep two things in mind: The union, intersect and except technique treats an entire record as a member. The join technique allows the member to be specified in the “on” clause. However, it is necessary to use Coalesce function to project sets on the two sides of the join into a single set.

    Read the article

  • Set Covering : Runtime hang\error at function call in c

    - by EnthuCrazy
    I am implementing a set covering application which uses cover function int cover(set *skill_list,set *player_list,set *covering) Suppose skill_set={a,b,c,d,e}, player_list={s1,s2,s3} then output coverin ={s1,s3} where say s1={a,b,c}, s3={d,e} and s2={b,d}. Now when I am calling this function it's hanging at run (set_cover.exe stopped working). Here is my cover function: typedef struct Spst_{ void *key; set *st; }Spst; int cover(set *skill_list,set *player_list,set *covering) { Liste *member,*max_member; Spst *subset; set *intersection; void **data; int max_size; set_init(covering); //to initialize set covering initially while(skill_list->size>0&&player_list->size>0) { max_size=0; for(member=player_list->head;member!=NULL;member=member->next) { if(set_intersection(intersection,((Spst *)(member->data))->st,skill_list)!=0) return -1; if(intersection->size>max_size) { max_member=member; max_size=intersection->size; } set_destroy(intersection); //at the end of iteration } if(max_size==0) //to check for no covering return -1; subset=(Spst *)max_member->data; //to insert max subset from play list to covering set set_inselem(covering,subset); for(member=(((Spst *)max_member->data)->st->head);member!=NULL;member=member->next) //to rem elem from skill list { data=(void **)member->data; set_remelem(skill_list,data); } set_remelem(player_list,(void **)subset); //to rem subset from set of subsets play list } if(skill_list->size>0) return -1; return 0; } Now assuming I have defined three set type sets(as stated above) and calling from main as cover(skills,subsets,covering);=> runtime hang Here Please give inputs on the missing link in this or the prerequisites for a proper call to this function type required. EDIT: Assume other functions used in cover are tested and working fine.

    Read the article

  • Ray Intersecting Plane Formula in C++/DirectX

    - by user4585
    I'm developing a picking system that will use rays that intersect volumes and I'm having trouble with ray intersection versus a plane. I was able to figure out spheres fairly easily, but planes are giving me trouble. I've tried to understand various sources and get hung up on some of the variables used within their explanations. Here is a snippet of my code: bool Picking() { D3DXVECTOR3 vec; D3DXVECTOR3 vRayDir; D3DXVECTOR3 vRayOrig; D3DXVECTOR3 vROO, vROD; // vect ray obj orig, vec ray obj dir D3DXMATRIX m; D3DXMATRIX mInverse; D3DXMATRIX worldMat; // Obtain project matrix D3DXMATRIX pMatProj = CDirectXRenderer::GetInstance()->Director()->Proj(); // Obtain mouse position D3DXVECTOR3 pos = CGUIManager::GetInstance()->GUIObjectList.front().pos; // Get window width & height float w = CDirectXRenderer::GetInstance()->GetWidth(); float h = CDirectXRenderer::GetInstance()->GetHeight(); // Transform vector from screen to 3D space vec.x = (((2.0f * pos.x) / w) - 1.0f) / pMatProj._11; vec.y = -(((2.0f * pos.y) / h) - 1.0f) / pMatProj._22; vec.z = 1.0f; // Create a view inverse matrix D3DXMatrixInverse(&m, NULL, &CDirectXRenderer::GetInstance()->Director()->View()); // Determine our ray's direction vRayDir.x = vec.x * m._11 + vec.y * m._21 + vec.z * m._31; vRayDir.y = vec.x * m._12 + vec.y * m._22 + vec.z * m._32; vRayDir.z = vec.x * m._13 + vec.y * m._23 + vec.z * m._33; // Determine our ray's origin vRayOrig.x = m._41; vRayOrig.y = m._42; vRayOrig.z = m._43; D3DXMatrixIdentity(&worldMat); //worldMat = aliveActors[0]->GetTrans(); D3DXMatrixInverse(&mInverse, NULL, &worldMat); D3DXVec3TransformCoord(&vROO, &vRayOrig, &mInverse); D3DXVec3TransformNormal(&vROD, &vRayDir, &mInverse); D3DXVec3Normalize(&vROD, &vROD); When using this code I'm able to detect a ray intersection via a sphere, but I have questions when determining an intersection via a plane. First off should I be using my vRayOrig & vRayDir variables for the plane intersection tests or should I be using the new vectors that are created for use in object space? When looking at a site like this for example: http://www.tar.hu/gamealgorithms/ch22lev1sec2.html I'm curious as to what D is in the equation AX + BY + CZ + D = 0 and how does it factor in to determining a plane intersection? Any help will be appreciated, thanks.

    Read the article

  • Great projects, works, people in intersection of programming and art/music?

    - by jacob
    In a recent question I was introduced to the work of André Michelle, which blew me away. What other great people or works do you know in the fields of art and music? As someone with a love for math/programming and art/music I'd love to know more about people using sophisticated (or not so sophisticated) techniques to produce creative things. The software used can be anything from Max/MSP, Flash to simple C code or Assembler. Pointers to forums, blogs, newsletters and similar are very appreciated as well.

    Read the article

  • Can this rectangle to rectangle intersection code still work?

    - by Jeremy Rudd
    I was looking for a fast performing code to test if 2 rectangles are intersecting. A search on the internet came up with this one-liner (WOOT!), but I don't understand how to write it in Javascript, it seems to be written in an ancient form of C++. Can this thing still work? Can you make it work? struct { LONG left; LONG top; LONG right; LONG bottom; } RECT; bool IntersectRect(const RECT * r1, const RECT * r2) { return ! ( r2->left > r1->right || r2->right left || r2->top > r1->bottom || r2->bottom top ); }

    Read the article

  • Given two lines on a plane, how to find integer points closest to their intersection?

    - by Lukasz Lew
    I can't solve it: You are given 8 integers: A, B, C representing a line on a plane with equation A*x + B*y = C a, b, c representing another line x, y representing a point on a plane The two lines are not parallel therefore divide plane into 4 pieces. Point (x, y) lies inside of one these pieces. Problem: Write a fast algorithm that will find a point with integer coordinates in the same piece as (x,y) that is closest to the cross point of the two given lines. Note: This is not a homework, this is old Euler-type task that I have absolutely no idea how to approach. Update: You can assume that the 8 numbers on input are 32-bit signed integers. But you cannot assume that the solution will be 32 bit.

    Read the article

  • Pointers to Derived Class Objects Losing vfptr

    - by duckworthd
    To begin, I am trying to write a run-of-the-mill, simple Ray Tracer. In my Ray Tracer, I have multiple types of geometries in the world, all derived from a base class called "SceneObject". I've included the header for it here. /** Interface for all objects that will appear in a scene */ class SceneObject { public: mat4 M, M_inv; Color c; SceneObject(); ~SceneObject(); /** The transformation matrix to be applied to all points of this object. Identity leaves the object in world frame. */ void setMatrix(mat4 M); void setMatrix(MatrixStack mStack); void getMatrix(mat4& M); /** The color of the object */ void setColor(Color c); void getColor(Color& c); /** Alter one portion of the color, leaving the rest as they were. */ void setDiffuse(vec3 rgb); void setSpecular(vec3 rgb); void setEmission(vec3 rgb); void setAmbient(vec3 rgb); void setShininess(double s); /** Fills 'inter' with information regarding an intersection between this object and 'ray'. Ray should be in world frame. */ virtual void intersect(Intersection& inter, Ray ray) = 0; /** Returns a copy of this SceneObject */ virtual SceneObject* clone() = 0; /** Print information regarding this SceneObject for debugging */ virtual void print() = 0; }; As you can see, I've included a couple virtual functions to be implemented elsewhere. In this case, I have only two derived class -- Sphere and Triangle, both of which implement the missing member functions. Finally, I have a Parser class, which is full of static methods that do the actual "Ray Tracing" part. Here's a couple snippets for relevant portions void Parser::trace(Camera cam, Scene scene, string outputFile, int maxDepth) { int width = cam.getNumXPixels(); int height = cam.getNumYPixels(); vector<vector<vec3>> colors; colors.clear(); for (int i = 0; i< width; i++) { vector<vec3> ys; for (int j = 0; j<height; j++) { Intersection intrsct; Ray ray; cam.getRay(ray, i, j); vec3 color; printf("Obtaining color for Ray[%d,%d]\n", i,j); getColor(color, scene, ray, maxDepth); ys.push_back(color); } colors.push_back(ys); } printImage(colors, width, height, outputFile); } void Parser::getColor(vec3& color, Scene scene, Ray ray, int numBounces) { Intersection inter; scene.intersect(inter,ray); if(inter.isIntersecting()){ Color c; inter.getColor(c); c.getAmbient(color); } else { color = vec3(0,0,0); } } Right now, I've forgone the true Ray Tracing part and instead simply return the color of the first object hit, if any. As you have no doubt noticed, the only way the computer knows that a ray has intersected an object is through Scene.intersect(), which I also include. void Scene::intersect(Intersection& i, Ray r) { Intersection result; result.setDistance(numeric_limits<double>::infinity()); result.setIsIntersecting(false); double oldDist; result.getDistance(oldDist); /* Cycle through all objects, making result the closest one */ for(int ind=0; ind<objects.size(); ind++){ SceneObject* thisObj = objects[ind]; Intersection betterIntersect; thisObj->intersect(betterIntersect, r); double newDist; betterIntersect.getDistance(newDist); if (newDist < oldDist){ result = betterIntersect; oldDist = newDist; } } i = result; } Alright, now for the problem. I begin by creating a scene and filling it with objects outside of the Parser::trace() method. Now for some odd reason, I cast Ray for i=j=0 and everything works wonderfully. However, by the time the second ray is cast all of the objects stored in my Scene no longer recognize their vfptr's! I stepped through the code with a debugger and found that the information to all the vfptr's are lost somewhere between the end of getColor() and the continuation of the loop. However, if I change the arguments of getColor() to use a Scene& instead of a Scene, then no loss occurs. What crazy voodoo is this?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >