<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.0.2" -->
<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/"
	>

<channel>
	<title>ionous</title>
	<link>http://www.ionous.net</link>
	<description>all you never wanted to know about game programming.</description>
	<pubDate>Tue, 05 Aug 2008 21:51:11 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.0.2</generator>
	<language>en</language>
			<item>
		<title>bartleby</title>
		<link>http://www.ionous.net/2008/07/28/bartleby/</link>
		<comments>http://www.ionous.net/2008/07/28/bartleby/#comments</comments>
		<pubDate>Mon, 28 Jul 2008 15:30:13 +0000</pubDate>
		<dc:creator>io</dc:creator>
		
	<category>Python</category>
		<guid isPermaLink="false">http://www.ionous.net/2008/07/28/bartleby/</guid>
		<description><![CDATA[One of the things on my mind the last week or so has been: what kind of constructs in Python would allow for easy to use type safety / type checking?  Mix a little keyword parameter usage with a little bit of django-y model definitions and the net result is Bartleby.
I expect that the [...]]]></description>
			<content:encoded><![CDATA[<p>One of the things on my mind the last week or so has been: what kind of constructs in Python would allow for easy to use type safety / type checking?  Mix a little keyword parameter usage with a little bit of django-y model definitions and the net result is <a title="Bartleby: type safe python" target="_blank" href="http://code.google.com/p/bartleby/">Bartleby</a>.</p>
<p><a id="more-80"></a>I expect that the reaction of most people to type safety in python would be to first ask why, and then wonder wouldn&#8217;t it make python as slow to develop in as C or Java. Worse: doesn&#8217;t it break duck-typing.</p>
<p>Let me answer those in reverse order:</p>
<p>My personal take regarding development speed is that python is good not due to how few keystrokes it requires you to enter, but from how quickly you can try out new ideas.</p>
<p>Number one on that front is that python is an interpreted language, so no compiler. Especially compared to C where something like a header file change can force you to sit for umpteen minutes to get results, life with python is good. Beyond that: automatic garbage collection, good string support, and a gigantic set of built in libraries all make getting real work done easy.</p>
<p>For me ( at least ) typing ( keystrokes ) is the <strong>least</strong> time consuming aspect of development. Even if i have to cursor around to add members to a class, that&#8217;s nothing compared with the brain time it takes me to figure out how i&#8217;m going to put together an application.</p>
<p>All that said, even if you were to allow that maybe a few extra keystrokes here and there ( i think it averages out to about 15 extra characters or so per parameter and class member ) might not make a significant difference in development time &#8212; the question still remains: <em><strong>why</strong></em>.</p>
<p>I&#8217;m a bad programmer. I make mistakes all the time. To me, types are an integral part of making sure I&#8217;m doing the right thing. To put it another way:</p>
<p>Types are a form of implicit unit tests.</p>
<p>And unit tests are good, right?</p>
<p>Bartleby is actually the expression of the fact that whenever I try to refactor code in python, I often spend a <em>significant</em> amount of time tracking errors due to parameters or class members that have changed. If those errors were caught early in a given run, rather than late: so much the better.</p>
<p>Last thing: duck-typing. First, imagine a long philosophical argument about the wonderful clarity of adapter classes here -> (). And, then, imagine a similar discussion about how code is mostly supported not written here -> (). Roger. So that said ; ) you can always &#8216;&#8217;not'&#8217; use Bartleby where you want to allow duck typing, and you can also use Type(object,&#8230;) to allow any type.
</p>
]]></content:encoded>
			<wfw:commentRSS>http://www.ionous.net/2008/07/28/bartleby/feed/</wfw:commentRSS>
		</item>
		<item>
		<title>Source Insight</title>
		<link>http://www.ionous.net/2008/05/10/source-insight/</link>
		<comments>http://www.ionous.net/2008/05/10/source-insight/#comments</comments>
		<pubDate>Sat, 10 May 2008 15:38:50 +0000</pubDate>
		<dc:creator>io</dc:creator>
		
	<category>Ionous</category>
	<category>C++</category>
	<category>tools</category>
		<guid isPermaLink="false">http://www.ionous.net/2008/05/10/source-insight/</guid>
		<description><![CDATA[Search wikipedia for code editors and you won&#8217;t find Source Insight.
Most people out there have heard of SlickEdit, CodeWarrior, etc. but Source Insight?  It&#8217;s rare.
It deserves so much more recognition than it gets, however, because it does several key things better than everything else.  Unfortunately (for me) it hasn&#8217;t kept up over the [...]]]></description>
			<content:encoded><![CDATA[<p>Search wikipedia for code editors and you won&#8217;t find Source Insight.<br />
Most people out there have heard of SlickEdit, CodeWarrior, etc. but Source Insight?  It&#8217;s rare.</p>
<p>It deserves so much more recognition than it gets, however, because it does several key things better than everything else.  Unfortunately (for me) it hasn&#8217;t kept up over the years with language changes and even small things like Java attributes disturb its order so completely as to make the program unusable.</p>
<p>After somewhere near 12 years of use I&#8217;ve become physically grafted to it.  This is great when the editor works but horrible when when it doesn&#8217;t.  Due to some of the problems it has I&#8217;ve been looking for a new editor this last couple of weeks &#8212; but I still can&#8217;t find one that works the way I want.</p>
<p>In order to prove to myself that it&#8217;s not simply out of habit that I use Source Insight but that it still actually rocks after all these years&#8230; here&#8217;s my review.</p>
<h2>Simple, Beautiful Features</h2>
<h3>Search results are a normal text window.</h3>
<p>Whether you do a &#8220;find in this file&#8221; or a &#8220;find in all files&#8221; your results go into a newly created text file.  Yup.  Not a specialized dockable floatable window with resizable columns or buttons to click on.  Just a text window.   How emacs I know.</p>
<p>A few reasons why this works so well:</p>
<ul>
<li>You can have limitless search windows, controllable in a very standard way: just like every other file buffer.</li>
<li>You can manually winnow your searches.  I can&#8217;t emphasize enough just how useful it is to search for a call to a function, toggle back and forth between the search window and the actual code, delete matches that aren&#8217;t what you are looking for, append new searches, rinse repeat.  Learning new code? Looking for a bug? Needing to refactor?  This is a must have feature.</li>
<li>You can save your searches ( they are just text files after all ) and call them up later ( though see &#8220;annoyances&#8221; below )</li>
</ul>
<p>The closest to this is SlickEdit which does allow you to manually winnow your search but still insists on having a custom window.</p>
<p>The furthest away is Eclipse.  Can I ask: who thought putting search results into a tree view that you have to click through with your mouse was a good idea? It&#8217;s essentially unusable.</p>
<p>Why doesn&#8217;t any other professional editor copy this simple feature?</p>
<p>My opinion, is that I think the developers of most editors are focused on individual feature bells and whistles &#8212; they don&#8217;t see the benefits to the end user when different features use the same code and act in the same way.  Source Insight seems to have limited itself to four, possibly five, control / window types &#8212; everything therefore looks the same and operates the same even though you do different tasks with them.  The next feature is in this category as well.</p>
<h3>Case intelligent syllable-based winnowing.</h3>
<p>In every dialog where there&#8217;s a list of items: files, symbols, etc.  you can winnow the list in real time by typing what you are looking for.   For instance, in the file dialog: you initially see the list of all files in the project along with an edit box into which you can type.  As you type the list of files is reduced to what matches the text you have typed.  If you have two files: &#8220;Foo.txt&#8221; and &#8220;Fee.txt&#8221; &#8212; if you first type &#8220;F&#8221; you will still see both files, then if you type, &#8220;Fo&#8221; you will only see &#8220;Foo.txt&#8221;, if you instead typed &#8220;Fx&#8221; &#8212; nothing would show up.</p>
<p>Lots of programs do this these days but Source Insight was doing it ten years ago and it still manages to do it better because it didn&#8217;t stop with simple winnowing.  It also uses &#8220;syllable matching&#8221;.</p>
<p>Syllable matching is slightly a misnomer.  Basically, SI starts by separating words out of the run-together phrases that programmers use to identify variables and types.  MY_GROUP, MyGroup, myGroup, and my_group, all share the three two words.  If I were to type either &#8220;my&#8221; or &#8220;group&#8221; into the symbol lookup window ( and this works for files and every other list as well ) Source Insight would consider that a match and ensure that, for instance, &#8220;MyGroup&#8221; would show up in the list of possible symbols.</p>
<p>It goes a tiny bit further than just raw matching though.  If you specify a case for the partial words that you type by mixing cases, for instance: &#8220;camelCase&#8221; or &#8220;PascalCase&#8221;, then it assumes that you are trying to give it more specific information and will limit its search to your matching case pattern.  If you are unsure of the case but want to enter multiple syllables you can enter a space.  A quick example of what this means, typing: &#8220;render object&#8221; in the symbol lookup might yield &#8220;renderMyObject&#8221;, &#8220;MSG_RENDER_OBJECT&#8221;, and &#8220;ObjectRenderFunction&#8221;.</p>
<p>Just to explain why this particular feature is one I love: i can&#8217;t tell you the number of times i can sort of remember the class name of something but not exactly.  Or I need to open a file, but can&#8217;t remember exactly where it is in the file path.  If i can remember some piece of the item in question &#8212; i can find it almost instantly.</p>
<p>Could it go further? It&#8217;d be great if it prioritized symbols by most likely match, only prioritized case based searches not actually winnowed out differently matched cases, and it&#8217;d be awesome if it remembered my recently searched items and ranked those high.</p>
<p><strong><em>Comparisons</em></strong></p>
<p><span style="font-weight: bold">Visual Studio</span>: the command window is a beautiful hidden feature.  If you can find the menu option that let&#8217;s you access it, and if you type the command &#8220;of&#8221; at the prompt, it will let you open a file using basic winnowing. Matching is case-insensitive and it doesn&#8217;t do any form of syllable matching, but still much better than clicking endlessly through project file hierarchies.  ( I know msdev can be extended with plugins and that there are a couple of really good ones out there, some that give you a special window to open files. )<br />
<span style="font-weight: bold">Eclipse</span>: only begins to winnow after you type something &#8212; so you can&#8217;t do searches by scrolling through lists.</p>
<p><span style="font-weight: bold">Slickedit</span>: it appears to do basic syllable matching, but truly horrible and essentially a show stopper for me:  winnowing is done as a synchronous operation.  If SlickEdit needs to search it stops you from typing.  if you have a project with 100,000 symbols it is so amazingly slow and interruptive to use you might as well not.</p>
<h3>The Context Window.</h3>
<p>This is a dockable window that shows you the definition of whatever symbol your cursor is on, plus has a few lines ( the number depends on how large you make your context window  ) on either side of the definition so you can see comments, and other related code.</p>
<p>This is very similar to SlickEdit&#8217;s preview window.  Strangely neither source insight, nor slickedit allow you to copy text from this window.  More strangely: slickedit lets you try, makes it seem like you succeeded, but it doesn&#8217;t actually copy the text out that you want.</p>
<p>SI&#8217;s implementation has two nice features:</p>
<p>First, you can &#8220;lock&#8221; the window so no matter what other file you open or symbol you look at the window stays at what you were previewing.</p>
<p>Second, for variables, the window&#8217;s focus changes over time. If you are looking at a variable, it will first show you the variable&#8217;s declaration, and then, a second or so later, the declaration of its type.  I kind of wish it would keep going up through class hierarchies, etc. but still it&#8217;s very useful &#8212; you can see lots of information about any given variable without having to leave the location you are editing.  By using &#8220;lock&#8221;, if you don&#8217;t want it to go up to the type, you can stop the window after it shows the variable&#8217;s declaration.</p>
<p>The context window incredibly helpful when navigating code, and it also provides some of what people look for in auto-completion: what parameters can this function I&#8217;ve just typed take?</p>
<p>SlickEdit has a similar feature, but strangely: you can only search for symbols of text you have highlighted.  Want to look up something off the cuff and you are out of luck.  ( I&#8217;m sure you could write a macro in SlickC to help with this )</p>
<h3>Smart Reference Matching.</h3>
<p>&#8220;Symbol search&#8221; allows you to search for all uses of a symbol in a file or project &#8212; many editors have this now, but again, Source Insight has had it for quite a long time, and for several  years now has had an excellent extension: Smart Reference Matching.</p>
<p>This extension of symbol search attempts to limit the search to the specific instance of a symbol name that you have highlighted.  If you have two classes that both have a method ShouldaNamedItUniquely() then it will attempt to limit its search to particular uses of the class you are interested in.  This is amazingly invaluable for projects that really like to use short method names where you can wind up with dozens of classes that have a method called &#8220;getName()&#8221; or the like.  That said it doesn&#8217;t always work perfectly &#8212; so you have to somewhat intuitively learn when you can trust it and when you can&#8217;t.</p>
<p>SlickEdit has search by matched color.  I find it hard to activate and feel it has limited use because it just says: search for all methods called &#8220;getName&#8221; as opposed to limiting by symbol context.  I think it&#8217;s generally pretty rare for different types of symbols in a project to use exactly the same case and exactly the same word tense, and I find name duplication across types to be much more rare than within the same type.</p>
<h3>Matched Symbol Color Coding.</h3>
<p>Source Insight colors text not just based on what you mean the text to be, but whether name you&#8217;ve typed is valid in the context you&#8217;ve used it.  This means that without compiling your code you can visually see whether a symbol you&#8217;ve used is valid in the current context or not.  If, for instance, you have an instance &#8216;x&#8217; of class &#8216;X&#8217; with a method &#8216;doStuff()&#8217;, x.doMyStuff() won&#8217;t color code, but x.doStuff() will.</p>
<p>This doesn&#8217;t eliminate syntax all of your syntax errors  completely &#8212; but it gets damn close.</p>
<p>That said this feature does have its ups and downs.  80% of the time it works correctly but if you&#8217;ve got files it can&#8217;t parse ( see deal breakers ) then it will fail.</p>
<p>Many editors have something similar &#8212; but generally you either only get basic detection of intent or you have to compile the project to get the validation.</p>
<p>With only basic detection things that seem like methods to the editor, whether or not the method is a valid member of the class in question get colored as a method.  ( SlickEdit is in this category )</p>
<p>Regarding compilation, it seems like, because Java has reflection, most Java editors choose this route.  They compile behind the scenes as you type.  It&#8217;s better than SlickEdit &#8212; but, if you&#8217;ve got incomplete classes, or other syntax errors &#8212; a common occurrence when you&#8217;re initially authoring new code &#8212; you don&#8217;t get proper color coding.  Also it feels, to me, a little slow &#8212; but maybe that&#8217;s just Java GUI on Windows.   Visual Studio also seems to do something like this compilation under the hood for C/++.</p>
<p><strong>Change This Color</strong>: As an aside: SI allows you to select a colored piece of text in the editor and, in the context menu, popup the color dialog for that text colorization type. It&#8217;s a super nice way to tweak the editor.</p>
<p><strong>Color Inactive Code</strong>: Also on the matching/ color front for C/++: SI allows you to define project ( and global ) conditional compiler settings &#8212; this lets SI know that the code is inactive.  Although it doesn&#8217;t have code collapsing, it will grey out those blocks, and will ( by default ) ignore those blocks when you search.</p>
<h3>File History and Auto Recovery</h3>
<p>Every time you save a file Source Insight generates a completely new backup of your file.  This has saved me from my own stupidity so many times I can&#8217;t even say.  Even better, it appears to quietly auto-save to the new backup file up to the point when you manually save to your actual file.  ( ie. manual save is probably: force auto-save, save-file, generate new-autosave file. )  This has saved me from the rare source insight crash, os crash, and power failure more than a few times.</p>
<h3>Intelligent Cursor History</h3>
<p>Just as a back button on a browser lets you move to earlier links,  Source Insight tracks the history of your cursor, and lets you jump back to earlier locations.  Many programs provide some basic implementation of this &#8212; but the way SI&#8217;s seems to work is that it only creates an internal bookmark if you either jumped there due to a search, edited some code, or hung out at a location for a while.  This means minor movements of the cursor are collapsed in the history.  Visual Studio, for instance, has a cursor history but i find it unusable because it remembers literally every movement.</p>
<h2>Other nice stuff</h2>
<p><span style="font-weight: bold">Global Symbol Lookup. </span>This is similar to Symbol Search, mentioned with Smart Reference Matching above, but instead of finding uses of a symbol, it allows you to jump to the definition of any symbol.  This used to be a feature unique to SI but many editors offer this now.  Source Insight still bests them due to its syllable matching.</p>
<p><span style="font-weight: bold">Relation Lookup. </span>Lets you see the hierarchy of classes, lets you choose to look up or down the hierarchy.   Can display results in tree-view form or in graphical format.  It&#8217;d probably has more power than I give it credit for.  I generally find it hard to change the relation I&#8217;m looking at, so i usually don&#8217;t bother with the window at all.</p>
<p><span style="font-weight: bold">Parse Source Links.  </span>Using regular expressions you can turn any text file into a bunch of navigable links.</p>
<p><span style="font-weight: bold">Project Add/Remove Files.  </span>Source Insight does this pretty badly.  What&#8217;s amazing to me is that everyone else does this even worse.  In SlickEdit, for instance, there is *NO WAY* to add a file that you have open to your project.  ( I&#8217;m sure you could write this in SlickC, but still )</p>
<p>Add /remove files recursively by wildcard.  Nice. Simple. Easy.  No one else does this.  You either get: recursive, or you get wildcard, but you don&#8217;t get both simultaneously.</p>
<p>Add any known type.  Most programs have sets of wildcards for each type &#8212; Source Insight has that, but it also allows you to automatically add any file type it knows about.  That&#8217;s really nice if you have a combo project made of C, xml, txt, vcprojs, html, etc.  Most big projects are of this sort.</p>
<p><span style="font-weight: bold">Toolbar / Menu / Key customization.  </span>All menu and keyboards commands etc. are referred to by a two part hierarchy of names corresponding exactly to the default menu layout, and the names are in plain english.  For instance, the command to open a file is &#8220;File: Open&#8221; because it appears on the &#8220;File&#8221; menu with the name &#8220;Open&#8221;.</p>
<p>Straight forward enough?  Until I used SlickEdit I didn&#8217;t realize how important this is.  In SlickEdit if you want to add something you see on a menu to a key shortcut?  Good luck &#8212; you&#8217;ll have to guess the command name.  Same issue for popping up dialog boxes.  For instance, to get to the &#8220;open file in project&#8221; list you have to hunt down the command: &#8220;active-files&#8221; and that&#8217;s one of the less obscure commands.<br />
As example of the simple reuse of code: you can dump all of the key bindings, menu bindings, etc. to a text file so you can see / sort for commands.  Other editors invent custom navigation and search dialogs &#8212; which is nice i suppose &#8212; but spend time on actual functionality not complexity please.</p>
<p><span style="font-weight: bold">Keyboard oriented but mouse friendly. </span>You can do every operation quickly and easily with the keyboard but you can also use your mouse if you want.  Most programs that are heavily keyboard accelerated generally need at least some mouse based interaction to get stuff done.  Those that don&#8217;t ( ex. emacs ) aren&#8217;t friendly at all if you want to use the mouse.  Usually keyboard is the way to go, but sometimes it is just faster to click on what you can see.</p>
<p><span style="font-weight: bold">Instant on. </span>Ever opened netbeans or eclipse?   It takes on the order of a minute.  Good luck getting a new idea down quickly.  Source Insight opens faster than you can blink even on my highly underpowered laptop ( okay ~10 seconds ).  The editor doesn&#8217;t feel big and bloated.  It feels light and transparent.  Unfortunately, most of the Java editors I&#8217;ve tried move like thick soup.</p>
<h2>The Deal Breakers</h2>
<p>User created languages are second class citizens so if Source Insight doesn&#8217;t fully support a given language: good luck.  Two of the worst for me are Java and ActionScript.</p>
<h3>Java parsing can&#8217;t handle @tags.</h3>
<p>If you have an @tag, rather then skip the line because it doesn&#8217;t understand it &#8212; source insight&#8217;s parser eats the whole file &#8212; nothing in the file registers as a symbol after the tag. Yikes.  Even better, because it&#8217;s a predefined language, you can&#8217;t create your regex interpretation of the tag to make the parser ignore it.</p>
<h3>No action script support.</h3>
<p>You can sort of get a good look but you can&#8217;t make it recognize the weird javascript based variable syntax well enough to truly allow good symbol lookup.</p>
<h3>Auto-Completion is terrible</h3>
<p>Every time you type the popup symbol / auto completion box disappears and restarts parsing. It&#8217;s also a little slow ( which is strange given how fast everything else is ).  This isn&#8217;t a deal breaker for me because I don&#8217;t use auto-completion but I list it in this category because I know several people who can&#8217;t live without it.</p>
<h2>Miscellaneous Annoying Stuff</h2>
<p><span style="font-weight: bold"> Some searches can&#8217;t be saved.  </span>If there&#8217;s both file and line info in displayed in the search then you can save the search and reload it later; if not you can&#8217;t.</p>
<p><span style="font-weight: bold">Symbol searches don&#8217;t show line numbers.  </span>I think this is a recently introduced bug &#8212; and it&#8217;s annoying.  It means you can&#8217;t save symbol searches.  Of course since you can&#8217;t do this in most programs anyway I guess I shouldn&#8217;t complain.</p>
<p><span style="font-weight: bold">Bad colors / text sizes out of the box.  </span>No predefined palettes to swap between and the default is *crazy*. I&#8217;ve had several friends try Source Insight only to get turned off by how cartoony it initially looks.</p>
<p><span style="font-weight: bold">&#8220;Goto implementation&#8221; for constructors never works.   </span>It works for destructors and all other methods of a class &#8212; go figure.</p>
<p><span style="font-weight: bold">Custom regular expressions.  </span>SI&#8217;s syntax is pretty good but it&#8217;s its own custom flavor.  For instance: it doesn&#8217;t let you do multiline regex &#8212; this can occasionally be a pain when trying to do multi-line search and replace operations.</p>
<p><span style="font-weight: bold">Cut and copy from SI .txt files to Microsoft products strip line feeds. </span>I&#8217;ve got no idea why, but most ms programs think blocks of text pasted from Source Insight .txt files dont have proper line feeds.  If I resave the .txt file as a .cpp it always works.</p>
<p><span style="font-weight: bold">No extended features. </span>Source Insight is just an editor and nothing else.  Sure there&#8217;s a very small macro language, and sure you can launch command line programs and parse their results.  But there are no source control plugins, no package managers, no debuggers, no compilers, no maven like task managers, etc.  This is all good, and all bad.  It really would be nice if it supported plugins ( and if some existed <img src='http://www.ionous.net/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .  If it did, it&#8217;d be nice &#8212; unlike Eclipse and NetBeans &#8212; to initialize them after load, so that the startup / access sequence stays fast.</p>
<p><span style="font-weight: bold">No built in refactoring. </span>Eclipse and Netbeans offer some pretty impressive auto-refactoring abilities that would be great to see in more products including Source Insight.</p>
<p><span style="font-weight: bold">Windows only. </span>Sigh. I&#8217;ve already been doing some development on Ubuntu, I&#8217;d like to work on a Mac.  What will I do?</p>
<h2>Conclusions</h2>
<p>Can&#8217;t live without it, and, unfortunately, sometimes can&#8217;t live with it.  I think for C and C++ I&#8217;m stuck.  It&#8217;s a great product with features I don&#8217;t want to give up and that no one else has.   But, unless a new round of fixes and language expansions rolls in, for everything else:  I&#8217;ve got to move on.</p>
<p>I wish so much more for this great editor and wish others would see it and adopt it&#8217;s features.  However, I&#8217;m pretty sure there&#8217;s just one person who maintains source insight these days &#8212; and the company doesn&#8217;t charge much: I paid maybe a hundred or so US dollars a few years ago for version 3 and get free updates once a year or so.  It&#8217;s still the same version today but the price is now a little over 200 dollars &#8212; at any rate I suspect these days it&#8217;s just someone&#8217;s side job or hobby, and it could possibly be facing death in obscurity.</p>
<p>Maybe someday, if it&#8217;s indeed on that path, the author(s) could open source the code and it could live a new fresh life again.  Hopefully inspiring others with its goodness along the way.
</p>
]]></content:encoded>
			<wfw:commentRSS>http://www.ionous.net/2008/05/10/source-insight/feed/</wfw:commentRSS>
		</item>
		<item>
		<title>Making Lemonade</title>
		<link>http://www.ionous.net/2008/04/05/making-lemonade/</link>
		<comments>http://www.ionous.net/2008/04/05/making-lemonade/#comments</comments>
		<pubDate>Sat, 05 Apr 2008 18:01:09 +0000</pubDate>
		<dc:creator>io</dc:creator>
		
	<category>Game Dev</category>
		<guid isPermaLink="false">http://www.ionous.net/2008/04/05/making-lemonade/</guid>
		<description><![CDATA[Let me posit a new law of the land: actor classes should never contain movement logic.  Over the years I&#8217;ve followed this as a rule of thumb, but much to my regret, in my python dungeon crawler &#8212; since I didn’t quite know where the code was heading nor exactly the implications of using [...]]]></description>
			<content:encoded><![CDATA[<p>Let me posit a new law of the land: actor classes should never contain movement logic.  Over the years I&#8217;ve followed this as a rule of thumb, but much to my regret, in my python dungeon crawler &#8212; since I didn’t quite know where the code was heading nor exactly the implications of using python &#8212; I quietly bowed to the tyranny of the actor that does everything.</p>
<p>Don&#8217;t go there.  It&#8217;s the dark side.</p>
<p>Turn towards something different.  Call it MVC, call it narrow encapsulation, call it one of the most important design choices you can make in your game&#8217;s architecture: get movement out of your actor class, remove behavior of all kinds.</p>
<p>Your object-orientated instincts &#8212; especially if, for some reason that I have yet to put my finger on, your background is in C++ &#8212; might tell you: if an object can take an action, then that action should be a method on the object in question.</p>
<p>Take whatever book you read that in and burn it.</p>
<p>Lemons are objects; making lemonade is not an object.</p>
<p>Before I get into this too deeply, I should explain: by object here I don&#8217;t mean class.  Conceptually, by object here I mean: it has a real world physical analog.  It&#8217;s an object in the sense that your non-programming friends would understand.</p>
<p>Behavior may be a class, but is not an object.</p>
<p>Take the questionable lemon.  You can&#8217;t get away from this new law of the land by simply moving your &#8220;squeeze&#8221; function to the lemonade stand.  Try it and the police are already at your door.</p>
<p>The lemonade stand is an object. The person making the lemonade? An object.  The lemonade itself? You guessed it: an object.</p>
<p>Making lemonade? Not an object.</p>
<p>So what should an object contain then anyway if not the methods that give it character and life?  Honestly: I&#8217;d suggest radicalism.  Overcorrect, rather than under correct.  Save yourself lengthy legal arguments.  Head back towards C and Plain-Old-Data structures.</p>
<p>To be on the safe side: the essential properties and attributes of the conceptual object should go in your object class &#8212; and nothing else.  I&#8217;m not arguing for truly pure POD structures &#8212; so I&#8217;m not saying only your essential member variables &#8212; but rather those variables and the bare minimum number of methods necessary to expose those to the rest of your game.</p>
<p>As an example from a basketball game. Your actor might have the variables &#8220;height off the floor&#8221; and &#8220;current speed&#8221; and it might use those to expose the properties: &#8220;isRunning()&#8221; and &#8220;isJumping()&#8221;. But, just because you can put the &#8220;jump()&#8221; method in your Actor class doesn&#8217;t mean you should.</p>
<p>In order for your code to live a long and healthy life &#8212; you really want to wind up in a situation where a single code base could possibly be reused multiple times.   If your actor, for instance, gets a &#8220;shootHoop()&#8221; method &#8212; you are not going to want to reuse that actor class for a hockey game.  Now, if perhaps you aren’t interested in that level of reusability, consider the following much more likely case.</p>
<p>You are two years into the development of a new first person shooter and suddenly your designer says to you: I really need the player to drive a car in this part of the game.  If the only tool available to you is to add &#8220;steer()&#8221;, &#8220;accelerate()&#8221;, and &#8220;brake()&#8221; to your human actor object class &#8212; I can guarantee  you are going to have some long sleepless nights ahead of you.  In this case, your actor class is probably already several thousand lines long, and to add even simplistic driving, its going to become several thousands more.  Even if you can shunt most of the code of into a car class, your main human actor will be inextricably bound up to that car, and the number of dependencies between states within these two classes will start to give you nightmares once you can grab some shuteye.</p>
<p>As a programmer you might feel inclined to blame design for not letting you know 2 years ago you might have car driving as a one off in your game &#8212; but the reality is: that&#8217;s just game development.  Your code has to be able to cope with radically shifting needs.  Separating behavior and the objects behaviors operate upon will help get you to that point.</p>
<p>&#8220;Object-oriented&#8221; does mean the language orients &#8212; focuses &#8212; you on using objects&#8230; just don&#8217;t let it imprison you there.
</p>
]]></content:encoded>
			<wfw:commentRSS>http://www.ionous.net/2008/04/05/making-lemonade/feed/</wfw:commentRSS>
		</item>
		<item>
		<title>Mu - the path of the unstuck</title>
		<link>http://www.ionous.net/2008/04/01/mu-the-path-of-the-unstuck/</link>
		<comments>http://www.ionous.net/2008/04/01/mu-the-path-of-the-unstuck/#comments</comments>
		<pubDate>Tue, 01 Apr 2008 15:44:49 +0000</pubDate>
		<dc:creator>io</dc:creator>
		
	<category>Game Dev</category>
		<guid isPermaLink="false">http://www.ionous.net/2008/04/01/mu-the-path-of-the-unstuck/</guid>
		<description><![CDATA[A couple of truism:  Simple choices can have a wide, cascading effect.  The design of your game&#8217;s root classes can effect every other piece of code in game.
I&#8217;m porting my python dungeon crawler over to java, and am trying to get it up and running one small piece at a time.  For [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of truism:  Simple choices can have a wide, cascading effect.  The design of your game&#8217;s root classes can effect every other piece of code in game.</p>
<p>I&#8217;m porting my python dungeon crawler over to java, and am trying to get it up and running one small piece at a time.  For the first time I&#8217;m trying out true unit tests; trying to get each piece debugged before setting the whole thing going as one.</p>
<p>I&#8217;m currently faced with a deceptively simple choice: should a &#8220;Room&#8221; class contain a list of pointers to &#8220;Actor&#8221; objects?</p>
<p>If you feel the answer is: yes, of course Rooms should contain Actors, you probably consider yourself a McCoy programmer: a programmer who favors simple, easy to understand code, that executes quickly.  If you say: good god no, you probably consider yourself a good engineer, a person who creates robust code for the long haul, a purely Hatfield programmer.</p>
<p>Behind their back McCoy programmers get called hackers, spaghetti programmers, baby killers; Hatfield programmers get called language lawyers, code obfuscators, Bush administration supporters.Even today the Hatfields and the McCoys don&#8217;t get along.</p>
<p>If you are unlucky: you will have both ardent Hatfields and ardent McCoys on your team, both sides hell bound to have their way.  Debates over simple choices will rage for weeks, no code will actually get written, your game will get cancelled, and you&#8217;ll be forced to live out your days penniless.</p>
<p>If you&#8217;re <span style="font-style: italic">really </span>unlucky you&#8217;ll have someone who professes to be a Hatfield but codes like a McCoy.  This person will know just what to do, will spend two weeks coding something &#8220;abstract&#8221; and &#8220;decoupled&#8221; that’s 6000 lines long, distributed across eight object classes, and uses string compares to look up actors.  Your game will ship and become wildly successful.  They will get a promotion, while you will have to spend the rest of your career maintaining something so fragile that it breaks every time a stray neutrino passes near.</p>
<p>Fundamentally, there is no right answer to the question I&#8217;ve posed.  Software is pliable, and it allows you to make whatever choices you want.  When &#8220;mu&#8221; choices come up I generally just take my best most educated guess and move on, correcting bad choices later on.</p>
<p>I justify this with a personal tenet that programmers need to get code into customers&#8217; hands as quickly as reasonably possible.  ( The quality level of &#8220;reasonable&#8221; and the speed of &#8220;quick&#8221; being up to endless debate on a case by case basis ).</p>
<p>My python code therefore is currently McCoy like &#8212; it has bi-directional pointers, Rooms hold Actors, Actors track their parent room.  Unfortunately, both my Actor and my Room classes have become top heavy: if I port one, I have to port the other.</p>
<p>I am at a cross-roads then, I can:</p>
<ul>
<li>port both together</li>
<li>create abstract base classes for each to lighten the load, then port each in turn.</li>
<li>separate the two from each other entirely.</li>
</ul>
<p>The land of databases sheds some light: If I were to construct these as tables, I never would have been able to have had one complex class contain lists of another complex class &#8212; I&#8217;d have to an Actor table, a Room table, and a third, ActorsInRooms, table.</p>
<p>Taking that metaphor forward: it&#8217;s easily possible to create the ActorsInRooms table up front as small and as flat as the list of the Rooms itself can be.  For a static per level set of rooms: a simple level load time allocated array &#8212; indexed by room id &#8212; will be just as quick (I&#8217;m throwing cache to the wind here) and just as small as a direct in Room list of actors.</p>
<p>Later, if the Rooms need to get Items, Lights, Fixtures, etc.  We have a nice simple model that allows for fast. compact, lookup when needed without bogging down the Room object model.</p>
<p>The downside may be that, if Rooms become dynamic, that list may have to become a hash at some point &#8212; but, down that route, the Rooms themselves will need to go in a hash, and so perhaps, it will be possible to create a shared central lookup.</p>
<p>At any rate: here&#8217;s a rule of thumb I advocate that isn&#8217;t repeated enough in code design books, classes, discussions, etc.  Keep your classes SMALL.  Try to keep per class responsibilities down.  If classes start to get big, side step that increase by introducing <span style="font-style: italic">simple</span> relationship objects that can help express connections between objects.</p>
<p>Most importantly, however, revise and streamline your class design as you go.  Don&#8217;t worry about abstract choices too much.  Instead, focus on getting reasonable code in your customers&#8217; hands quickly.  Later, as you learn about the issues your code needs to handle, take the time to make your code better.
</p>
]]></content:encoded>
			<wfw:commentRSS>http://www.ionous.net/2008/04/01/mu-the-path-of-the-unstuck/feed/</wfw:commentRSS>
		</item>
		<item>
		<title>Time-Sliced Embedded Python</title>
		<link>http://www.ionous.net/2007/08/21/time-sliced-embedded-python/</link>
		<comments>http://www.ionous.net/2007/08/21/time-sliced-embedded-python/#comments</comments>
		<pubDate>Tue, 21 Aug 2007 23:32:27 +0000</pubDate>
		<dc:creator>io</dc:creator>
		
	<category>Game Dev</category>
	<category>Python</category>
		<guid isPermaLink="false">http://www.ionous.net/2007/08/21/time-sliced-embedded-python/</guid>
		<description><![CDATA[This post assumes you are trying to have your game run python rather than the other way around, and you are looking for something quick and dirty that will get the integration up and running quickly.  The two basic options for embedding python go something like this:

Blocking execution:  run in one thread, intersperse [...]]]></description>
			<content:encoded><![CDATA[<p>This post assumes you are trying to have your game run python rather than the other way around, and you are looking for something quick and dirty that will get the integration up and running quickly.  The two basic options for embedding python go something like this:<br />
<span style="font-weight: bold"><br />
<span style="font-weight: bold">Blocking execution: </span></span> run in one thread, intersperse your code with calls to the high level <span class="misspell">PyRun</span>*() functions</p>
<ol>
<li>&#8230; do some stuff  &#8230; run python &#8230; do some more stuff &#8230; run more python &#8230;</li>
</ol>
<p><span style="font-weight: bold">Simultaneous execution: </span>run with multiple threads, launching ( and perhaps reusing ) a second thread whenever you want to run one of the high level <span class="misspell">PyRun</span>*() functions</p>
<ol>
<li>&#8230; do some stuff &#8230; do some more stuff &#8230;</li>
<li>&#8230; run python &#8230;.  run more python &#8230;</li>
</ol>
<p>The first method means that your python script will block your game&#8217;s processing loop; the second method means you have to synchronize access to any data shared between your game and python.</p>
<p>If you are only running truly short scripts, the first one might work &#8212; though you will definitely want some way to abort scripts that enter an infinite loop.  ( the code in this post could be adapted to do just that  )</p>
<p>For the long haul, the second one will work must better, but it will definitely take more thought and more work up front.  For quick and dirty integration, especially if you are in a situation where you are embedding scripting in order to support debugging and prototyping and don&#8217;t intend to ship with Python as part of your game that extra work may be a burden.</p>
<p>Ideally, there would be an alternative embedding where you could run python for a small slice of time during each single frame.</p>
<p>Essentially, your game loop might then look something like this:</p>
<ul>
<li>main_game_loop()</li>
<ul>
<li>process_input()</li>
<li>run_game_updates()</li>
<li>run_python_for_a_limited_time()</li>
<li>render()</li>
</ul>
</ul>
<p>While this does have some of the same downsides as the pure simultaneous model &#8212; namely that a single C/++ based object might appear to have several different states over the course of a single loop of python processing &#8212; it wouldn&#8217;t require that the actual reading to and writing from C/++ objects be thread safe.  The fact that python and the rest of your game run at completely times ensures that object access isn&#8217;t occurring simultaneously.</p>
<p>There appear to be two basic ways to accomplish this time-sliced processing mode.</p>
<ol>
<li>Use the standard high level <span class="misspell">PyRun</span>() commands, interrupting processing at a &#8220;safe time&#8221; once the desired slice of time has elapsed.</li>
<li>Eschew the higher level <span class="misspell">PyRun</span>() commands, executing commands from the script one at a time until the slice has expired.</li>
</ol>
<p>So far I&#8217;ve only explored the first method, and while it runs, it doesn&#8217;t feel particularly clean.  The rest of this post will be devoted to documenting &#8212; for good or for ill &#8212; how it works.  At some future point I will probably try to figure out how to accomplish the second method, perhaps by looking more closely at how python debuggers work.</p>
<h2>The GIL</h2>
<p>First thing first is to understand a little bit about the way the python interpreter works &#8212; I&#8217;m not an expert by any stretch of imagination &#8212; so feel free to question / correct me if you think I&#8217;ve got things wrong.</p>
<p>Basically, regardless of how many threads of Python processing you have going there is, conceptually, one central python execution engine.  This central engine is protected by a single global synchronized object &#8212; only one thread can own the object at a time, only the thread that owns the object will run its python instructions through the engine.</p>
<p>The object in the docs is referred to as the GIL &#8212; the global interpreter lock &#8212; and in Python2.5 it&#8217;s represented by the static variable &#8220;interpreter_lock&#8221; in <span class="misspell">ceval</span>.c.  The Python/C API allows a thread to request a lock on the GIL &#8212; the request blocks that thread until the lock succeeds &#8212; and unlock the GIL, which allows other threads who have requested the GIL to get the lock so that they can run.</p>
<p>The GIL works differently than a typical critical section or <span class="misspell">mutex</span>.  Basically, every one hundred instructions or so, at the same time that the currently running thread normally checks for interrupts ( <span class="misspell">ctrl</span>-c ) and external i/o signals, the running thread releases the GIL, and then immediately tries to reacquire it.  If there are any other threads who have been waiting on the GIL, they will get the lock, and the previously current thread will be suspended.  ( Python also releases and reacquires the GIL at other times: mainly (only?) during reading new python from files, including from the <span class="misspell">stdin</span>. )</p>
<p>Reading through the docs trying to understand exactly how the GIL and the functions that manipulate it work can be a bit confusing.  The API for manipulating the GIL is named in a way that focuses on <span style="font-style: italic">extending </span>python &#8212; your app being called back by python &#8212; rather than embedding &#8212; you calling into python.</p>
<p>From the extending point of view the overall process for two threads runs something like this:</p>
<ul>
<li>Run a Python file</li>
</ul>
<ul>
<ul>
<li>thread A requests a lock on the GIL</li>
<li>thread A does stuff, perhaps executing a function in a C extension</li>
<ul>
<li>the extension does stuff, returns</li>
</ul>
<li>100 instructions later thread A unlocks GIL and immediately request a lock again</li>
<li>thread B, who was waiting, gets the GIL first</li>
<li>thread B does stuff, perhaps executing a function in a C extension</li>
<li>100 instructions later thread B releases the GIL and immediately requests another lock</li>
<li>thread A, who was waiting, gets the GIL first</li>
<li>&#8230;</li>
<li>the threads reach the end of their python instructions and exit.</li>
</ul>
</ul>
<p>The API for manipulating the GIL therefore is centered around the concept that the extension may take some significant amount of time, and, if there are multiple threads of python code, that blocking for too long would be bad.  The pseudo code in the docs therefore looks something like this:</p>
<ul>
<li>Python:</li>
<ul>
<li>thread A requests the GIL</li>
<li>thread A executes a C extension function</li>
<li>C extension:</li>
<ul>
<li>saves the &#8220;thread state&#8221; of thread A</li>
<li>unlocks the GIL - thread B can begin processing python code</li>
<ul>
<li>extension does blocking stuff</li>
</ul>
<li>lock the GIL again - will block until it can acquire the GIL from thread B</li>
</ul>
<ul>
<li>restores the thread state of thread A</li>
<li>the extension returns to python</li>
</ul>
<li>100 instructions later thread A releases the GIL again</li>
<li>&#8230;</li>
</ul>
</ul>
<h2>Thread State Oddities</h2>
<p>The &#8220;thread state&#8221; referred to above, is an internal python record keeping object &#8212; it stores information on the actual OS thread ( on my system the Window&#8217;s thread handle ) but more importantly, stores pointers to all of the information that Python needs to process code.</p>
<p>Python&#8217;s execution engine can&#8217;t run without a valid thread state object.</p>
<p>In two strange quirks of the API, Python will only allow you to set the thread state of the engine to a thread state that originated on the current thread, and the API will only allow you to have one thread state per thread.  This means that there must exist a one to one mapping between the real operating system thread and the python thread state, and only the OS thread that owns the python thread state can manipulate its python thread state.</p>
<p>While this seems on the surface logical, it&#8217;s actually quite odd.  Python knows those things well enough to be able to check them &#8212; and if you don&#8217;t play by the rules Python complains loudly &#8212; so why then does it even allow you to, really require you to, manipulate them?   Python&#8217;s engine itself could just select the right thread state any time someone successfully acquires a lock.  Lockers that don&#8217;t yet have a thread state would have it swapped in when they first create a thread state, deletion of a thread state would only ever delete the current one.</p>
<p>At any rate, this has implications for the <span class="misspell">timeslicing</span>, because it limits what API functions you can legally call from where.</p>
<h2>Time slicing</h2>
<p>Here&#8217;s what I&#8217;ve found works, the following code is split up two threads &#8212; the main thread (MT) and the time-sliced thread (<span class="misspell">TT</span>).</p>
<p>The main thread handles three functions: start(), process(), stop(), while the time-sliced thread has only a single run() function.</p>
<p>In this example start() takes a <span class="misspell">filename</span> that the time-sliced thread will have python process, in little per frame chunks, until finished.</p>
<p>Wherever a request to lock the GIL occurs I&#8217;ve put a <strong><</strong><br />
Wherever the GIL gets unlocked a corresponding <strong>></strong><br />
Wherever a thread state is swapped in a <strong>[</strong><br />
Wherever it&#8217;s swapped out a <strong>]</strong></p>
<p>Again, the thread state needs to be forcibly swapped in before you run any python code from the current thread.</p>
<blockquote><p>MT: start()</p>
<ul>
<li>initialize python embedding</li>
<li>initialize python thread package</li>
<li>create <span class="misspell">TT</span>; force it to start life suspended.</li>
</ul>
<p>MT: process()</p>
<ul>
<li>resume <span class="misspell">TT</span></li>
<li>wait for the desired time slice</li>
<li>< suspend <span class="misspell">TT</span>></li>
</ul>
<p>MT: stop()</p>
<ul>
<li><[ send an exit interrupt to TT, then resume TT ]></li>
<li>wait for <span class="misspell">TT</span> to exit</li>
<li>close <span class="misspell">TT</span> thread handle</li>
</ul>
<p><span class="misspell">TT</span>: run()</p>
<ul>
<li>< create a thread state></li>
<li>load the requested file</li>
<li><[ use Python to print out the results of the file load ]></li>
<li><[ <span class="misspell">PyRun</span>() the file ]></li>
<li>close the file</li>
<li>< delete the thread state></li>
</ul>
</blockquote>
<p>In process() the main point is that the gets GIL locked before the thread is suspended.  This ensures that the thread is at safe spot in its execution of python code &#8212; a place where it expects that it might be swapped out.To handle the wait I&#8217;m using Window&#8217;s <span class="misspell">WaitForSingleObject</span>().<br />
While it&#8217;s not the most accurate timer, it does the main thread to sit idle for a short amount of time.</p>
<p>Ideally, Python&#8217;s lock object would be available for Wait() on, but it&#8217;s not exposed for direct use by embedding apps.  You can only access it through the low level <span class="misspell">PyEval</span>_Acquire/<span class="misspell">ReleaseLock</span>() and the higher level functions that wrap those calls.</p>
<p>The only real alternative therefore is to <span class="misspell">WaitForSingleObject</span> on your processing thread, and then, after the wait has finished, request a lock on the GIL, which block your thread until python is at a &#8220;good enough&#8221; stopping point ( for instance: not in a callback into your own app ) where you can then suspend the thread entirely until the next frame.</p>
<p>I suppose, actually, another, perhaps even better alternative, would be to remove the wait() altogether, and just sit in a tight loop, requesting the gil, checking the elapsed time, estimating when is a good time to exit the tight loop.  You could even track the time it took to execute the last 100 statements, and thus guess at when the next round of processing will drive the time sliced thread over its time limit.</p>
<blockquote><p>MT: process()</p>
<ul>
<li>resume <span class="misspell">TT</span></li>
<li>while (TT is still valid)</li>
<ul>
<li>lock the gil (<)</li>
<li>check time</li>
<li>if estimated time is more than the desired time:</li>
<ul>
<li>suspend TT, unlock the gil (>)</li>
</ul>
<li>if its safe to run some more:</li>
<ul>
<li>unlock the gil (>) and continue the loop</li>
</ul>
</ul>
</ul>
</blockquote>
<h2>Sample Code</h2>
<p>At any rate:</p>
<p>Here&#8217;s the real deal: <a title="sample code to run python in small time sliced chunks" href="http://www.ionous.net/wordpress/wp-content/uploads/2007/08/TimeSlicedPython.zip">TimeSlicedPython.zip</a><br />
Hope it&#8217;s useful to you and that it gives you some new insights into how Python works under the hood.
</p>
]]></content:encoded>
			<wfw:commentRSS>http://www.ionous.net/2007/08/21/time-sliced-embedded-python/feed/</wfw:commentRSS>
		</item>
	</channel>
</rss>
