<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>www.hackification.com &#187; Experiments</title>
	<atom:link href="http://www.hackification.com/category/experiments/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.hackification.com</link>
	<description></description>
	<lastBuildDate>Sat, 05 Jun 2010 11:16:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Resizing Single-Image-Rollovers Using jQuery</title>
		<link>http://www.hackification.com/2009/09/02/resizing-single-image-rollovers-using-jquery/</link>
		<comments>http://www.hackification.com/2009/09/02/resizing-single-image-rollovers-using-jquery/#comments</comments>
		<pubDate>Wed, 02 Sep 2009 14:28:00 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Experiments]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[rollovers]]></category>
		<category><![CDATA[sprites]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=252</guid>
		<description><![CDATA[In this article I describe how to create shaped buttons in HTML/CSS that size to their content, have roll-over state, and require only a single image, using jQuery. I&#8217;m sure most web developers know about image rollovers (using separate images for normal and &#8220;hover&#8221; states of anchors). Hopefully also the use of &#8220;CSS Sprites&#8221; is [...]]]></description>
			<content:encoded><![CDATA[<p>In this article I describe how to create shaped buttons in HTML/CSS that size to their content, have roll-over state, and require only a single image, using jQuery.</p>
<p><span id="more-252"></span></p>
<p>I&#8217;m sure most web developers know about image rollovers (using separate images for normal and &#8220;hover&#8221; states of anchors). Hopefully also the use of &#8220;<a href="http://www.alistapart.com/articles/sprites" target="_blank">CSS Sprites</a>&#8221; is becoming better known &#8211; combining the normal and rollover images into a single physical image file to speed up load times and reduce flicker. I won&#8217;t cover those techniques here.</p>
<p>However, if you want the anchor or button to size to its contents, it&#8217;s more difficult to make use of these techniques. Here&#8217;s one way.</p>
<p><img class="aligncenter size-full wp-image-258" title="Sizing Rollovers" src="http://www.hackification.com/wp-content/uploads/2009/09/SizingRollovers.png" alt="Sizing Rollovers" width="414" height="127" /></p>
<p style="text-align: center;"><em>(The final result &#8211; <a href="http://www.hackification.com/jquery-examples/sizing-rollovers/sizing-rollovers.htm" target="_blank">view demo</a>).</em></p>
<p><strong>Start With Markup</strong></p>
<p>Before diving into fancy techniques, get the markup down as you would like it, if you didn&#8217;t have to style anything.</p>
<pre>&lt;a href="..." class="rollover"&gt;Button Text&lt;/a&gt;</pre>
<p>Ideally we want the markup to be clean and not compromised by styling requirements.</p>
<p><strong>Handle Degradation Gracefully</strong></p>
<p>My technique is going to make use of JavaScript, so let&#8217;s handle the case where the user has it disabled for some reason. Here&#8217;s some very basic CSS to give the button a simple style:</p>
<pre>a.rollover
{
  background-color: #00f;
  border: solid 1px #000;
  color: #fff;
  font-weight: bold;
  padding: 4px;
  text-decoration: none;
}

a.rollover:hover
{
  background-color: #008;
}</pre>
<p><strong>Add Styling Naively</strong></p>
<p>Next, I&#8217;m going to add some rollover styling &#8211; but in a way that isn&#8217;t complete. Firstly I created a simple rollover image, but made it very wide &#8211; it needs to be at least as wide as the widest button is ever going to be:</p>
<p><img class="aligncenter size-full wp-image-256" title="Button Rollover" src="http://www.hackification.com/wp-content/uploads/2009/09/buttons.png" alt="Button Rollover" width="657" height="123" /></p>
<p>I&#8217;m going to define my rollover styling against a class selector of &#8220;extra&#8221; &#8211; you&#8217;ll see where that comes from in a moment.</p>
<pre>a.rollover.extra
{
  background: url(buttons.png) repeat-x left 0;
  border: none;
  height: 27px;
  padding: 23px 40px 10px 40px;
  position: relative;
}

a.rollover.extra:hover
{
  background-position: left -57px;
}</pre>
<p>Note that we&#8217;ve had to undo some of the styles applied previously, such as border.</p>
<p>We&#8217;re kind of getting there, but our buttons won&#8217;t look correct on the right-hand-side.</p>
<p><strong>Use JavaScript To Add Styling Markup</strong></p>
<p>To fix the right-hand end-caps, we need to modify our markup. However, I really don&#8217;t want to have to do that on my pages &#8211; afterall, I might change my mind about the site styling.</p>
<p>Here I recommend using JavaScript to tweak at runtime the markup to what we need. I&#8217;m going to use jQuery for this:</p>
<pre>$(function() {
  $('.rollover')
    .addClass('extra')
    .append('&lt;div class="cap"&gt;&lt;/div&gt;');
});</pre>
<p>Basically, when the pad is ready, I find all elements with class &#8220;rollover&#8221;, add another class (&#8220;extra&#8221;), and append into the rollover button an empty span element which has a class of &#8220;cap&#8221;.</p>
<p>That class &#8220;extra&#8221; triggers the image rollovers. The &#8220;cap&#8221; span can be styled as follows:</p>
<pre>a.rollover.extra .cap
{
  background: url(buttons.png) no-repeat right 0;
  height: 100%;
  position: absolute;
  right: 0;
  top: 0;
  width: 40px;
}

a.rollover.extra:hover .cap
{
  background-position: right -57px;
}</pre>
<p>And voila!</p>
<blockquote><p><a href="http://www.hackification.com/jquery-examples/sizing-rollovers/sizing-rollovers.htm" target="_blank">If you&#8217;d like to see this technique in action, please view the demo</a>.</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2009/09/02/resizing-single-image-rollovers-using-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Debug.Assert Considered Pointless</title>
		<link>http://www.hackification.com/2009/06/10/debug-assert-considered-pointless/</link>
		<comments>http://www.hackification.com/2009/06/10/debug-assert-considered-pointless/#comments</comments>
		<pubDate>Wed, 10 Jun 2009 20:26:24 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Experiments]]></category>
		<category><![CDATA[Links]]></category>
		<category><![CDATA[Opinion]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[assert]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=214</guid>
		<description><![CDATA[One thing I was told as a young programmer was to make good use of assertions for checking code. As time goes by however, I can see less and less use for assertions. I&#8217;m starting to think they&#8217;re pretty useless. (I&#8217;m going to use C# in my examples here: some of these points might not [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-225" style="margin-left: 10px; margin-right: 10px;" title="Debug Assert Stop" src="http://www.hackification.com/wp-content/uploads/2009/06/stop.png" alt="Debug Assert Stop" width="96" height="96" />One thing I was told as a young programmer was to make good use of assertions for checking code. As time goes by however, I can see less and less use for assertions. I&#8217;m starting to think they&#8217;re pretty useless.</p>
<p><span id="more-214"></span></p>
<p>(I&#8217;m going to use C# in my examples here: some of these points might not apply to all languages. By default, an assertion will not fire in a C# release build, and furthermore, the code inside will not even be executed).</p>
<p><em>Update 2009-06-11: I probably haven&#8217;t been clear enough, but luckily various commenters have picked up on this: I&#8217;m not advocating removing assertions and replacing them with nothing! In general, I think assertions should be replaced with a stronger check that also runs (or can run) in a release build.</em></p>
<p><strong>1. Pointless Guard Checking</strong></p>
<p>Unfortunately in my coding travels I see quite a bit of code like this:</p>
<pre>void Foo(Bar bar)
{
  Debug.Assert(bar != null);

  bar.DoSomething();
}</pre>
<p>What&#8217;s the point? If bar is null, then using it will throw an exception anyway. Why add unnecessary lines of code that make reading harder?</p>
<p><strong>2. Bad Argument Checking</strong></p>
<p>But, you&#8217;re thinking, what if the usage is separated from the assignment?</p>
<pre>class Foo
{
  public Foo(Bar bar)
  {
    Debug.Assert(bar != null);

    _bar = bar;
  }

  public void Method()
  {
    _bar.DoSomething();
  }

  private Bar _bar;
}</pre>
<p>True, you want to catch the error as it happens, not later on in the method. But shouldn&#8217;t you be throwing an ArgumentNullException instead?</p>
<p><strong>3. Difficult Detective Work</strong></p>
<p>So now you&#8217;re telling me that you&#8217;re not writing component code, and the only client of this class will be the application it&#8217;s embedded in. Why not save some effort and skimp on the checking code, and make it debug-only?</p>
<p>Fine idea&#8230; until you get a crash report from one of your users, and the stacktrace points to a NullReferenceException in Method(). Now you have to figure out where the null value got passed to the constructor&#8230; a potentially much more difficult task.</p>
<p><strong>4. Differences Between Debug and Release</strong></p>
<p>If you&#8217;re like me, you generally run the applications in debug. Your customers however, run in release. Why make the differences between these two versions any bigger? Even if you don&#8217;t intend your debug statements to change program state, it&#8217;s all too easy to accidentally do so:</p>
<ul>
<li>Running lazy-initializers or singleton constructors;</li>
<li>Loading data from the database via an ORM;</li>
<li>Moving data in or out of a cache;</li>
<li>Running static constructors.</li>
</ul>
<p><strong>5. Too-Shy Sanity-Checking</strong></p>
<p>Sometimes, despite the above warning, you really do have sanity-checking code that you&#8217;d like to run in a development or test environment to catch regressions, but which is too slow to give to general users. (I read somewhere that Excel has two computation engines: a simple, slow, reference one, and a fast, parallel, release one. Testers can run the two in parallel, and any differences are automatically flagged as errors).</p>
<p>So you might be tempted to do something like:</p>
<pre>Debug.Assert( SlowlyAndCarefullyVerifyInternalState() );</pre>
<p>The problem I have with this is that the debug/release division is way too blunt.</p>
<ul>
<li>Suppose a tester wants to test a release build, but also perform the sanity-checking?</li>
<li>Suppose a customer finds a bug in a complex calculation, and you want them to run the checks?</li>
<li>Suppose a developer wants to debug performance issues in the non-checked code?</li>
</ul>
<p>I would suggest you move the conditionals for code like this to a (possibly hidden) configuration setting. Someone wants to run in slow-and-safe mode? No problem, just tell them the registry setting (or whatever). By all means, change the splash screen or title bar or whatever so it says &#8220;test mode&#8221;.</p>
<p>The advantages of this method are:</p>
<ul>
<li>Anyone can turn it on and off;</li>
<li>Sanity-checking can be controlled at a much finer granularity than all-on / all-off.</li>
</ul>
<p><strong>6. Is It Recoverable, Or Not?</strong></p>
<p>The final argument against debug assertions concerns just exactly what an assertion means.</p>
<p>To my mind, an assertion is different to a simple flow-control test (&#8220;did the user enter a valid number?&#8221;), which is something the program can (should) handle. By definition, an assertion is checking for a disallowed state. An assertion doesn&#8217;t check for incorrect data; it checks for an incorrect program. Continuing after an assertion leads to undefined behaviour.</p>
<p>So how can you continue? More to the point, why should a user even be allowed to continue? If the state really is unrecoverable, then fail. Fail fast, log the error, and bail (possibly trying to allow the user to save work, or whatever). Having a release-build application continue after what would have been an assertion is just plain wrong.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2009/06/10/debug-assert-considered-pointless/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Using WPF To Generate Web Images</title>
		<link>http://www.hackification.com/2009/04/10/using-wpf-to-generate-web-images/</link>
		<comments>http://www.hackification.com/2009/04/10/using-wpf-to-generate-web-images/#comments</comments>
		<pubDate>Fri, 10 Apr 2009 21:27:37 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Experiments]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[images]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=95</guid>
		<description><![CDATA[Recently I needed to display rotated graphics within a web-page. Since there&#8217;s no way to do that cross-browser using CSS, I needed to auto-generate a collection of pre-rotated images that could be displayed as CSS sprites. I&#8217;ve found that WPF (Windows Presentation Foundation) is great for generating batches of images suitable for use in web [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I needed to display rotated graphics within a web-page. Since there&#8217;s no way to do that cross-browser using CSS, I needed to auto-generate a collection of pre-rotated images that could be displayed as CSS sprites. I&#8217;ve found that WPF (Windows Presentation Foundation) is great for generating batches of images suitable for use in web apps.</p>
<p><span id="more-95"></span></p>
<p>Let&#8217;s start with an example graphic, Arrow.xaml:</p>
<pre>&lt;UserControl x:Class="WebImagesGenerator.Graphics.Arrow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Height="64" Width="64"&gt;
  &lt;Canvas Width="64" Height="64"&gt;
    &lt;Polygon Points="32,4 60,32 42,32 42,60 22,60 22,32 4,32"
      Fill="Red" Stroke="Black"
      StrokeThickness="3" StrokeLineJoin="Round" /&gt;
  &lt;/Canvas&gt;
&lt;/UserControl&gt;</pre>
<p>That&#8217;s just a standard XAML file, nothing fancy there.</p>
<p>Rendering WPF content to an image is really easy; you use the RenderTargetBitmap class. I wanted to be able to produce a strip of images, all the same except rotated, that can be used as CSS sprites. For my actual web application, I have a quick console application that generates the images as a batch. If I ever change the XAML files, I can quickly re-generate all the auto-generated images in my project just be running my console application.</p>
<p>Let&#8217;s get started on the console application:</p>
<pre>[STAThread]
static void Main( string[] args )
{
  var arrow = new Graphics.Arrow();

  SaveStrip( arrow, GenerateSeries( 0, 360, 10 )
           , "..\\..\\Testing\\arrows.png" );
}</pre>
<p>WPF must be run in a [STAThread] context. I create an instance of my graphic, then call my SaveStrip routine. GenerateSeries simply returns an array of integers:</p>
<pre>static int[] GenerateSeries( int start, int end, int step )
{
  var series = new List&lt;int&gt;();

  for( var v = start; v &lt; end; v += step )
  {
    series.Add( v );
  }

  return series.ToArray();
}</pre>
<p>The real magic happens in SaveStrip:</p>
<pre>static void SaveStrip( FrameworkElement fe, int[] angles, string filename )
{
  var outer = new Canvas();

  outer.Width = fe.Width * angles.Length;
  outer.Height = fe.Height;

  outer.Children.Add( fe );

  outer.Arrange( new Rect( 0, 0, outer.Width, outer.Height ) );

  var bmp = new RenderTargetBitmap
    ( (int) fe.Width * angles.Length
    , (int) fe.Height, 96, 96, PixelFormats.Pbgra32 );

  for( var i = 0; i &lt; angles.Length; ++i )
  {
    var transforms = new TransformGroup();

    transforms.Children.Add
      ( new RotateTransform( angles[i], fe.Width / 2, fe.Height / 2 ) );

    fe.RenderTransform = transforms;
    fe.SetValue( Canvas.LeftProperty, i * fe.Width );

    // The following line is VITAL!
    outer.Arrange( new Rect( 0, 0, outer.Width, outer.Height ) );

    bmp.Render( fe );
  }

  var encoder = new PngBitmapEncoder();

  encoder.Frames.Add( BitmapFrame.Create( bmp ) );

  using( var stream = File.Create( filename ) )
  {
    encoder.Save( stream );
  }
}</pre>
<p>When I first tried this technique, all my output bitmaps were completely blank. After debugging for a while, I realised that all my graphics were of zero size. You MUST call Arrange() on your elements before calling Render(), otherwise they won&#8217;t have been laid out properly.</p>
<p>When run, this console app produces the following (reduced in size to fit):</p>
<p><img class="alignnone size-full wp-image-102" title="WPF-Generated Images" src="http://www.hackification.com/wp-content/uploads/2009/04/arrows1.png" alt="WPF-Generated Images" width="580" height="15" /></p>
<p>Fantastic! To get a better idea of how such images might appear in a web-page, I&#8217;ve created a little HTML+jQuery demo to see a very quick example of the images in use:</p>
<blockquote><p><strong><a href="http://www.hackification.com/jquery-examples/test-wpf-images.htm" target="_blank">View Demo</a></strong></p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2009/04/10/using-wpf-to-generate-web-images/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>LINQ-to-Entities: Follow-Up</title>
		<link>http://www.hackification.com/2008/12/04/linq-to-entities-follow-up/</link>
		<comments>http://www.hackification.com/2008/12/04/linq-to-entities-follow-up/#comments</comments>
		<pubDate>Thu, 04 Dec 2008 15:08:14 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Experiments]]></category>
		<category><![CDATA[Opinion]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[entities]]></category>
		<category><![CDATA[linq]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=62</guid>
		<description><![CDATA[There&#8217;s been a bit of discussion about my last article, &#8220;LINQ-to-Entities: The Blackberry Storm of ORMs?&#8220;. I thought I&#8217;d try to clear up a bit of what I was trying to say, especially with regards my statement about LINQ-to-Entities returning differing values depending on code order. Firstly, the discussions for reference: Discussion on Reddit; Post [...]]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s been a bit of discussion about my last article, &#8220;<a title="Permanent Link: LINQ-to-Entities: The Blackberry Storm of ORMs?" rel="bookmark" href="../2008/12/03/linq-to-entities-the-blackberry-storm-of-orms/">LINQ-to-Entities: The Blackberry Storm of ORMs?</a>&#8220;. I thought I&#8217;d try to clear up a bit of what I was trying to say, especially with regards my statement about LINQ-to-Entities returning differing values depending on code order.</p>
<p><span id="more-62"></span></p>
<p>Firstly, the discussions for reference:</p>
<ul>
<li><a title="LINQ-to-Entities: The Blackberry Storm of ORMs? : programming" href="http://www.reddit.com/r/programming/comments/7h345/linqtoentities_the_blackberry_storm_of_orms/" target="_blank">Discussion on Reddit</a>;</li>
<li><a title="Does LINQ-to-Entities really return different results depending on previous queries?" href="http://www.infoq.com/news/2008/12/Lazy-Loading" target="_blank">Post on InfoQ</a>.</li>
</ul>
<p><strong>#1: It&#8217;s Not Functional</strong></p>
<p>Imagine the following SQL statements:</p>
<pre>SELECT * FROM [Order] WHERE [CustomerId] = 1
SELECT * FROM [Order]
SELECT * FROM [Order] WHERE [CustomerId] = 1</pre>
<p><em>In the absence of any other concurrent users</em>, if I suggested that the first and third <em>identical queries</em> should return different values, you&#8217;d think I was nuts. But that&#8217;s exactly what LINQ-to-Entities does.</p>
<p>The world is moving towards functional programming. Functions named &#8220;Get&#8221; (or &#8220;SELECT&#8221;) really shouldn&#8217;t have side-effects. LINQ-to-Entities violates the principle of least surprise &#8211; most coders would expect a SELECT to have no (functional) side-effects.</p>
<p><strong>#2: Performance Over Correctness</strong></p>
<p>I understand why LINQ-to-Entities doesn&#8217;t load the values in the first instance. There is a danger when using ORMs that queries inside loops can lead to N+1 queries, killing performance. (In my last job I was involved in writing a custom ORM system, so I know a <em>little </em>about the problem).</p>
<p>However, in my opinion there really are two options to solve this:</p>
<ol>
<li>Performance indicators are applied as &#8216;hints&#8217; that don&#8217;t affect functionality &#8211; if you find a block of code is producing bad or multiple queries, you add pre-loading hints.</li>
<li>Performance is determined to be sufficiently important that idea #1 is no good. In that case, if the appropriate pre-loads haven&#8217;t been issued, an exception is thrown.</li>
</ol>
<p>LINQ-to-Entities have decided to go for &#8216;option&#8217; #3, silently return the wrong answer. I always thought the guiding principle of .NET was <em>managed coding</em> &#8211; sacrifice a little performance for a great deal of safety: bounds checking, type checking, and so forth. Perhaps the ADO.NET team still think they&#8217;re writing C code?</p>
<p><strong>#3: It&#8217;s Not A Replacement To LINQ-to-SQL</strong></p>
<p>There&#8217;s no one correct way to write an ORM. Different applications have different requirements. A general purpose ORM will never satisfy 100% of developers. Fine. I&#8217;m happy with that; there&#8217;s a nice market for specialist providers.</p>
<p>What I&#8217;m not happy with is that while LINQ-to-SQL seemed to make 90% of developers happy, it&#8217;s being <em>replaced </em>with LINQ-to-Entities that (judging by the feedback I&#8217;ve seen) makes far less developers happy.</p>
<p>I&#8217;m fine with the ADO.NET team writing a solution that fills that 10% gap or otherwise augments LINQ-to-SQL. I&#8217;m not happy with them replacing a 90% solution with a specialist 10% solution.</p>
<p><strong>#4: It Hinders Common Scenarios</strong></p>
<p>I work largely in the web app development area, which I understand is just one of many dev scenarios that Microsoft must support. Having said that, it is an increasingly large area (perhaps <em>the </em>largest commercial area, considering that Windows desktop applications are essentially dead apart from internal coporate dev).</p>
<p>Let&#8217;s take a typical data-driven web-page:</p>
<p><a title="User stusmith - StackOverflow" href="http://stackoverflow.com/users/6604/stusmith" target="_blank">http://stackoverflow.com/users/6604/stusmith</a></p>
<p>(Now you can put a face to my writing).</p>
<p>I can imagine the pseudo-LINQ being something like this:</p>
<pre>var user = (from u in data.Users
            where u.UserName == "stusmith"
            select u).Single();

// Display the header details.

var questions = from q in user.Questions
                orderby q.Votes desc
                select q;

// Display each question.

var answers = from a in user.Answers
              orderby a.Votes desc
              select a;

// Display each answer.

// Etc for tags, badges, and so forth.</pre>
<p>It&#8217;s very common, doesn&#8217;t involve any performance issues, but LINQ-to-Entities demands that I explicitly load from the database.</p>
<p><strong>#5: Is It Nothing More Than LINQ-to-Objects &#8211; or &#8211; Where&#8217;s The Magic Gone?</strong></p>
<p>The response to my article from the ADO.NET guys is:</p>
<p><em>&#8220;The case here is actually a misunderstanding on the part of the author. The second query that they [sic] author runs, var order, is actually a LINQ to Objects query, not a LINQ to Entities (or LINQ to SQL) query.&#8221;</em></p>
<p>So&#8230; LINQ-to-Entities only kicks in when I either (a) query top-level tables, or (b) call Load() methods?</p>
<p>In which case, LINQ-to-Entities actually does a lot less than LINQ-to-SQL. Another quote:</p>
<p><em>&#8220;&#8230;the explicit loading in the Entity Framework means that it will not make extra trips to the database &#8220;magically&#8221; for you.&#8221;</em></p>
<p>My point exactly.</p>
<blockquote><p>LINQ-to-Entities is like LINQ-to-SQL <em>but with the magic removed</em>.</p></blockquote>
<p>(Maybe that should be their marketing slogan? &#8220;LINQ-to-Entities &#8211; now with 100% less magic!&#8221;).</p>
<p>I always thought the point of an ORM was that it was a <em>transparent mapping</em> from database to objects. I can write explicit loads myself; they&#8217;re called <em>SELECT statements</em>. The wonder of LINQ-to-SQL was that I didn&#8217;t have to. Now I do. <strong>Is that really progress?</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2008/12/04/linq-to-entities-follow-up/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>LINQ-to-Entities: The Blackberry Storm of ORMs?</title>
		<link>http://www.hackification.com/2008/12/03/linq-to-entities-the-blackberry-storm-of-orms/</link>
		<comments>http://www.hackification.com/2008/12/03/linq-to-entities-the-blackberry-storm-of-orms/#comments</comments>
		<pubDate>Wed, 03 Dec 2008 11:35:16 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Experiments]]></category>
		<category><![CDATA[Opinion]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[entities]]></category>
		<category><![CDATA[linq]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=60</guid>
		<description><![CDATA[(In case you missed the reference, the new Blackberry Storm has been widely slammed as an inferior copy of the iPhone, and was released basically unfinished to try to fend off its better rival). Note: the first part of this article is a bit of an opinionated rant &#8211; if you want to skip to [...]]]></description>
			<content:encoded><![CDATA[<p>(In case you missed the reference, the new Blackberry Storm has been <a title="No Keyboard? And You Call This a BlackBerry? " href="http://www.nytimes.com/2008/11/27/technology/personaltech/27pogue.html?_r=3&amp;bl&amp;ex=1227934800&amp;en=e69773c4efd24c5c&amp;ei=5087%0A" target="_blank">widely</a> <a title="Can Stephen Fry kill a gadget?" href="http://www.bbc.co.uk/blogs/technology/2008/11/can_stephen_fry_kill_a_gadget.html" target="_blank">slammed</a> as an inferior copy of the iPhone, and was released basically unfinished to try to fend off its better rival).</p>
<p><em>Note: the first part of this article is a bit of an opinionated rant &#8211; if you want to skip to the actual code examples a little further down and make up your own mind, that&#8217;s fine by me.</em></p>
<p><span id="more-60"></span></p>
<p><strong>A Bit of History<br />
</strong></p>
<p>One of the best new features to appear in .NET recently has been LINQ (language integrated query) &#8211; and particularly, LINQ-to-SQL. This marvellous bit of the framework lets you define a mapping between database and objects (or more likely, automatically generate the mapping from a database schema), and then query and update the database in a type-safe manner, using syntax that nicely bridges the gap between C# and SQL.</p>
<p>Unfortunately, LINQ-to-SQL was a bit of a skunkworks project &#8211; while hyped projects such as ObjectSpaces and WinFS collapsed under their own weight, LINQ to SQL quietly delivered.</p>
<p>Clearly for political reasons this successful ORM project had to be stopped, and fast. (<a title="Move over LINQ to SQL - you have served your purpose" href="http://blogs.conchango.com/simonmunro/archive/2008/11/02/move-over-linq-to-sql-you-have-served-your-purpose.aspx" target="_blank">Nice article here</a>).</p>
<p>So enter LINQ-to-Entities &#8211; the ADO.NET team&#8217;s &#8220;answer&#8221; to LINQ-to-SQL. Unfortunately, while LINQ-to-SQL was a wonderful, polished jewel of functionality that was a nice example of IJW (&#8220;it just worked&#8221;), LINQ-to-Entities seems to be a product of <a title="Don't Let Architecture Astronauts Scare You" href="http://www.joelonsoftware.com/articles/fog0000000018.html" target="_blank">Architecture Astronauts</a> who would rather bamboozle us with their cleverness than actually provide useful solutions.</p>
<p><strong>Enough Ranting &#8211; Some Examples</strong></p>
<p>I&#8217;ve written a small handful of applications using LINQ-to-SQL, so when I found that LINQ-to-Entities was its replacement, I thought I&#8217;d start my next application experiment using it. I&#8217;m going to include the source for these examples in a little test application at the end of this article, if you&#8217;d like to try it for yourself. I&#8217;ve used identical code for both LINQ-to-SQL and LINQ-to-Entities, with minor changes for logging and creation of the entity model. Both schemas were imported from the same database.</p>
<p><strong>The Schema</strong></p>
<p>The schema contains just two tables, joined by a single foreign key relationship:</p>
<p><img class="aligncenter size-full wp-image-61" title="Database Schema" src="http://www.hackification.com/wp-content/uploads/2008/12/linqschema.png" alt="" width="194" height="237" /></p>
<p><strong>Problem #1 &#8211; Silently Gives Differing Results</strong></p>
<p>This problem is to my mind the worst that I&#8217;ve found so far.</p>
<p>Suppose I search for a customer:</p>
<pre>var alice = data.Customers.First( c =&gt; c.Name == "Alice" );</pre>
<p>Fine, that works nicely. Now let&#8217;s see if I can find one of her orders:</p>
<pre>var order = ( from o in alice.Orders
              where o.Item == "Item_Name"
              select o ).FirstOrDefault();</pre>
<p>LINQ-to-SQL will find the child row. <em>LINQ-to-Entities will silently return nothing.</em></p>
<p>Now let&#8217;s suppose I iterate through all orders in the database:</p>
<pre>foreach( var order in data.Orders )
{
  Console.WriteLine( "Order: " + order.Item );
}</pre>
<p>And now repeat my search:</p>
<pre>var order = ( from o in alice.Orders
              where o.Item == "Item_Name"
              select o ).FirstOrDefault();</pre>
<p>Wow! LINQ-to-Entities is suddenly telling me the child object exists, despite telling me earlier that it didn&#8217;t!</p>
<p>Let me put that in bigger letters in case you missed the significance:</p>
<blockquote><p><strong>LINQ-to-Entities will return different results depending on what previous queries you&#8217;ve executed!</strong></p></blockquote>
<p>That&#8217;s hardly a transparent mapping between database and objects.</p>
<p><strong>Problem #2 &#8211; No Support for Constant-Folding</strong></p>
<p>Consider the following code:</p>
<pre>using( var data = new LinqToEntities() )
{
  var names = new[] { "Alice", "Bob", "Dummy" };

  for( var i = 0; i &lt; names.Length; ++i )
  {
    var customers = from c in data.Customers
                    where c.Name == names[i]
                    select c;

    // Do something with the customers found.
  }
}</pre>
<p>LINQ-to-SQL handles this fine, treating names[i] as a constant expression. LINQ-to-Entities fails with:</p>
<p><em>&#8220;The LINQ expression node type &#8216;ArrayIndex&#8217; is not supported in LINQ to Entities.&#8221;</em></p>
<p><strong>Problem #3 &#8211; No support for Single() or SingleOrDefault()</strong></p>
<p>LINQ-to-SQL supported a nice method of &#8216;asserting&#8217; that you were expecting zero or one results &#8211; for example if querying against a key:</p>
<pre>var customer = ( from c in data.Customers
                 where c.Name == "Alice"
                 select c ).SingleOrDefault();</pre>
<p>LINQ-to-Entities however says:</p>
<p><em>&#8220;The method &#8216;Single&#8217; is not supported by LINQ to Entities. Consider using the method &#8216;First&#8217; instead.&#8221;</em></p>
<p>But First() doesn&#8217;t express what I want &#8211; namely that more than one result is a logical error.</p>
<p><strong>Problem #4 &#8211; Exceptions</strong></p>
<p>The final problem I&#8217;ve noticed is that LINQ-to-Entities throws and catches exceptions internally. Just running the test application with exceptions turned on throws multiple exceptions:</p>
<pre>A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll

Additional information: Could not find file
'C:\&lt;snip&gt;\bin\Debug\System.Data.Resources.CodeGenerationSchema.xsd'.</pre>
<p>and</p>
<pre>A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll

Additional information: Could not find file
'C:\&lt;snip&gt;\bin\Debug\System.Data.Resources.EntityStoreSchemaGenerator.xsd'.</pre>
<p>I now have the choice between turning off exceptions (thus hampering my own debugging), or having to press &#8216;continue&#8217; several times. I guess they hadn&#8217;t heard of File.Exists().</p>
<p><strong>Bonus #1 &#8211; Refresh From Database</strong></p>
<p>OK, I&#8217;ve been a little mean to LINQ-to-Entities. Surely it has some good points?</p>
<p>From my perspective, there is just one feature that I like over LINQ-to-SQL. (I know it supports many-to-many mappings of tables and classes. Seriously, what tiny percentage of users would want to do that?). The designer in LINQ-to-Entities allows you to refresh your mappings from database changes, whereas LINQ-to-SQL forces you to either make the changes manually, or delete everything and re-import.</p>
<p>However, that&#8217;s a designer feature. Couldn&#8217;t we have had that for LINQ-to-SQL as well?</p>
<p><strong>Source Code</strong></p>
<p>If you&#8217;d like to try these examples out for yourself, I&#8217;ve included an ZIP file. You&#8217;ll need Visual Studio 2008 SP1, and MS SQL Server 2005 or later.</p>
<p>The ZIP file contains a create database script you&#8217;ll need to run, which creates a database called &#8216;LinqTest&#8217; and populates it with a few rows of data.</p>
<blockquote><p><a title="linqtest.zip" href="http://www.hackification.com/source/linqtest.zip">Download &#8220;linqtest.zip&#8221;, 14Kb.</a></p></blockquote>
<p><strong>Conclusion</strong></p>
<p>In my opinion, we seem to have given up on a perfectly good, working ORM solution (LINQ-to-SQL), and replaced it with a buggy, half-baked one (LINQ-to-Entities). I sure hope v2 improves matters, because for now, switching to the entity framework is a downgrade.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2008/12/03/linq-to-entities-the-blackberry-storm-of-orms/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Experiments in Ray-Tracing, Part 9: Interpolation</title>
		<link>http://www.hackification.com/2008/09/07/experiments-in-ray-tracing-part-9-interpolation/</link>
		<comments>http://www.hackification.com/2008/09/07/experiments-in-ray-tracing-part-9-interpolation/#comments</comments>
		<pubDate>Sun, 07 Sep 2008 16:11:40 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[Experiments]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[interpolation]]></category>
		<category><![CDATA[ray-tracing]]></category>
		<category><![CDATA[speed-up]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=36</guid>
		<description><![CDATA[In this article I&#8217;m going to present a technique that trades lower image quality for faster rendering time: interpolation. Instead of ray-tracing every single pixel, we instead start by tracing pixels in an evenly-spaced grid, say every two or four pixels. (So if we have an interpolation step of two, we trace one out of [...]]]></description>
			<content:encoded><![CDATA[<p>In this article I&#8217;m going to present a technique that trades lower image quality for faster rendering time: interpolation.</p>
<p>Instead of ray-tracing every single pixel, we instead start by tracing pixels in an evenly-spaced grid, say every two or four pixels. (So if we have an interpolation step of two, we trace one out of every four pixels, and if we have an interpolation step of four, we trace one out of every sixteen pixels).</p>
<p><img class="aligncenter size-full wp-image-37" title="Interpolating, two and four pixel separation" src="http://www.hackification.com/wp-content/uploads/2008/09/interpolate.png" alt="" width="380" height="170" /></p>
<p>The image on the left above represents the pixels that would be traced with an interpolation step of two; the image on the right, an interpolation step of four.</p>
<p>Once we&#8217;ve performed this initial trace, we then examine each square region formed by the grid of traced pixels. For each square region, there are two cases to consider:</p>
<ol>
<li>The four corner colors are roughly the same;</li>
<li>The four corner colors differ.</li>
</ol>
<p>Based on these two cases, we take one of two actions:</p>
<ol>
<li>If the four corner colors are roughly the same, we can save time by interpolating (estimating) the colors for the remaining pixels from the four corners.</li>
<li>If the corner colors differ, then we need to trace the rest of the pixels in the square region normally.</li>
</ol>
<p>(Alternatively for option two and a large interpolation step, we could subdivide the square and apply the same algorithm with a halved interpolation step).</p>
<p>(As an added bonus, if we want to anti-alias the scene, we only need to anti-alias the pixels in a square that we aren&#8217;t interpolating).</p>
<p>As an example, I&#8217;ve added debug code to display the interpolated pixels as green in my usual shiny-spheres-on-a-chessboard scene; interpolate step of two above, interpolate step of four below:</p>
<p><img class="aligncenter size-full wp-image-38" title="Interpolate step of two" src="http://www.hackification.com/wp-content/uploads/2008/09/interpolate2.png" alt="" width="266" height="256" /></p>
<p><img class="aligncenter size-full wp-image-39" title="Interpolate step of four" src="http://www.hackification.com/wp-content/uploads/2008/09/interpolate4.png" alt="" width="268" height="250" /></p>
<p>So what sort of speed-ups have I seen? Well, I haven&#8217;t put much effort into optimizing my interpolation algorithm, since I&#8217;m moving onto radiosity, but here&#8217;s some numbers:</p>
<ul>
<li>No interpolation: 360ms</li>
<li>Interpolation of two: 200ms</li>
<li>Interpolation of four: 230ms</li>
<li>Interpolation of eight: 310ms</li>
</ul>
<p>As you can see, there&#8217;s an optimal interpolation step, in this case, of two. As the interpolation step increases, it becomes more likely that the colors at the corner of each square will differ, and so less interpolation will happen. Higher interpolation steps are also more likely to introduce artifacts into the image.</p>
<p>As I mentioned at the start, this technique does trade off image quality for speed. In the images below, the upper image is properly traced; the lower one has been interpolated with a step of two. You will be able to see some blurring of the reflection of the chessboard in the spheres.</p>
<p><img class="aligncenter size-full wp-image-40" title="Normal Tracing" src="http://www.hackification.com/wp-content/uploads/2008/09/internormal.png" alt="" width="262" height="250" /></p>
<p><img class="aligncenter size-full wp-image-41" title="Interpolated Tracing" src="http://www.hackification.com/wp-content/uploads/2008/09/interfast.png" alt="" width="262" height="242" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2008/09/07/experiments-in-ray-tracing-part-9-interpolation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Experiments in Ray-Tracing, Part 8: Anti-Aliasing</title>
		<link>http://www.hackification.com/2008/08/31/experiments-in-ray-tracing-part-8-anti-aliasing/</link>
		<comments>http://www.hackification.com/2008/08/31/experiments-in-ray-tracing-part-8-anti-aliasing/#comments</comments>
		<pubDate>Sun, 31 Aug 2008 15:45:16 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[Experiments]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[anti-alias]]></category>
		<category><![CDATA[edges]]></category>
		<category><![CDATA[ray-tracing]]></category>
		<category><![CDATA[sobel]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=31</guid>
		<description><![CDATA[In this article I&#8217;ll explain how to perform anti-aliasing quickly, getting 5x sampling for a cost of just 2x the time. Anti-aliasing is a technique to remove the &#8220;jaggies&#8221; in a rendered image. Let&#8217;s start with the standard shiny-balls-on-a-chessboard: I&#8217;ve zoomed into the image a little, so that you can see the pixellated edges. Anti-aliasing [...]]]></description>
			<content:encoded><![CDATA[<p>In this article I&#8217;ll explain how to perform anti-aliasing quickly, getting 5x sampling for a cost of just 2x the time.</p>
<p>Anti-aliasing is a technique to remove the &#8220;jaggies&#8221; in a rendered image. Let&#8217;s start with the standard shiny-balls-on-a-chessboard:</p>
<p><img class="aligncenter size-full wp-image-32" title="No Anti-Aliasing" src="http://www.hackification.com/wp-content/uploads/2008/08/antialias1.png" alt="" width="285" height="251" /></p>
<p>I&#8217;ve zoomed into the image a little, so that you can see the pixellated edges.</p>
<p>Anti-aliasing is most simply achieved by multi-sampling each pixel. Instead of casting one ray through the center of each pixel, you cast several rays (say around four), distributed within the pixel area. (You might want to distribute them in a grid, or you might want to distribute them randomly). We then take the average color value of each of those tracings.</p>
<p>Obviously however, this is going to slow down rendering &#8211; if I use 4x anti-aliasing, then the render will take four times as long. Not good. I can be a bit smarter about it though.</p>
<p>Looking at the image above, it&#8217;s only really the edges that are &#8220;jaggy&#8221; and need anti-aliasing. Everywhere else could be left alone really. So rather than tracing multiple rays through every single pixel, I just need to identify the edges. This is really easy and fast. Assuming I have a (non anti-aliased) rendered image, I can compute an &#8220;edge factor&#8221; for a single pixel as follows:</p>
<pre>var g = Math.Abs( ( p1 + 2 * p2 + p3 ) - ( p7 + 2 * p8 + p9 ) )
      + Math.Abs( ( p3 + 2 * p6 + p9 ) - ( p1 + 2 * p4 + p7 ) );</pre>
<p>Where p1..p9 are the pixel values around the pixel in question &#8211; p1 is above and to the left, p5 is the pixel itself, and p9 is below and to the right. (I perform this calculation on the intensity of the pixels, to avoid having to deal with RGB values).</p>
<p>[This is the <a title="Sobel operator" href="http://en.wikipedia.org/wiki/Sobel_operator" target="_blank">"Sobel operator"</a> - there are other faster edge detection operators, but this one seemed to work nicely for me.]</p>
<p>If <em>g</em> is bigger that some value (say 0.5), we consider the pixel to be part of an edge. In the following image, I&#8217;ve displayed the edges in red:</p>
<p><img class="aligncenter size-full wp-image-34" title="Edges Detected" src="http://www.hackification.com/wp-content/uploads/2008/08/antialias21.png" alt="" width="260" height="260" /></p>
<p>(Of course, in normal use you&#8217;d actually save the edge flags into a separate store, rather than overwriting your rendered image, but I&#8217;ve done this here for debugging).</p>
<p>So now, wherever I&#8217;ve detected an edge pixel in my status buffer, I cast a further four rays through it, and average them with the single ray I&#8217;ve already done prior to edge-detection:</p>
<p><img class="aligncenter size-full wp-image-35" title="Anti-Aliased Image" src="http://www.hackification.com/wp-content/uploads/2008/08/antialias3.png" alt="" width="270" height="254" /></p>
<p>I find that I can achieve 5x anti-aliasing for just a doubling in render time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2008/08/31/experiments-in-ray-tracing-part-8-anti-aliasing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Experiments in Ray-Tracing, Part 7: Multi-Threading</title>
		<link>http://www.hackification.com/2008/08/17/experiments-in-ray-tracing-part-7-multi-threading/</link>
		<comments>http://www.hackification.com/2008/08/17/experiments-in-ray-tracing-part-7-multi-threading/#comments</comments>
		<pubDate>Sun, 17 Aug 2008 21:08:04 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[Experiments]]></category>
		<category><![CDATA[ray-tracing]]></category>
		<category><![CDATA[threading]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=24</guid>
		<description><![CDATA[Now that I&#8217;ve covered the basics of ray-tracing, I&#8217;ll cover a few optimization techniques I&#8217;ve tried. Optimizations can be placed into three broad categories: Those which speed up the ray-tracing, without affecting the image; Those which speed up the ray-tracing, but degrade the image quality, and; Those which improve the image quality, but slow down [...]]]></description>
			<content:encoded><![CDATA[<p>Now that I&#8217;ve covered the basics of ray-tracing, I&#8217;ll cover a few optimization techniques I&#8217;ve tried. Optimizations can be placed into three broad categories:</p>
<ul>
<li>Those which speed up the ray-tracing, without affecting the image;</li>
<li>Those which speed up the ray-tracing, but degrade the image quality, and;</li>
<li>Those which improve the image quality, but slow down the ray-tracing.</li>
</ul>
<p>Obviously implementing the first set of optimizations is a no-brainer, but which blend of the others is of course up to you.</p>
<p>So let&#8217;s start with the most effective speed-up: multi-threading. Rendering each pixel in the image happens pretty much independently of the others, so we can partition the rendering amongst the available processors (or cores).</p>
<p>One naive way of partitioning the scene is to simply divide it into N parts, assuming we have N processors. This however doesn&#8217;t necessarily make best use of the processors: if one of those partitions has less complexity than the others, then that processor will be idle for most of the render.</p>
<p><img class="size-full wp-image-25 alignleft" style="margin-left: 10px; margin-right: 10px; float: left;" title="Naive scene partitioning" src="http://www.hackification.com/wp-content/uploads/2008/08/partition.png" alt="" width="100" height="100" />In this example, we&#8217;ve partitioned the rendering of a scene amongst four processors, but the first slice will finish way before all the others, since it contains nothing but background colour. Slice three will probably finish last. Essentially, we have a very uneven usage of our CPUs.</p>
<p>A better way to use the available processors is to divide the rendering into many more parts than we have processors, and put them in a work queue. Each processor can then pop a piece of work from the queue every time it&#8217;s ready. When the queue is empty and all processors are done, then the rendering is complete. This method makes far better use of the available CPU power.</p>
<p><img class="size-full wp-image-26 alignleft" style="margin-left: 10px; margin-right: 10px; float: left;" title="Scene partitioning, with primary ray optimization" src="http://www.hackification.com/wp-content/uploads/2008/08/primaryparts.png" alt="" width="100" height="100" />In fact, we can be even more cunning with our division of the scene. Suppose we divide the scene displayed here into a grid. Each grid line corresponds to a plane passing through the camera. (If you have trouble with that idea, consider the edges of your monitor: you can imagine triangles with points at your eye, and two points on the corner of the monitor).</p>
<p>We can work out which spheres (yes, those coloured circles are supposed to be spheres) intersect each column (left to right):</p>
<ul>
<li>Red;</li>
<li>Red, Green, and Blue;</li>
<li>Red (just), Green, and Blue;</li>
<li>Blue.</li>
</ul>
<p>Similarly, we can work out which spheres intersect each row (top to bottom):</p>
<ul>
<li>Green;</li>
<li>Green and Blue;</li>
<li>Red, Green (just) and Blue;</li>
<li>Red and Blue.</li>
</ul>
<p>(See <a href="http://www.hackification.com/2008/07/25/experiments-in-ray-tracing-part-6-intersection-tests/" target="_blank">last article</a> for a selection of intersection tests).</p>
<p>[To speed up this pre-processing stage, I used a binary chop algorithm - repeatedly partitioning the scene into two sets of objects.]</p>
<p>Once we&#8217;ve performed this pre-processing, we can make use of this information to speed up the actual processing. When rendering each part, the primary ray intersection test only needs to consider those objects which are in the intersection of the appropriate row and column sets.</p>
<p>As an example, consider the top-left part. The row contains the green sphere; the column the red sphere. We can therefore see that the area doesn&#8217;t contain any objects &#8211; so there&#8217;s no point rendering each pixel &#8211; we just fill it with background.</p>
<p>For parts that do contain one or more objects, we can speed up primary ray intersection testing by only testing against the identified objects &#8211; we don&#8217;t need to test against every object in the scene.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2008/08/17/experiments-in-ray-tracing-part-7-multi-threading/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Experiments in Ray-Tracing, Part 6: Intersection Tests</title>
		<link>http://www.hackification.com/2008/07/25/experiments-in-ray-tracing-part-6-intersection-tests/</link>
		<comments>http://www.hackification.com/2008/07/25/experiments-in-ray-tracing-part-6-intersection-tests/#comments</comments>
		<pubDate>Fri, 25 Jul 2008 18:42:09 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[Experiments]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[intersection]]></category>
		<category><![CDATA[ray-tracing]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=21</guid>
		<description><![CDATA[I wasn&#8217;t going to present quite so much code in this series, but the following intersection tests are (a) tricky to get working correctly and quickly, and (b) they&#8217;re not exactly exciting, so I thought I&#8217;d include them here as reference. I&#8217;ve also been saying things like &#8220;if the ray intersects the object&#8230;&#8221; without covering [...]]]></description>
			<content:encoded><![CDATA[<p>I wasn&#8217;t going to present quite so much code in this series, but the following intersection tests are (a) tricky to get working correctly and quickly, and (b) they&#8217;re not exactly exciting, so I thought I&#8217;d include them here as reference. I&#8217;ve also been saying things like &#8220;if the ray intersects the object&#8230;&#8221; without covering how you&#8217;d actually go about detecting that, so this article covers that.</p>
<p>(Please note that these algorithms most definitely aren&#8217;t my work: I&#8217;ve adapted most of them from &#8220;<a href="http://www.amazon.com/Real-Time-Rendering-Third-Tomas-Akenine-Möller/dp/1568814240/" target="_blank">Real-Time Rendering</a>&#8220;).</p>
<p>So here we go: a variety of intersection methods, implemented in C#.</p>
<p><strong>Intersection Constructor</strong></p>
<p>The intersection tests return either an intersection object, if the ray intersects the object, or null, if not. The constructor of the intersection class has the following form:</p>
<pre>public Intersection( Vector position, Vector normal, double t )
</pre>
<p>The plane tests given determine whether the object is completely on one side of the given plane, completely on the other side, or whether the plane passes through the object. Planes are represented as a point on the surface, and the surface normal.</p>
<p><strong>Ray-Sphere Intersection</strong></p>
<pre>public override Base.Intersection Intersect( Base.Ray ray )
{
  var el = _center - ray.Start;
  var d = Base.Vector.Dot( el, ray.Vector );
  var els = Base.Vector.Dot( el, el );
  var rs = _radius * _radius;

  if( d &lt; 0 &amp;&amp; els &gt; rs )
  {
    return null;
  }

  var ms = els - d * d;

  if( ms &gt; rs )
  {
    return null;
  }

  var q = Math.Sqrt( rs - ms );
  double t;

  if( els &gt; rs )
  {
    t = d - q;
  }
  else
  {
    t = d + q;
  }

  var p = ray.Start + ray.Vector * t;

  return new Base.Intersection( p, ( p - _center ).Normalize(), t );
}
</pre>
<p><strong>Ray-Triangle Intersection</strong></p>
<p>Note that _epsilon is somee small number, say 0.00001. _p0, _p1, and _p2 are the three vertices of the triangle.</p>
<pre>public override Base.Intersection Intersect( Base.Ray ray )
{
  var e1 = _p1 - _p0;
  var e2 = _p2 - _p0;
  var p = Base.Vector.Cross( ray.Vector, e2 );
  var a = Base.Vector.Dot( e1, p );

  if( a &gt; -_epsilon &amp;&amp; a &lt; _epsilon )
  {
    return null;
  }

  var f = 1 / a;
  var s = ray.Start - _p0;
  var u = f * Base.Vector.Dot( s, p );

  if( u &lt; 0 || u &gt; 1 )
  {
    return null;
  }

  var q = Base.Vector.Cross( s, e1 );
  var v = f * Base.Vector.Dot( ray.Vector, q );

  if( v &lt; 0 || u + v &gt; 1 )
  {
    return null;
  }

  var t = f * Base.Vector.Dot( e2, q );

  if( t &lt; 0 )
  {
    return null;
  }

  var position = ray.Start + ray.Vector * t;

  return new Base.Intersection( position, _normal, t );
}
</pre>
<p><strong>Plane-Sphere Test</strong></p>
<pre>public override Base.PlaneSide GetPlaneSide( Base.Plane plane )
{
  var p = _center - plane.Point;
  var distance = Base.Vector.Dot( p, plane.Normal );

  if( distance &gt; _radius )
  {
    return Base.PlaneSide.NormalSide;
  }
  else if( distance &lt; -_radius )
  {
    return Base.PlaneSide.OtherSide;
  }
  else
  {
    return Base.PlaneSide.Intersects;
  }
}
</pre>
<p><strong>Plane-Triangle Test</strong></p>
<pre>public override Base.PlaneSide GetPlaneSide( Base.Plane plane )
{
  var p0 = _p0 - plane.Point;
  var d0 = Base.Vector.Dot( p0, plane.Normal );
  var p1 = _p1 - plane.Point;
  var d1 = Base.Vector.Dot( p1, plane.Normal );
  var p2 = _p2 - plane.Point;
  var d2 = Base.Vector.Dot( p2, plane.Normal );

  if( d0 &gt; 0 &amp;&amp; d1 &gt; 0 &amp;&amp; d2 &gt; 0 )
  {
    return Base.PlaneSide.NormalSide;
  }
  else if( d0 &lt; 0 &amp;&amp; d1 &lt; 0 &amp;&amp; d2 &lt; 0 )
  {
    return Base.PlaneSide.OtherSide;
  }
  else
  {
    return Base.PlaneSide.Intersects;
  }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2008/07/25/experiments-in-ray-tracing-part-6-intersection-tests/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Experiments in Ray-Tracing, Part 5: Reflections</title>
		<link>http://www.hackification.com/2008/07/22/experiments-in-ray-tracing-part-5-reflections/</link>
		<comments>http://www.hackification.com/2008/07/22/experiments-in-ray-tracing-part-5-reflections/#comments</comments>
		<pubDate>Tue, 22 Jul 2008 21:34:55 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[Experiments]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[ray-tracing]]></category>
		<category><![CDATA[reflections]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=19</guid>
		<description><![CDATA[Reflections are so easy to implement in a ray-tracer, it&#8217;s not suprising that so many ray-traced images contain them. To implement reflectivee surfaces, we need to extend (or composite) our materials to support a reflectivity factor &#8211; this ranges from zero (absolutely no reflections) to one (a perfect mirror). Equally, as the reflectivity ranges from [...]]]></description>
			<content:encoded><![CDATA[<p>Reflections are so easy to implement in a ray-tracer, it&#8217;s not suprising that so many ray-traced images contain them. To implement reflectivee surfaces, we need to extend (or composite) our materials to support a reflectivity factor &#8211; this ranges from zero (absolutely no reflections) to one (a perfect mirror). Equally, as the reflectivity ranges from zero to one, the natural colour of the surface is scaled from one to zero.</p>
<p>Calculating the colour of a reflective surface is (usually) a recursive process &#8211; a secondary ray is cast from the reflective surface, and used to calculate the contribution to the primary colour. Of course, if the secondary ray hits a reflective surface, another ray will be fired, and so forth&#8230; so a limit of some kind is usually applied to this process, to end any potentially endless recursion.</p>
<p><a href="http://www.hackification.com/wp-content/uploads/2008/07/reflection.jpg"><img class="aligncenter size-full wp-image-20" title="Ray-Tracing Reflections" src="http://www.hackification.com/wp-content/uploads/2008/07/reflection.jpg" alt="" width="324" height="300" /></a></p>
<p>Let&#8217;s hope the above image makes things clearer. On the left is the camera/eye, casting a primary ray (marked &#8220;1&#8243;) which intersects a reflective sphere. (We can see that the colour of the pixel should be green).</p>
<p>Since the surface is reflective, we  recursively cast a secondary ray (marked &#8220;2&#8243;) at a vector that is the reflection of the primary ray against the surface (calculated against the intersection normal, &#8220;N&#8221;).</p>
<p>This secondary ray intersects another object (the green sphere), and here we calculate the colour as usual based on the lighting calculations.</p>
<p>Since the final object wasn&#8217;t reflective, the recursion ends, and the pixel is assigned the colour calculated via the secondary ray.</p>
<p>Here&#8217;s my code for a reflective material:</p>
<pre>public sealed class ReflectiveMaterial : Material
{
  public ReflectiveMaterial( double reflectivity, Material material )
  {
    _reflectivity = reflectivity;
    _material = material;
  }

  public override Base.Color GetColor( Scene.Scene scene, Base.Intersection intersection, int depth )
  {
    var surfaceColor = _material.GetColor( scene, intersection, depth );
    var reflectColor = scene.BackgroundColor;

    if( depth &lt; 3 )
    {
      var c1 = -Base.Vector.Dot( intersection.Normal, intersection.Ray.Vector );
      var r1 = intersection.Ray.Vector + ( intersection.Normal * 2 * c1 );
      var reflectRay = new Base.Ray( intersection.Position, r1 );

      var reflectIntersection = scene.GetIntersection( reflectRay, intersection.Primitive );

      if( reflectIntersection != null )
      {
        reflectColor = Tracing.Tracer.TraceRay( reflectIntersection, scene, depth + 1 );
      }
    }

    return surfaceColor * ( 1 - _reflectivity ) + reflectColor * _reflectivity;
  }

  private double _reflectivity;
  private Material _material;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2008/07/22/experiments-in-ray-tracing-part-5-reflections/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
