Modifying set_Basis values for a transform in Revit - c#

I am using a transform in Revit to show elevation views of individual beams (for the purpose of detailing). This works fine as long as the beam is flat (identical start and end offsets), but if I have a beam that is sloping, I am forced to "flatten" the endpoints.
I tried to define a unit vector along the actual start/end points, and a perpendicular to that vector on an XY plane running through the defined ".Origin" of the transform. I then used simple equations to define a normal to those two vectors...
double newx = first.Y * second.Z - first.Z * second.Y;
double newy = first.Z * second.X - first.X * second.Z;
double newz = first.X * second.Y - first.Y * second.X;
double vectlong = Math.Sqrt(newx * newx + newy * newy + newz * newz);
XYZ normal = new Autodesk.Revit.DB.XYZ(newx / vectlong, newy / vectlong, newz / vectlong);
I then used those three vectors as my ".set_Basis" 0, 1 & 2.
This code works as long as I've forced the beam's start and end points to be flat (which shows that the generated "normal" is valid), but when I remove the code to flatten and use the actual Z values of the endpoints of a sloping beam, the program fails when I try to use these values.
The SDK sample to generate a section through the middle of a beam (CreateViewSection) seems to have found the same problem, but the programmer gave up and simply forces the program to accept only beams that are already on the same XY plane, which is not really the "rule" for beams.
I exported the calculated values of my three vectors and verified that they were all unit length and orthonormal, which should be all that is required for the transform. Can anyone explain why these basis values fail?

Please use this code to set assembly transform. It will align assembly origin and axis properly so that assembly views are always aligned to XYZ axis!
var assyTransform = Transform.Identity;
var beamInst = mainElement as FamilyInstance;
if( beamInst != null )
{
assyTransform = beamInst.GetTransform();
assyTransform.Origin = ( assyInstance.Location as LocationPoint ).Point;
}
if ( !assyInstance.GetTransform()
.AlmostEqual( assyTransform ) )
{
assyInstance.SetTransform( assyTransform );
return true;
}

Related

Properly getting linear depth with a non-GLM projection matrix

I'm porting over a C++ volumetric clustered rendering engine to C#, and the code is here: https://github.com/Kermalis/HybridRenderingEngine-CS
Now, I'm trying to get a linear depth from the current fragment, because it is required for volumetric clustered rendering.
If you're using GLM to create the projection matrix, this is easy with the following equation in your shader:
float ndc = 2.0 * depthSample - 1.0;
float linear = 2.0 * zNear * zFar / (zFar + zNear - ndc * (zFar - zNear));
return linear;
This is because GLM projection matrices are created this way:
float num = (float)Math.Tan(fovy / 2f);
mat4 result = mat4.identity();
result[0, 0] = 1f / (aspect * num);
result[1, 1] = 1f / num;
result[2, 2] = (-(zFar + zNear)) / (zFar - zNear);
result[2, 3] = -1f;
result[3, 2] = (-2f * zFar * zNear) / (zFar - zNear);
However, with C# Matrix4x4, the projection matrix is created differently:
float num = (float)Math.Tan(fieldOfView * 0.5f);
float yScale = 1f / num;
float xScale = yScale / aspectRatio;
result.M11 = xScale;
result.M22 = yScale;
result.M33 = zFar / (zNear - zFar);
result.M34 = -1f;
result.M43 = zNear * zFar / (zNear - zFar);
M33 and M43 are different than GLM's. There are more differences if you create an "off center" projection matrix as well, but I'm not sure if they will make a difference.
The issue, is when you use that same shader code with the Matrix4x4 matrices, you get incorrect values.
If you do the math, you can find why that is:
Here's what you get with 1 Near, 300 Far:
And here's what you get with 0.1 Near, 1500 Far:
Sorry for my handwriting. C1 is M33, and C2 is M43.
You can see that when you divide C1 by C2, you get different depth values for the different projection matrices. So the shader code will not work with Matrix4x4, since it is not actually transforming it to where 0 = near, 1 = far, since the parts of the matrix are different and distribute a different depth curve.
I did find that multiplying by 0.5 will fix it for some near/far values, and you can see that it is close to half difference in my drawings between the two types.
What I want to know is, how would I get depth properly with these matrices in the shader, without having to multiply each fragment by the inverse projection matrix? That's being done in the compute shader (which is why I need the same linear result), but that only gets run one time, not every frame, so I don't care about performance there.
How is the first equation derived? If that becomes clear to me (trust me, I tried to make sense of it), then another one can be created for Matrix4x4, or any other custom one that is passed in. I know an inverse projection matrix will do the trick, but it'll be awfully slow. I can't think of any other robust solution that will cover any matrix. I just don't understand how that shader equation is created or how it applies the inverse.

How to plot an ellipse with given rotation angle in C# WPF using Oxyplot?

OxyPlot is a cross-platform plotting library for .NET, very convenient for making plots,
Now there's a situation here, I have to draw a 95% confidence ellipse to an XY scatter plot.
Oxyplot provides with following annotation:-
Given here Ellipse Annotation(OxyPlot.Annotations) gives only following properties to add ellipse-
We don't have any rotation property or method here, IRender provides several draw methods to override but none of the methods have double angled rotation argument or so. Neither the documentation has provides any direct solution to it:-
Then how to draw this:-
*I was facing this issue for one of my assignment, and came up with a solution after going through the following forums discussion to get hints on how to generate such an ellipse.
https://github.com/oxyplot/oxyplot/issues/268
https://oxyplot.userecho.com/en/communities/1/topics/598-ellipse-annotation-rotation
Please add more solutions if anyone else has :-
Based on the link shared (in Quest.) best and easiest solution here was to draw an ellipse using PolygonAnnotation, which takes List of co-ordinate points,
Let's say if you give four co-ordinate points A,B,C,D--- polygonAnnotation will give me a closed 4-gon~quadrilateral sort of structure based on kind of points taken.
Now if you increase the number of points from 4 to 6--- it will give you hexagon, and so on.
Now at pixel level you can give infinite-number/discrete-number of points eclipsing over 360 degree.
So here we need an algorithm/equation of point on an 2D ellipse- given following inputs (based on this case):-
Center of ellipse (h,k)
rotation angle of the ellipse axis
major axis (a)
minor axis (b)
theta angle from the x-axis
private void GeneratePolygonAsEllipse(PolygonAnnotation polygonAnnotation)
{
double step = 2 * Math.PI / 200;
var h = xCenter;
var k = yCenter;
var rotation = AngleOfRotation;
var a = MajorAxisLength;
var b = MinorAxisLength;
for (double theta = 0; theta < 2 * Math.PI; theta += step)
{
var x = a * Math.Cos(rotation) * Math.Cos(theta) + b * Math.Sin(rotation) * Math.Sin(theta) + h;
var y = b * Math.Cos(rotation) * Math.Sin(theta) + a * Math.Sin(rotation) * Math.Cos(theta) + k;
polygonAnnotation.Points.Add(new DataPoint(x, y));
}
}
I hope above stipulated sample method equation can be useful to other folks like me looking for solution. I couldn't find direct solution anywhere else so I have added my solution here, that can be used as reference.
Result:-
if anyone can come-up with other solutions like how to use IRender or anything else, would be great to look at them.

Making a Pen's LineCap go more into the drawn Line/Curve

Currently I have the following code:
AdjustableArrowCap arrow = new AdjustableArrowCap(10, 15, false);
penStateOutline.CustomEndCap = arrow;
And it draws this:
I have tried all day to make the arrow point to the ellipse itself rather than the center of it..
Update (I was wrong about the cap extending the line; it doesn't!)
To let the line and its cap end at the cirlce's outside you need to make the line shorter by the radius of the circle.
There are two approaches:
You can find a new endpoint that sits on the circle by calculating it, either with Pythagoras or by trigonometry. Then replace the endpoint, i.e. the circle's center, when drawing the line or curve by that new point.
Or put the other way round: You need to calculate a point on the circle as the new endpoint of the line.
It requires a little math, unless the line is horizontal or vertical...
This will work well for straight lines but for curves it may cause considerable changes in the shape, depending on how close the points get and how curved the shape is.
This may or may not be a problem.
To avoid it you can replace the curve points by a series of line points that are close enough to look like a curve when drawn. From the list of points we subtract all those that do not lie inside the circle.
This sounds more complicated than it is as there is a nice class called GraphicsPath that will allow you to add a curve and then flatten it. The result is a more or less large number of points. The same class also allows you to determine whether a point lies inside a shape, i.e. our case inside the circle.
To implement the latter approach, here is a routine that transforms a list of curve points to a list of line points that will end close to the circle..:
void FlattenCurveOutside(List<Point> points, float radius)//, int count)
{
using (GraphicsPath gp = new GraphicsPath())
using (GraphicsPath gpc = new GraphicsPath())
{
// firt create a path that looks like our circle:
PointF l = points.Last();
gpc.AddEllipse(l.X - radius, l.Y - radius, radius * 2, radius* 2);
// next one that holds the curve:
gp.AddCurve(points.ToArray());
// now we flatten it to a not too large number of line segments:
Matrix m = new Matrix(); // dummy matrix
gp.Flatten(m, 0.75f); // <== play with this param!!
// now we test the pathpoints from bach to front until we have left the circle:
int k = -1;
for (int i = gp.PathPoints.Length - 1; i >= 0; i--)
{
if ( !gpc.IsVisible(gp.PathPoints[i])) k = i;
if (k > 0) break;
}
// now we know how many pathpoints we want to retain:
points.Clear();
for (int i = 1; i <= k; i++)
points.Add(Point.Round(gp.PathPoints[i]));
}
}
Note that when the last part of the curve is too straight the result may look a little jagged..
Update 2
To implement the former approach here is a function that returns a PointF on a circle of radius r and a line connecting a Point b with the circle center c:
PointF Intersect(Point c, Point a, int rad)
{
float dx = c.X - a.X;
float dy = c.Y - a.Y;
var radians = Math.Atan2(dy, dx);
var angle = 180 - radians * (180 / Math.PI);
float alpha = (float)(angle * Math.PI / 180f);
float ry = (float)(Math.Sin(alpha) * rad );
float rx = (float)(Math.Cos(alpha) * rad );
return new PointF(c.X + rx, c.Y - ry);
}
The result thankfully looks rather similar:
The math can be simplified a little..
To apply it you can get the new endpoint and replace the old one:
PointF I = Intersect(c, b, r);
points2[points2.Count - 1] = Point.Round(I);
Thank you so much to #TaW for helping.
Unfortunately the answer he provided did not match my stupid OCD..
You made me think about the problem from a different perspective and I now have found a solution that I'll share if anyone else needs, note that the solution is not perfect.
public static Point ClosestPointOnCircle(int rad, PointF circle, PointF other)
{
if (other.X == circle.X && other.Y == circle.Y) // dealing with division by 0
other.Y--;
return new Point((int)Math.Floor(circle.X + rad * ((other.X - circle.X) / (Math.Sqrt(Math.Pow(other.X - circle.X, 2) + Math.Pow(other.Y - circle.Y, 2))))), (int)Math.Floor(circle.Y + rad * ((other.Y - circle.Y) / (Math.Sqrt(Math.Pow(other.X - circle.X, 2) + Math.Pow(other.Y - circle.Y, 2))))));
}
What the code does is return a point on the circle that is the closest to the another point, then, I used the curve middle point as the other point to change the end point of the curve.
Then I used the arrow cap as normal and got this:image
Which is good enough for my project.

GPS lap & Segment timer

I've been searching for a while but haven't found exactly what I'm looking for.
I'm working on an app that will go in a race car. It will give the driver the ability to press a button to mark a Start/Finish line. It will also have a button to allow a driver to set segment times.
Keep in mind a track can be an oval which I'm working on first. It could be a road course or it could be an auto cross where the start and finish line aren't the exact same location. They could be with 50 feet of each other or so but the car never crosses where it starts.
I have my gps data coming in and I convert the NMea messages to my classes and I store Lat, Lon, Speed, Course etc. In my research I've ran across this which is interesting. The GPS will be mounted outside the roof for better signal. It generates 10 hits per second. (Garmin Glo)
http://www.drdobbs.com/windows/gps-programming-net/184405690?pgno=1
It's old but it talks about UTM and the Cartesian coordinate system. So using the DecDeg2UTM, I convert Lat & Lon to X & coordinates as well.
I've also been trying to use the Intersect formula I found Here I took the intersect and tried to convert it to C# which I'll post at the end. However, feeding coordinates of an oval track, it doesn't seem to be working. Also, I'm not sure exactly what it's supposed to be doing. But the coordinates it returns when it does somethign like -35.xxx & 98.xxxx which out in an ocean somewhere 1000's of miles from where the track is.
I looking for answers to the following.
I assume I need to take the location recorded when a button is pressed for Start/Finish or Segment and calculate a line perpendicular to the direction the car in able to be able to do some sort of Line Intersection calculation. The Cartesian coordinates seems to calculate the bearing fairly well. But the question here is how do you get the "left and right coordinates". Also, keep in mind, an oval track may be 60 feet wide. But as mentioned an auto cross track may only be 20 ft wide and part of the track may be with 50 ft. Note I'm fine with indicating to set the points, the car needs to be going slow or stopped at the points to get an accurate coordinate. Some tracks they will have to be set while walking the track.
Based on this, should I be trying to use decimal lat lon or would utilizing the Cartesian coordinate system based on UTM be a more accurate method for what I'm trying to do?
Either one is there a .Net library or C based library with source code that has methods for making these calculations?
How can this be accurately handled. (Not that great with Math, links to code samples would help tremendously.)
Next, after I have the lines or whatever is needed for start/finish and segments, as I get GPS sign from the car racing, I need to figure out the most accurate way to tell when a car has crossed those segments. again if I'm lucky I'll get 10 hits per second but it will probably be lower. Then the vehicle speeds could vary significantly depending on the type of track and vehicle. So the GPS hit could be many feet "left or right" of a segment. Also, it could be many feet before or after a segment.
Again, if there is a GIS library out there I can feed coordinates and all this is calculated, that's would work as well as long as it's performant. If not again I'm trying to decide if it's best to break down coordinates to X Y or some geometry formulas for coordinates in decimal format. Mods, I assume there is hard data to support an answer of either way and this isn't responses aren't fully subjective to opinions.
Here is the C# code I came up with from the Script page above. I'm starting to feel UTM and the Cartesian Coordinate system would be better for accuracy and performance. But again I'm open to evidence to the contrary if it exists.
Thanks
P.S. Note GeoCoordinate is from the .Net System.Device.Location assemble. GpsData is just a class I use to convert NMEA messages into Lat, Lon, Course, NumSats, DateTime etc.
The degree Radian methods are extensions as as follows.
public static double DegreeToRadians(this double angle)
{
return Math.PI * angle / 180.0;
}
public static double RadianToDegree(this double angle)
{
return angle * (180.0 / Math.PI);
}
}
public static GeoCoordinate CalculateIntersection(GpsData p1, double brng1, GpsData p2, double brng2)
{
// see http://williams.best.vwh.net/avform.htm#Intersection
// Not sure I need to use Cosine
double _p1LatRadians = p1.Latitude.DegreeToRadians();
double _p1LonToRadians = p1.Longitude.DegreeToRadians();
double _p2LatToRadians = p2.Latitude.DegreeToRadians();
double _p2LonToRadians = p2.Longitude.DegreeToRadians();
double _brng1ToRadians = brng1.DegreeToRadians();
double _brng2ToRadians = brng2.DegreeToRadians();
double _deltaLat = _p2LatToRadians - _p1LatRadians;
double _deltaLon = _p2LonToRadians - _p1LonToRadians;
var _var1 = 2 * Math.Asin(Math.Sqrt(Math.Sin(_deltaLat / 2) * Math.Sin(_deltaLat / 2)
+ Math.Cos(_p1LatRadians) * Math.Cos(_p2LatToRadians) * Math.Sin(_deltaLon / 2) * Math.Sin(_deltaLon / 2)));
if (_var1 == 0) return null;
// initial/final bearings between points
var _finalBrng = Math.Acos((Math.Sin(_p2LatToRadians) - Math.Sin(_p1LatRadians) * Math.Cos(_var1)) / (Math.Sin(_var1) * Math.Cos(_p1LatRadians)));
//if (isNaN(θa)) θa = 0; // protect against rounding
var θb = Math.Acos((Math.Sin(_p1LatRadians) - Math.Sin(_p2LatToRadians) * Math.Cos(_var1)) / (Math.Sin(_var1) * Math.Cos(_p2LatToRadians)));
var θ12 = Math.Sin(_p2LonToRadians - _p1LonToRadians) > 0 ? _finalBrng : 2 * Math.PI - _finalBrng;
var θ21 = Math.Sin(_p2LonToRadians - _p1LonToRadians) > 0 ? 2 * Math.PI - θb : θb;
var α1 = (_brng1ToRadians - θ12 + Math.PI) % (2 * Math.PI) - Math.PI; // angle 2-1-3
var α2 = (θ21 - _brng2ToRadians + Math.PI) % (2 * Math.PI) - Math.PI; // angle 1-2-3
if (Math.Sin(α1) == 0 && Math.Sin(α2) == 0) return null; // infinite intersections
if (Math.Sin(α1) * Math.Sin(α2) < 0) return null; // ambiguous intersection
α1 = Math.Abs(α1);
α2 = Math.Abs(α2);
// ... Ed Williams takes abs of α1/α2, but seems to break calculation?
var α3 = Math.Acos(-Math.Cos(α1) * Math.Cos(α2) + Math.Sin(α1) * Math.Sin(α2) * Math.Cos(_var1));
var δ13 = Math.Atan2(Math.Sin(_var1) * Math.Sin(α1) * Math.Sin(α2), Math.Cos(α2) + Math.Cos(α1) * Math.Cos(α3));
var _finalLatRadians = Math.Asin(Math.Sin(_p1LatRadians) * Math.Cos(δ13) + Math.Cos(_p1LatRadians) * Math.Sin(δ13) * Math.Cos(_brng1ToRadians));
var _lonBearing = Math.Atan2(Math.Sin(_brng1ToRadians) * Math.Sin(δ13) * Math.Cos(_p1LatRadians), Math.Cos(δ13) - Math.Sin(_p1LatRadians) * Math.Sin(_finalLatRadians));
var _finalLon = _p1LonToRadians + _lonBearing;
var _returnLat = _finalLatRadians.RadianToDegree();
var _latToDegree = _finalLon.RadianToDegree();
var _returnLon = ( _latToDegree + 540) % 360 - 180;
return new GeoCoordinate(_returnLat, _returnLon);
//return new LatLon(φ3.toDegrees(), (λ3.toDegrees() + 540) % 360 - 180); // normalise to −180..+180°
}

Logarithmic Spiral - Is Point on Spiral (cartesian coordinates

Lets Say I have a 3d Cartesian grid. Lets also assume that there are one or more log spirals emanating from the origin on the horizontal plane.
If I then have a point in the grid I want to test if that point is in one of the spirals. I acutally want to test if it within a certain range of the spirals but determining if it is on the point is a good start.
So I guess the question has a couple parts.
How to generate the arms from parameters (direction, tightness)
How to tell if a point in the grid is in one of the spiral arms
Any ideas? I have been googling all day and don't feel I am any closer to a solution than when I started.
Here is a bit more information that might help:
I don't actually need to render the spirals. I want to set the pitch and rotation and then pass a point to a method that can tell me if the point I passed is within the spiral (within a given range of any point on the spiral). Based on the value returned (true or false) my program will make a decision on whether or not something exists at the point in space.
How to parametrically define the log spirals (pitch and rotation and ??)
Test if a point (x, y, z) is withing a given range of any point on the spiral.
Note: Both of the above would be just on the horizontal plane
These are two functions defining an anti-clockwise spiral:
PolarPlot[{
Exp[(t + 10)/100],
Exp[t/100]},
{t, 0, 100 Pi}]
Output:
These are two functions defining a clockwise spiral:
PolarPlot[{
- Exp[(t + 10)/100],
- Exp[t/100]},
{t, 0, 100 Pi}]
Output:
Cartesian coordinates
The conversion Cartesian <-> Polar is
(1) Ro = Sqrt[x^2+y^2]
t = ArcTan[y/x]
(2) x = Ro Cos[t]
y = Ro Sin[t]
So, If you have a point in Cartesian Coords (x,y) you transform it to your equivalent polar coordinates using (1). Then you use the forula for the spiral function (any of the four mentinoned above the plots, or similar ones) putting in there the value for t, and obtaining Ro. The last step is to compare this Ro with the one we got from the coordinates converion. If they are equal, the point is on the spiral.
Edit Answering your comment
For a Log spiral is almost the same, but with multiple spirals you need to take care of the logs not going to negative values. That's why I used exponentials ...
Example:
PolarPlot[{
Log[t],
If[t > 3, Log[ t - 2], 0],
If[t > 5, Log[ t - 4], 0]
}, {t, 1, 10}]
Output:
Not sure this is what you want, but you can reverse the log function (or "any" other for that matter).
Say you have ln A = B, to get A from B you do e^B = A.
So you get your point and pass it as B, you'll get A. Then you just need to check if that A (with a certain +- range) is in the values you first passed on to ln to generate the spiral.
I think this might work...
Unfortunately, you will need to know some mathematics notation anyway - this is a good read about the logarithmic sprial.
http://en.wikipedia.org/wiki/Logarithmic_spiral
we will only need the top 4 equations.
For your question 1
- to control the tightness, you tune the parameter 'a' as in the wiki page.
- to control the direction, you offset theta by a certain amount.
For your question 2
In floating point arithmetic, you will never get absolute precision, which mean there will be no point falling exactly on the sprial. On the screen, however, you will know which pixel get rendered, and you can test whether you are hitting a point that is rendered.
To render a curve, you usually render it as a sequence of line segments, short enough so that overall it looks like a curve. If you want to know whether a point lies within certain distance from the spiral, you can render the curve (on a off-screen buffer if you wish) by having thicker lines.
here a C++ code drawing any spiral passing where the mouse here
(sorry for my English)
int cx = pWin->vue.right / 2;
int cy = pWin->vue.bottom / 2;
double theta_mouse = atan2((double)(pWin->y_mouse - cy),(double)(pWin->x_mouse - cx));
double square_d_mouse = (double)(pWin->y_mouse - cy)*(double)(pWin->y_mouse - cy)+
(double)(pWin->x_mouse - cx)*(double)(pWin->x_mouse - cx);
double d_mouse = sqrt(square_d_mouse);
double theta_t = log( d_mouse / 3.0 ) / log( 1.19 );
int x = cx + (3 * cos(theta_mouse));
int y = cy + (3 * sin(theta_mouse));
MoveToEx(hdc,x,y,NULL);
for(double theta=0.0;theta < PI2*5.0;theta+=0.1)
{
double d = pow( 1.19 , theta ) * 3.0;
x = cx + (d * cos(theta-theta_t+theta_mouse));
y = cy + (d * sin(theta-theta_t+theta_mouse));
LineTo(hdc,x,y);
}
Ok now the parameter of spiral is 1.19 (slope) and 3.0 (radius at center)
Just compare the points where theta is a mutiple of 2 PI = PI2 = 6,283185307179586476925286766559
if any points is near of a non rotated spiral like
x = cx + (d * cos(theta));
y = cy + (d * sin(theta));
then your mouse is ON the spiral... I searched this tonight and i googled your past question

Categories

Resources