Bezier Curves in WPF - wpf

I'm drawing some Bezier curves in WPF and for the most part it's working but I'm getting some faint separations between each segment. As you can see they even appear in straight sections so I don't believe the issue is due to an insufficient number of segments. (This image is at 4x magnification.)
I'm using a collection of System.Windows.Shapes.Line objects to paint them. They are instantiated in code like so:
Shapes.Line Line = new Shapes.Line();
Line.Stroke = Brush;
Line.HorizontalAlignment = Windows.HorizontalAlignment.Left;
Line.VerticalAlignment = Windows.VerticalAlignment.Center;
Line.StrokeThickness = 10;
My theory is that this separation is due to the fact that the point where one line ends is the same point where the next begins but I unsure what's the best way to fix this. I'm fairly new at this so I don't want to go hacking away before I ask if anyone has any tried and true solutions to make these faint separations disappear.
EDIT:
Here is the code I'm using to generate the segments. The ILine interface is something I created but it's point values are simply translated to the System.Windows.Shapes.Line respective values later on in the program.
public static void FormBezier(List<ILine> Lines, Point[] pt)
{
if (Lines.Count == 0) return;
double t, dt, x0, y0, x1, y1;
t = 0.0;
dt = 1.0 / Lines.Count;
x1 = X(t, new double[] { pt[0].X, pt[1].X, pt[2].X, pt[3].X });
y1 = X(t, new double[] { pt[0].Y, pt[1].Y, pt[2].Y, pt[3].Y });
t += dt;
for(int index = 1; index < Lines.Count - 1; index++)
{
x0 = x1;
y0 = y1;
x1 = X(t, new double[] { pt[0].X, pt[1].X, pt[2].X, pt[3].X });
y1 = X(t, new double[] { pt[0].Y, pt[1].Y, pt[2].Y, pt[3].Y });
Lines[index].Start.X = x0;
Lines[index].End.X = x1;
Lines[index].Start.Y = y0;
Lines[index].End.Y = y1;
t += dt;
}
t = 1.0;
x0 = x1;
y0 = y1;
x1 = X(t, new double[] { pt[0].X, pt[1].X, pt[2].X, pt[3].X });
y1 = X(t, new double[] { pt[0].Y, pt[1].Y, pt[2].Y, pt[3].Y });
Lines[Lines.Count - 1].Start.X = x0;
Lines[Lines.Count - 1].End.X = x1;
Lines[Lines.Count - 1].Start.Y = y0;
Lines[Lines.Count - 1].End.Y = y1;
}
public static double X(double t, double[] x)
{
return
x[0] * Math.Pow((1 - t), 3) +
x[1] * 3 * t * Math.Pow((1 - t), 2) +
x[2] * 3 * Math.Pow(t, 2) * (1 - t) +
x[3] * Math.Pow(t, 3);
}

At a wild guess, it's probably a rounding error. The units used in WPF aren't pixels, they are resolution independent units. When WPF actually draws something it has to convert those units to real pixels on whatever screen it's drawing to. If the conversion ends up being half way between real pixels, it'll shade those pixels to try and approximate half a pixel in each real pixel. Hence you sometimes get gray pixels around a supposedly black line (anti-aliasing).
The property SnapsToDevicePixels might help you.

Clearly a fault in drawing algorithm. I am not best at WPF but you may want to have a look at this blog post.

Related

Mandelbrot Set Zoom Distortion in C

I'm writing a C program to render a Mandelbrot set and currently, I'm stuck with trying out to figure out how to zoom in properly.
I want for the zoom to be able to follow the mouse pointer on the screen - so that the fractal zooms in into the cursor position.
I have a window defined by:
# define WIDTH 800
# define HEIGHT 600
My Re_max, Re_min, Im_Max, Im_Min are defined and initialized as follows:
man->re_max = 2.0;
man->re_min = -2.0;
man->im_max = 2.0;
man->im_min = -2.0;
The interpolation value (more on in later) is defined and initialized as follows:
pos->interp = 1.0;
To map the pixel coordinates to the center of the screen, I'm using the position function:
void position(int x, int y, t_mandel *man)
{
double *s_x;
double *s_y;
s_x = &man->pos->shift_x;
s_y = &man->pos->shift_y;
man->c_re = (x / (WIDTH / (man->re_max - man->re_min)) + man->re_min) + *s_x;
man->c_im =(y / (HEIGHT / (man->im_max - man->re_min)) + man->im_min) + *s_y;
man->c_im *= 0.8;
}
To zoom in, I first get the coordinates of the mouse pointer and map them to the visible area given by the rectangle defined by the (Re_Max, Re_Min, Im_Max, Im_Min) using this function, where x and y are coordinates of the pointer on a screen:
int mouse_move(int x, int y, void *p)
{
t_fract *fract;
t_mandel *man;
fract = (t_fract *)p;
man = fract->mandel;
fract->mouse->Re = x / (WIDTH / (man->re_max - man->re_min)) + man->re_min;
fract->mouse->Im = y / (HEIGHT / (man->im_max - man->re_min)) + man->im_min;
return (0);
}
This function is called when a mouse wheel scroll is registered. The actual zooming is achieved by this function:
void zoom_control(int key, t_fract *fract)
{
double *interp;
interp = &fract->mandel->pos->interp;
if (key == 5) // zoom in
{
*interp = 1.0 / 1.03;
apply_zoom(fract->mandel, fract->mouse->Re, fract->mouse->Im, *interp);
}
else if (key == 4) // zoom out
{
*interp = 1.0 * 1.03;
apply_zoom(fract->mandel, fract->mouse->Re, fract->mouse->Im, *interp);
}
}
Which calls this:
void apply_zoom(t_mandel *man, double m_re, double m_im, double interp)
{
man->re_min = interpolate(m_re, man->re_min, interp);
man->im_min = interpolate(m_im, man->im_min, interp);
man->re_max = interpolate(m_re, man->re_max, interp);
man->im_max = interpolate(m_im, man->im_max, interp);
}
I have a simple interpolate function to redefine the area bounding rectangle:
double interpolate(double start, double end, double interp)
{
return (start + ((end - start) * interp));
}
So the problem is:
My code renders the fractal like this -
Mandelbrot set
But when I try to zoom in as described with the mouse, instead of going nicely "in", it just distorts like this, the image just sort of collapses onto itself instead of actually diving into the fractal.
I would really appreciate help with this one as I've been stuck on it for a while now.
If you please could also explain the actual math behind your solutions, I would be overjoyed!
Thank you!
After quite a bit of headache and a lot of paper wasted on recalculation interpolation methods, I've realized that the way I've mapped my complex numbers on-screen was incorrect, to begin with. Reworking my mapping method solved my problem, so I'll share what have I done.
-------------------------------OLD WAY--------------------------------------
I've initialized my Re_max, Re_min, Im_Max, Im_Min values, which define the visible area in the following way:
re_max = 2.0;
re_min = -2.0;
im_max = 2.0;
im_min = -2.0;
Then, I used this method to convert my on-screen coordinates to the complex numbers used to calculate the fractal (note that the coordinates used for mapping the mouse position for zoom interpolation and coordinates used to calculate the fractal itself use the same method):
Re = x / (WIDTH / (re_max - re_min)) + re_min;
Im = y / (HEIGHT / (im_max - re_min)) + im_min;
However, this way I didn't take the screen ratio into account and I've neglected the fact (due to a lack of knowledge) that the y coordinate on-screen is inverse (at least in my program) - negative direction is up, positive is down.
This way, when I tried to zoom in with my interpolation, naturally, the image distorted.
------------------------------CORRECT WAY-----------------------------------
When defining the bounding rectangle of the set, maximum imaginary im_max) part should be calculated, based on the screen ratio, to avoid image distortion when the display window isn't a square:
re_max = 2.0;
re_min = -2.0;
im_min = -2.0;
im_max = im_min + (re_max - re_min) * HEIGHT / WIDTH;
To map the on-screen coordinates to the complex numbers, I first found the "coordinate-to-number* ratio, which is equal to *rectangle length / screen width*:
re_factor = (re_max - re_min) / (WIDTH - 1);
im_factor = (im_max - im_min) / (HEIGHT - 1);
Then, I've mapped my pixel coordinates to the real and imaginary part of a complex number used in calculations like so:
c_re = re_min + x * re_factor;
c_im = im_max - y * im_factor;
After implementing those changes, I was finally able to smoothly zoom into the mouse position without any distortion or image "jumps".
If I understand you correctly, you want to make the point where the mouse is located a new center of the image, and change the scale of the image by a factor of 1.03. I would try something like that:
Your position() and mouse_move() functions remain the same.
in zoom_control() just change the way how you set the new value of interpolation, it should not be a fixed constant, but should be based on its current value. Also, pass the new scaling factor to the apply_zoom():
void zoom_control(int key, t_fract *fract)
{
double *interp;
interp = &fract->mandel->pos->interp;
double zoom_factor = 1.03;
if (key == 5) // zoom in
{
*interp /= zoom_factor;
apply_zoom(fract->mandel, fract->mouse->Re, fract->mouse->Im, 1.0 / zoom_factor);
}
else if (key == 4) // zoom out
{
*interp *= zoom_factor;
apply_zoom(fract->mandel, fract->mouse->Re, fract->mouse->Im, zoom_factor);
}
}
modify the apply zoom function:
void apply_zoom(t_mandel *man, double m_re, double m_im, double zoom_factor)
{
// Calculate the new ranges along the real and imaginary axes.
// They are equal to the current ranges multiplied by the zoom_factor.
double re_range = (man->re_max - man->re_min) * zoom_factor;
double im_range = (man->im_max - man->im_min) * zoom_factor;
// Set the new min/max values for real and imaginary axes with the center at
// mouse coordinates m_re and m_im.
man->re_min = m_re - re_range / 2;
man->re_max = m_re + re_range / 2;
man->im_min = m_im - im_range / 2;
man->im_max = m_im + im_range / 2;
}

Precisely locating glyph text in WPF

I am writing a chemical molecule editor for Windows. As it has to be used in a Word Add-In I am restricted to using WPF for rendering structures. This is working quite well, apart from one tiny niggling point.
I use GlyphRuns for rendering atom labels and they are always displaced slightly to the right. If you look on the screenshot you can see there is a leading whitespace, especially with the H2N, and Hg atom labels. Why? The white background is what you get when you get the outline geometry of the glyph run.
The GlyphRun class is so badly documented that I cannot see which of the properties to amend to precisely locate the text where I want it. So any suggestions to try would be welcome.
UPDATE: I've been asked to provide a sample. The code is complex, but not gratuitously so, so I'm cutting it down to focus on the essentials:
public void MeasureAtCenter(Point center)
{
GlyphInfo = GlyphUtils.GetGlyphsAndInfo(Text, PixelsPerDip, out GlyphRun groupGlyphRun, center, _glyphTypeface, TypeSize);
//compensate the main offset vector for any descenders
Vector mainOffset = GlyphUtils.GetOffsetVector(groupGlyphRun, AtomShape.SymbolSize) + new Vector(0.0, -MaxBaselineOffset) + new Vector(-FirstBearing(groupGlyphRun), 0.0);
TextRun = groupGlyphRun;
TextMetrics = new AtomTextMetrics
{
BoundingBox = groupGlyphRun.GetBoundingBox(center + mainOffset),
Geocenter = center,
TotalBoundingBox = groupGlyphRun.GetBoundingBox(center + mainOffset),
OffsetVector = mainOffset
};
}
public static GlyphInfo GetGlyphs(string symbolText, GlyphTypeface glyphTypeFace, double size)
{
ushort[] glyphIndexes = new ushort[symbolText.Length];
double[] advanceWidths = new double[symbolText.Length];
double[] uprightBaselineOffsets = new double[symbolText.Length];
double totalWidth = 0;
for (int n = 0; n < symbolText.Length; n++)
{
ushort glyphIndex = glyphTypeFace.CharacterToGlyphMap[symbolText[n]];
glyphIndexes[n] = glyphIndex;
double width = glyphTypeFace.AdvanceWidths[glyphIndex] * size;
advanceWidths[n] = width;
double ubo = glyphTypeFace.DistancesFromHorizontalBaselineToBlackBoxBottom[glyphIndex] * size;
uprightBaselineOffsets[n] = ubo;
totalWidth += width;
}
return new GlyphInfo { AdvanceWidths = advanceWidths, Indexes = glyphIndexes, Width = totalWidth, UprightBaselineOffsets = uprightBaselineOffsets };
}
public static GlyphUtils.GlyphInfo GetGlyphsAndInfo(string symbolText, float pixelsPerDip, out GlyphRun hydrogenGlyphRun, Point point, GlyphTypeface glyphTypeFace, double symbolSize)
{
//measure the H atom first
var glyphInfo = GlyphUtils.GetGlyphs(symbolText, glyphTypeFace, symbolSize);
hydrogenGlyphRun = GlyphUtils.GetGlyphRun(glyphInfo, glyphTypeFace,
symbolSize, pixelsPerDip, point);
//work out exactly how much we should offset from the center to get to the bottom left
return glyphInfo;
}
public static Vector GetOffsetVector(GlyphRun glyphRun, double symbolSize)
{
Rect rect = glyphRun.ComputeInkBoundingBox();
//Vector offset = (rect.BottomLeft - rect.TopRight) / 2;
Vector offset = new Vector(-rect.Width / 2, glyphRun.GlyphTypeface.CapsHeight * symbolSize / 2);
return offset;
}
Indeed the GlyphRun class is a lot of work to use. I would suggest working with FormattedText objects instead. If there are performance issues, you can consider converting the FormattedText to Geometry once and reusing that. The MSDN docs provide a comparison of the different approaches.

How to resize control with rotated in ViewModel

... I can't speak english...
I have a problem.
I want to resize after rotate using 8 ResizeThumb.(like PowerPoint)
But when I applied RotateTransform(orgin = 0.5), Resize method is strangely work.
Item ViewModel ViewModel has properties(X, Y, Angle, Width, Height) like this.
private double _X;
public double X
{
get
{
return_X;
}
set
{
value = Math.Round(value);
if(_X == value) { return; }
_X = value;
RaisePropertyChanged("X");
}
}
... and Y, Angle, Height, Width.
And I tried Binding like this.
Angle is binding at RotateTransform.
X, Y is binding at Canvas.Left/Top or TranslateTransform.
But both case strangely work.
So when I calculate X,Y after rotate, I think calculate angle together.
public void ResizeTopCenter(DragDeltaEventArgs e)
{
Matrix m = Matrix.Identity;
m.Rotate(Angle * Math.PI/180);
Point rotated = m.Transform(new Point(e.HorizontalChanged, e.VerticalChange));
// little bit different every direction.
ViewModel.X += rotated.X;
ViewModel.Y += rotated.Y;
ViewModel.Height += rotated.Y;
}
Another way
Canvas.SetTop(this.designerItem, Canvas.GetTop(this.designerItem) + (this.transformOrigin.Y * deltaVertical * (1 - Math.Cos(-this.angle))));
Canvas.SetLeft(this.designerItem, Canvas.GetLeft(this.designerItem) - deltaVertical * this.transformOrigin.Y * Math.Sin(-this.angle));
... strange as expected.
I can't write full source because I was off work.
Had suffered for eight hours, tomorrow is also continuing.
Please help me.
thank you.
and I'm sorry to read strage english.

Quaternion "lookAt" function

Im struggling with the following problem. Im working with bone animation and I want (ie) the head of the player to follow an another object in space. My up axis is +Z my forward axis is +Y, and the magnitude of the quaternion is in W. I tried to use the mesa code for gluLookAt and use the 3x3 matrix to transform to a quaternion but it doesn't work as expected so I go in another direction...
So far I got the following code that is "almost" working at least the head of the player is rotating (however the X angle seems to affect the Y rotation axis) in the good direction but its looking straight up instead on following an object on the floor at about 65 degree:
qt LookRotation( v3 lookAt, v3 upDirection )
{
qt t;
v3 forward = lookAt;
v3 up = upDirection;
OrthoNormalize( &forward, &up );
v3 right = v3_cross( up, forward );
mat3 m = mat3_make( right.x, up.x, forward.x,
right.y, up.y, forward.y,
right.z, up.z, forward.z );
t.w = sqrtf( 1.0f +
m.r[ 0 ].x +
m.r[ 1 ].y +
m.r[ 2 ].z ) * 0.5f;
float w4_recip = 1.0f / ( 4.0f * t.w );
t.x = ( m.r[ 2 ].y - m.r[ 1 ].z ) * w4_recip;
t.y = ( m.r[ 0 ].z - m.r[ 2 ].x ) * w4_recip;
t.z = ( m.r[ 1 ].x - m.r[ 0 ].y ) * w4_recip;
t = qt_normalize( t );
return t;
}
...
...
...
v3 v = v3_sub( vec4_to_v3( transform.world.r[ 3 ] /* The object XYZ location in the world */),
skeleton->final_pose.location[ i ] /* i = The head joint location */ );
v = v3_normalize( v );
qt q = LookRotation( v,
v3_make( 0.0f, 0.0f, 1.0f ) );
Can someone help me figuring out this problem... Im kinda new with quaternions and don't really know where I could have messed up. After quite some research basically what I want to do is something like the Unity API: http://docs.unity3d.com/Documentation/ScriptReference/Quaternion.LookRotation.html
I think this function will do what you need:
/// <summary>
/// Evaluates a rotation needed to be applied to an object positioned at sourcePoint to face destPoint
/// </summary>
/// <param name="sourcePoint">Coordinates of source point</param>
/// <param name="destPoint">Coordinates of destionation point</param>
/// <returns></returns>
public static Quaternion LookAt(Vector3 sourcePoint, Vector3 destPoint)
{
Vector3 forwardVector = Vector3.Normalize(destPoint - sourcePoint);
float dot = Vector3.Dot(Vector3.forward, forwardVector);
if (Math.Abs(dot - (-1.0f)) < 0.000001f)
{
return new Quaternion(Vector3.up.x, Vector3.up.y, Vector3.up.z, 3.1415926535897932f);
}
if (Math.Abs(dot - (1.0f)) < 0.000001f)
{
return Quaternion.identity;
}
float rotAngle = (float)Math.Acos(dot);
Vector3 rotAxis = Vector3.Cross(Vector3.forward, forwardVector);
rotAxis = Vector3.Normalize(rotAxis);
return CreateFromAxisAngle(rotAxis, rotAngle);
}
// just in case you need that function also
public static Quaternion CreateFromAxisAngle(Vector3 axis, float angle)
{
float halfAngle = angle * .5f;
float s = (float)System.Math.Sin(halfAngle);
Quaternion q;
q.x = axis.x * s;
q.y = axis.y * s;
q.z = axis.z * s;
q.w = (float)System.Math.Cos(halfAngle);
return q;
}
This code comes from here:
https://gamedev.stackexchange.com/questions/15070/orienting-a-model-to-face-a-target
I just slightly modified it to fit my case, which was implementation of the transform.LookAt without using Unity3D.
Both of current answers have various problems for edge cases. The accepted answer is not correct for other reasons as well including the fact that it sets w=pi for one of the cases and also it doesn't do proper norms. After looking around quite a bit and testing several cases, I also found out that you need front and up vector to do this computation. So without further ado below is the code I'm using:
Quaternion lookAt(const Vector3f& sourcePoint, const Vector3f& destPoint, const Vector3f& front, const Vector3f& up)
{
Vector3f toVector = (destPoint - sourcePoint).normalized();
//compute rotation axis
Vector3f rotAxis = front.cross(toVector).normalized();
if (rotAxis.squaredNorm() == 0)
rotAxis = up;
//find the angle around rotation axis
float dot = VectorMath::front().dot(toVector);
float ang = std::acosf(dot);
//convert axis angle to quaternion
return Eigen::AngleAxisf(rotAxis, ang);
}
Bove uses popular Eigen library. If you don't want to use that then you might need following replacement for Eigen::AngleAxisf:
//Angle-Axis to Quaternion
Quaternionr angleAxisf(const Vector3r& axis, float angle) {
auto s = std::sinf(angle / 2);
auto u = axis.normalized();
return Quaternionr(std::cosf(angle / 2), u.x() * s, u.y() * s, u.z() * s);
}
Note that special cases for dot product 0 or 1 or -1 gets automatically handled because normalized() returns 0 for the zero vector in Eigen library.
On the side note, for all your conversions worries, this is a great document to go to.
You don't need to use acos and axis angle (which will in turn do 2 more trig functions) to get the quaternion from 2 vectors:
public static Quaternion LookAt(Vector3 sourcePoint, Vector3 destPoint)
{
Vector3 forwardVector = Vector3.Normalize(destPoint - sourcePoint);
Vector3 rotAxis = Vector3.Cross(Vector3.forward, forwardVector);
float dot = Vector3.Dot(Vector3.forward, forwardVector);
Quaternion q;
q.x = rotAxis.x;
q.y = rotAxis.y;
q.z = rotAxis.z;
q.w = dot+1;
return q.normalize();
}
The reason for the dot+1 and subsequent normalize is because if you don't, you'll get the quaternion for the double rotation. Those 2 steps will effectively do slerp(identity, q, 0.5) which will be the proper quaternion.

Mapping a 3D rectangle to a 2D screen

I've searched SO but I just can't figure this out. The other questions didn't help or I didn't understand them.
The problem is, I have a bunch of points in a 3D image. The points are for a rectangle, which doesn't look like a rectangle from the 3d camera's view because of perspective. The task is to map the points from that rectangle to the screen. I've seen some ways which some call "quad to quad transformations" but most of them are for mapping a 2d quadrilateral to another one. But I've got the X, Y and Z coordinates of the rectangle in the real world so I'm looking for some easier ways. Does anyone know any practical algorithm or method of doing this?
If it helps, my 3d camera is actually a Kinect device with OpenNI and NITE middlewares, and I'm using WPF.
Thanks in advance.
edit:
I also found the 3d-projection page on Wikipedia that used angles and cosines but that seems to be a difficult way (finding angles in the 3d image) and I'm not sure if it's the real solution or not.
You might want to check out projection matrices
That's how any 3D rasterizer "flattens" 3D volumes on a 2D screen.
See this code to get the projection matrix for a given WPF camera:
private static Matrix3D GetProjectionMatrix(OrthographicCamera camera, double aspectRatio)
{
// This math is identical to what you find documented for
// D3DXMatrixOrthoRH with the exception that in WPF only
// the camera's width is specified. Height is calculated
// from width and the aspect ratio.
double w = camera.Width;
double h = w / aspectRatio;
double zn = camera.NearPlaneDistance;
double zf = camera.FarPlaneDistance;
double m33 = 1 / (zn - zf);
double m43 = zn * m33;
return new Matrix3D(
2 / w, 0, 0, 0,
0, 2 / h, 0, 0,
0, 0, m33, 0,
0, 0, m43, 1);
}
private static Matrix3D GetProjectionMatrix(PerspectiveCamera camera, double aspectRatio)
{
// This math is identical to what you find documented for
// D3DXMatrixPerspectiveFovRH with the exception that in
// WPF the camera's horizontal rather the vertical
// field-of-view is specified.
double hFoV = MathUtils.DegreesToRadians(camera.FieldOfView);
double zn = camera.NearPlaneDistance;
double zf = camera.FarPlaneDistance;
double xScale = 1 / Math.Tan(hFoV / 2);
double yScale = aspectRatio * xScale;
double m33 = (zf == double.PositiveInfinity) ? -1 : (zf / (zn - zf));
double m43 = zn * m33;
return new Matrix3D(
xScale, 0, 0, 0,
0, yScale, 0, 0,
0, 0, m33, -1,
0, 0, m43, 0);
}
/// <summary>
/// Computes the effective projection matrix for the given
/// camera.
/// </summary>
public static Matrix3D GetProjectionMatrix(Camera camera, double aspectRatio)
{
if (camera == null)
{
throw new ArgumentNullException("camera");
}
PerspectiveCamera perspectiveCamera = camera as PerspectiveCamera;
if (perspectiveCamera != null)
{
return GetProjectionMatrix(perspectiveCamera, aspectRatio);
}
OrthographicCamera orthographicCamera = camera as OrthographicCamera;
if (orthographicCamera != null)
{
return GetProjectionMatrix(orthographicCamera, aspectRatio);
}
MatrixCamera matrixCamera = camera as MatrixCamera;
if (matrixCamera != null)
{
return matrixCamera.ProjectionMatrix;
}
throw new ArgumentException(String.Format("Unsupported camera type '{0}'.", camera.GetType().FullName), "camera");
}
You could do a basic orthographic projection (I'm thinking in terms of raytracing, so this might not apply to what you're doing):
The code is quite intuitive:
for y in image.height:
for x in image.width:
ray = new Ray(x, 0, z, Vector(0, 1, 0)) # Pointing forward
intersection = prism.intersection(ray) # Since you aren't shading, you can check only for intersections.
image.setPixel(x, y, intersection) # Returns black and white image of prism mapped to plane
You just shoot vectors with a direction of (0, 1, 0) directly out into space and record which ones hit.
I found this. Uses straight forward mathematics instead of matricies.
This is called perspective projection to convert from a 3D vertex to a 2D screen vertex. I used this to help me with my 3D program I have made.
HorizontalFactor = ScreenWidth / Tan(PI / 4)
VerticalFactor = ScreenHeight / Tan(PI / 4)
ScreenX = ((X * HorizontalFactor) / Y) + HalfWidth
ScreenY = ((Z * VerticalFactor) / Y) + HalfHeight
Hope this could help. I think its what you where looking for. Sorry about the formatting (new here)
Mapping points in a 3d world to a 2d screen is part of the job of frameworks like OpenGL and Direct3d. It's called Rasterisation like Heandel said. Perhaps you could use Direct3d?

Resources