I am working on a countdown project that involves an arc. I've been struggling with the math for a few hours now and hope someone can help me. I have a 150px circle on which I want to draw arc that runs over starting at the top. The circle (ellipse really) is at 160,4
<Ellipse Height="150" HorizontalAlignment="Left" Margin="160,4,0,0"
Name="minutesClock" Stroke="Gainsboro" StrokeThickness="20"
VerticalAlignment="Top" Width="150" />
I have a method that is supposed to calculate the arc from the center top of the circle to whatever number of seconds is left
private void drawArc(int timevalue, int maxvalue)
{
Ellipse element = (Ellipse)LayoutRoot.FindName("minutesClock");
double top = element.Margin.Top;
double left = element.Margin.Left;
double width = element.Width;
double height = element.Height;
double strokeWidth = element.StrokeThickness;
double startX = left + (width / 2);
double startY = top + (strokeWidth / 2);
double radius = (width / 2) - (strokeWidth / 2);
double percent = (double)timevalue / (double)maxvalue;
Point center = new Point();
center.X = top + (height / 2);
center.Y = left + (width / 2);
Point newEnd = calculatePoint(radius, percent, center);
Path arc = (Path)LayoutRoot.FindName(what + "Arc");
PathFigure path = new PathFigure();
path.StartPoint = new Point(startX, startY);
ArcSegment arcSegment = new ArcSegment();
arcSegment.IsLargeArc = false;
Size arcSize = new Size(radius,radius);
arcSegment.Size = arcSize;
arcSegment.SweepDirection = SweepDirection.Clockwise;
arcSegment.Point = newEnd;
arcSegment.RotationAngle = 45;
path.Segments.Add(arcSegment);
PathGeometry pg = new PathGeometry();
pg.Figures = new PathFigureCollection();
pg.Figures.Add(path);
arc.Data = pg;
}
The arc starts at the right place but doesn't end up in the right place (the end point is all over the place). My calculatePoint code has to be where the error is. I figure it has something to do with
private Point calculatePoint(double radius, double percent, Point center)
{
double degrees = 90 - (360 * percent);
double radians = (Math.PI * degrees) / 180;
Point endPoint = new Point();
endPoint.X = center.X + (radius * Math.Sin(radians));
endPoint.Y = center.Y + (radius * Math.Cos(radians));
return endPoint;
}
Where am I going wrong?
You need to subtract the sinus (to go from the center "upwards" on the UI canvas):
endPoint.X = center.X - (radius * Math.Sin(radians));
Origin 0,0 is Top Left corner, not bottom left.
[Edit]
Oh and you are confusding x and y: think x is horizontal coordinated and y is vertical, so this is wrong:
center.X = top + (height / 2);
center.Y = left + (width / 2);
and this is wrong:
endPoint.X = center.X + (radius * Math.Sin(radians));
endPoint.Y = center.Y + (radius * Math.Cos(radians));
Corrected:
center.Y = top + (height / 2);
center.X = left + (width / 2);
and (with the subtraction fix I mentioned)
endPoint.Y = center.Y - (radius * Math.Sin(radians));
endPoint.X = center.X + (radius * Math.Cos(radians));
Related
I created some Functions, these will draw Rectangles, Circles, Hexagons etc.
One of them looks like this:
rotation = 45;
function hex(hex_sides, hex_size, hex_color){
x = ctx.canvas.width/2;
y = ctx.canvas.height/2;
ctx.save();
ctx.rotate(rotation*Math.PI/180);
ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
ctx.moveTo(x + hex_size * Math.cos(0), y + hex_size * Math.sin(0));
ctx.restore();
for (i = 0; i < hex_sides+1; i++) {
ctx.lineTo(x + hex_size * Math.cos(i * 2 * Math.PI / hex_sides), y + hex_size * Math.sin(i * 2 * Math.PI / hex_sides));
}
ctx.strokeStyle = hex_color;
ctx.stroke();
}
Now i call the Functions to Draw the Shapes inside my animation loop.
function loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
circle(200);
circle(220);
hex(6, 180, "#fff");
rotation += 0.4;
requestAnimationFrame(loop);
}
I'm incrementing the var rotation inside the loop but it does not rotate the whole shape but just one line of it instead. Other Shapes i cant get to rotate at all.
I think i got a wrong approach, maybe because of my confusion about .save() and .restore() or .beginPath() and .closePath().
In General the behaviour is very strange when i start to use .translate() and .rotate()
The entire Code is here.
UPDATE
It is definitely something about this line:
ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
Somehow it does not translate correctly. The rotation now happens around the right middle side of the normal shape position but i want the rotation around its own axis.
I changed the hex() function to:
ctx.save();
ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
ctx.rotate(rotation*Math.PI/180);
ctx.moveTo(x + hex_size * Math.cos(0), y + hex_size * Math.sin(0));
for (i = 0; i < hex_sides+1; i++) {
ctx.lineTo(x + hex_size * Math.cos(i * 2 * Math.PI / hex_sides), y + hex_size * Math.sin(i * 2 * Math.PI / hex_sides));
}
ctx.strokeStyle = hex_color;
ctx.stroke();
ctx.restore();
Again, entire Code is here.
Nevermind... figured it out, i have forgotten to substract half of the shapes width from the translation point and also the order seems to be more important then i tought.
Working Code
function hex(hex_sides, hex_size, hex_color){
x = ctx.canvas.width/2;
y = ctx.canvas.height/2;
ctx.save();
ctx.translate(x,y);
ctx.rotate(rotation*Math.PI/180);
//ctx.moveTo(x + hex_size * Math.cos(0), y + hex_size * Math.sin(0));
ctx.moveTo(0,0);
for (i = 0; i < hex_sides+1; i++) {
ctx.lineTo(x/hex_size + hex_size * Math.cos(i * 2 * Math.PI / hex_sides), y/hex_size + hex_size * Math.sin(i * 2 * Math.PI / hex_sides));
}
ctx.strokeStyle = hex_color;
ctx.stroke();
ctx.restore();
}
I want to draw Arc in Vieport3D using MeshGeometry3D.I have searched for it a lot but not found anything ,what I found is using PathGeometry.I am new to WPF so don't know much about 3D graphics.How can I do this?
thanks
here is the code which I wrote to create mesh-geometry for Arc.I hope this will help someone.
private GeometryModel3D GetModel(double radius, Vector3D normal, Point3D center, int resolution, double StartAngle, double EndAngle)
{
var mod = new GeometryModel3D();
var geo = new MeshGeometry3D();
// Generate the circle in the XZ-plane
// Add the center first
geo.Positions.Add(new Point3D(0, 0, 0));
// Iterate from angle 0 to 2*PI
double dev = (2 * Math.PI) / resolution;
double thik = 0.02;
//float spaceangle = StartAngle + 1;
if (StartAngle != EndAngle)
{
for (double i = StartAngle; i < EndAngle; i += dev)
{
geo.Positions.Add(new Point3D(radius * Math.Cos(i), 0, -radius * Math.Sin(i)));
geo.Positions.Add(new Point3D((radius-thik) * Math.Cos(i), 0, (-(radius-thik)) * Math.Sin(i)));
}
for (int i = 3; i < geo.Positions.Count; i += 1)
{
geo.TriangleIndices.Add(i - 3);
geo.TriangleIndices.Add(i - 1);
geo.TriangleIndices.Add(i - 2);
geo.TriangleIndices.Add(i - 1);
geo.TriangleIndices.Add(i);
geo.TriangleIndices.Add(i - 2);
}
}
mod.Geometry = geo;
// Create transforms
var trn = new Transform3DGroup();
// Up Vector (normal for XZ-plane)
var up = new Vector3D(0, 1, 0);
// Set normal length to 1
normal.Normalize();
var axis = Vector3D.CrossProduct(up, normal); // Cross product is rotation axis
var angle = Vector3D.AngleBetween(up, normal); // Angle to rotate
trn.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(axis, angle)));
trn.Children.Add(new TranslateTransform3D(new Vector3D(center.X, center.Y, center.Z)));
mod.Transform = trn;
return mod;
}
My homework is to write a C program with openGL/Glut which, after getting groups of 4 points by mouse click (points with 3 coordinates), should draw a bezier curve with adaptive algorithm. At a theoretical level it's clear how the algorithm works but I don't know how to put that in C code. I mean that at lesson we saw that the 4 control points could have a shape similar to a "trapeze" and then the algorithm calculates the two "heights" and then checks if they satisfy a tollerance. The problem is that the user might click everywhere in the screen and the points might not have trapeze-like shape...so, where can I start from? This is all I have
This is the cole I have written, which is called each time a control point is added:
if (bezierMode == CASTELJAU_ADAPTIVE) {
glColor3f (0.0f, 0.8f, 0.4f); /* draw adaptive casteljau curve in green */
for(i=0; i+3<numCV; i += 3)
adaptiveDeCasteljau3(CV, i, 0.01);
}
void adaptiveDeCasteljau3(float CV[MAX_CV][3], int position, float tolerance) {
float x01 = (CV[position][0] + CV[position+1][0]) / 2;
float y01 = (CV[position][1] + CV[position+1][1]) / 2;
float x12 = (CV[position+1][0] + CV[position+2][0]) / 2;
float y12 = (CV[position+1][1] + CV[position+2][1]) / 2;
float x23 = (CV[position+2][0] + CV[position+3][0]) / 2;
float y23 = (CV[position+2][1] + CV[position+3][1]) / 2;
float x012 = (x01 + x12) / 2;
float y012 = (y01 + y12) / 2;
float x123 = (x12 + x23) / 2;
float y123 = (y12 + y23) / 2;
float x0123 = (x012 + x123) / 2;
float y0123 = (y012 + y123) / 2;
float dx = CV[3][0] - CV[0][0];
float dy = CV[3][1] - CV[0][1];
float d2 = fabs(((CV[1][0] - CV[3][0]) * dy - (CV[1][1] - CV[3][1]) * dx));
float d3 = fabs(((CV[2][0] - CV[3][0]) * dy - (CV[2][1] - CV[3][1]) * dx));
if((d2 + d3)*(d2 + d3) < tolerance * (dx*dx + dy*dy)) {
glBegin(GL_LINE_STRIP);
glVertex2f(x0123, y0123);
glEnd();
return;
}
float tmpLEFT[4][3];
float tmpRIGHT[4][3];
tmpLEFT[0][0] = CV[0][0];
tmpLEFT[0][1] = CV[0][1];
tmpLEFT[1][0] = x01;
tmpLEFT[1][1] = y01;
tmpLEFT[2][0] = x012;
tmpLEFT[2][1] = y012;
tmpLEFT[3][0] = x0123;
tmpLEFT[3][1] = y0123;
tmpRIGHT[0][0] = x0123;
tmpRIGHT[0][1] = y0123;
tmpRIGHT[1][0] = x123;
tmpRIGHT[1][1] = y123;
tmpRIGHT[2][0] = x23;
tmpRIGHT[2][1] = y23;
tmpRIGHT[3][0] = CV[3][0];
tmpRIGHT[3][1] = CV[3][1];
adaptiveDeCasteljau3(tmpLEFT, 0, tolerance);
adaptiveDeCasteljau3(tmpRIGHT, 0, tolerance);
}
and obviously nothing is drawn. Do you have any idea?
the Begin / End should engulf your whole loop, not being inside for each isolated vertex !
I've got this Canvas defined in XAML:
<Canvas x:Name="MyCanvas" Background="White" TouchMove="MyCanvas_TouchMove"/>
And here's my first try to simulate a spray effect during TouchMove events :
for (int i = 0; i < 10; i++)
{
double r = random.NextDouble() * radius;
double theta = random.NextDouble() * (Math.PI * 2);
double x = e.GetTouchPoint(MyCanvas).Position.X + Math.Cos(theta) * r;
double y = e.GetTouchPoint(MyCanvas).Position.Y + Math.Sin(theta) * r;
Ellipse ellipse = new Ellipse();
ellipse.Height = 2;
ellipse.Width = 2;
ellipse.SetValue(Canvas.LeftProperty, x);
ellipse.SetValue(Canvas.TopProperty, y);
ellipse.Fill = (blackBrush);
MyCanvas.Children.Add(ellipse);
}
}
It works great at the beginning, but the more I "spray", the rendering slows dramatically.
I'm aware that the problem is most likely because I add a lot of elements on the canvas, and also because the Children.Add method is called too often.
How can I improve this ?
I have this texture representing internal area of a pipe:
I have created a simple cylinder model (GeometryModel3D) by dissecting the above texture to a grid of points and than wrapping this to form a cylinder, then mapping the above texture to it (each square on a grid having two triangles):
The left and right edges of the texture meet at the above black seam line, which is unwanted.
I could not use single vertex point for smooth continuation there, because that point corresponds to both 0 and 360 degrees which is single angle, but two distinct points on edges of the 2D texture.
So I have used pairs of vertices on the same location but each corresponding to different point in the source texture.
Is there anything I can do to hide the seam line?
Model creation code:
private void SceneViewerWindowOnLoaded(object sender, RoutedEventArgs e)
{
var imageSource = new BitmapImage(new Uri("pack://application:,,,/Resources/out1.jpg"));
var meshGeometry3D = new MeshGeometry3D();
double circumference = imageSource.PixelWidth;
double radius = (circumference / (2.0 * Math.PI));
double angleSegment = (2.0 * Math.PI / SegmentCountTrans);
double sizeSegmentLong = ((double)imageSource.PixelHeight / SegmentCountLong);
double sizeSegmentTrans = ((double)imageSource.PixelWidth / SegmentCountTrans);
for (int indexSegmentLong = 0; indexSegmentLong < SegmentCountLong; indexSegmentLong++)
{
double depth = (indexSegmentLong * sizeSegmentLong);
for (int indexSegmentTrans = 0; indexSegmentTrans < SegmentCountTrans; indexSegmentTrans++)
{
meshGeometry3D.Positions.Add(GetVertexPosition(indexSegmentTrans, depth, radius, angleSegment));
meshGeometry3D.TextureCoordinates.Add(new Point(indexSegmentTrans * sizeSegmentTrans, depth));
}
// add one extra vertex representing 360 degrees for complete wrap-around
meshGeometry3D.Positions.Add(GetVertexPosition(SegmentCountTrans, depth, radius, angleSegment));
meshGeometry3D.TextureCoordinates.Add(new Point(SegmentCountTrans * sizeSegmentTrans, depth));
}
meshGeometry3D.TriangleIndices.Clear();
for (int indexSegmentLong = 0; indexSegmentLong < (SegmentCountLong - 1); indexSegmentLong++)
{
for (int indexSegmentTrans = 0; indexSegmentTrans < SegmentCountTrans; indexSegmentTrans++)
{
int indexCurrent = (indexSegmentLong * (SegmentCountTrans + 1) + indexSegmentTrans);
meshGeometry3D.TriangleIndices.Add(indexCurrent);
meshGeometry3D.TriangleIndices.Add(indexCurrent + 1);
meshGeometry3D.TriangleIndices.Add(indexCurrent + SegmentCountTrans + 1);
meshGeometry3D.TriangleIndices.Add(indexCurrent + SegmentCountTrans + 1);
meshGeometry3D.TriangleIndices.Add(indexCurrent + 1);
meshGeometry3D.TriangleIndices.Add(indexCurrent + SegmentCountTrans + 2);
}
}
var geometryModel3D = new GeometryModel3D
{
Geometry = meshGeometry3D,
Material = new DiffuseMaterial
{
Brush = new ImageBrush(imageSource)
}
};
this.SceneViewer.Model = geometryModel3D;
}
private static Point3D GetVertexPosition(int indexSegmentAngle, double depth, double radius, double angleSegment)
{
double angle = (StartAngle + indexSegmentAngle * angleSegment);
return new Point3D(
radius * Math.Cos(angle),
radius * Math.Sin(angle),
-depth);
}
XAML code for the Viewport3D element containing the model:
<Viewport3D x:Name="Viewport3D">
<Viewport3D.Camera>
<PerspectiveCamera x:Name="Camera" Position="0.0,0.0,0.0" LookDirection="0.0,0.0,-1.0" UpDirection="0.0,1.0,0.0" FieldOfView="90"/>
</Viewport3D.Camera>
<ModelVisual3D>
<ModelVisual3D.Content>
<AmbientLight Color="White"/>
</ModelVisual3D.Content>
</ModelVisual3D>
<ModelVisual3D x:Name="ModelVisualModel"/>
</Viewport3D>
When you create your image brush try setting the TileMode to TileMode.Tile and ViewportUnits to BrushMappingMode.Absolute. If that still doesn't work then post a follow-up comment here and I'll try to reproduce it on my end.
I used DrawingBrush instead of Imagebrush. This fixed the seams and I also get an fps boost when setting the cachinghint.
Brush brush = new DrawingBrush(new ImageDrawing(_texture, new Rect(0,0,1,1)));
RenderOptions.SetCachingHint(brush , CachingHint.Cache);
RenderOptions.SetCacheInvalidationThresholdMinimum(brush , 0.5);
RenderOptions.SetCacheInvalidationThresholdMaximum(brush , 2.0);