Category Archives: misc

  1. avoid redundant state information

uh, more to come

You can:


using System.Runtime.InteropServices;

...

public static void test( [In][Out] ref int something )
{
    something = 5 ;
}

Be sure to add the using statement as shown!

Note if you try and do:

public static void test( out ref int something )
{
    something = 5 ;
}

You get:

Error 1 A parameter cannot have all the specified modifiers; there are too many modifers on the parameter

OK, this one is a bit more complex, so start here, then go there.

WHY C# events

An EVENT in C# is simply a means to create a CHAIN of functions that will execute when something “happens” to an object.

OBJECT with published event
subscriber 1 subscriber 2 subscriber 3 subscriber 4 subscriber 5

EVENTS in C# follow the observer design pattern. The object that CONTAINS the “event” is the “PUBLISHER”, while all the objects that “attach a function” to the event are “subscribers” to that event.

Understanding C# custom events

As a prerequisite to understanding this, you must have already worked with normal events in C#, and built a couple of simple windowed applications using .NET. If not, go read up on them, also try this.

In fact, let me summarize the prereqs to understanding this article here:

  • Worked with events in C# normally before (windows forms applications)
  • Understands delegates

If you don’t have those prereqs, RUN AWAY!! This will not make any sense to you, especially if you don’t understand delegates at all.

Custom events are great!

The point of defining custom events in C# is to provide an EASY MECHANISM to have a chain of functions that will execute in rapid succession on your command.

The idea is this. You have an object, say a BUTTON. WHEN THAT BUTTON IS CLICKED by the user, you want some function to run. But wait, not just ONE function. You want SEVERAL functions to run. In rapid succession, one after the other. AND YOU WANT THEM TO RUN WHEN THE BUTTON IS CLICKED!

So here’s what you do. You define an EVENT

using System;

public class Button
{
  // Define the EVENT here.
  public event Action Pushed ;

  // NOTICE how we specify the ACTION delegate
  // in this declaration.

  // The ACTION delegate use means that
  // the "Pushed" event accepts a chain of
  // functions to be attached to it that all have
  // NO arguments, and return type VOID.

  // You can use ANY DELEGATE TYPE YOU WANT for
  // an event in C#.  You can define your own
  // delegate type if you want, but you will really
  // have to study and understand delegates if you
  // want to do that (not covered here!)

  // This is the function that triggers the event.
  public void PushButton()
  {
    // Print out a message before actually firing the
    // Pushed event.
    Console.WriteLine("Oh, you pushed me.");

    // !! VERY IMPORTANT LINE!!
    Pushed();  // "FIRE" EVENT:  CAUSES ALL FUNCTIONS THAT WERE ATTACHED
    // TO THE "Pushed" EVENT PREVIOUSLY TO EXECUTE IN
    // RAPID SUCCESSION, ONE AFTER THE OTHER!

    // The funny thing about Events is the WEIRD, WEIRD, WEIRD
    // syntax is uses.  At one moment, you're +='ing to it,
    // the next moment, you're calling it as if it were a function.

    // Strictly speaking, the Pushed event ISN'T a function.
    // Its a series of functions.. internally it must be some
    // kind of object with some kind of linked list inside.  But
    // in any case, this notation takes some getting used to,
    // but once you're used to it, it makes a whole lotta sense.

    // ALSO, take note that YOU MUST "FIRE" THIS EVENT FROM
    // WITHIN THE Button CLASS!

    // YOU __CANNOT__ "FIRE" AN EVENT OUTSIDE THE CLASS IN WHICH
    // THAT EVENT IS DECLARED.  I explain this in more detail
    // below.

    // Finally, print out another message after firing all
    // event functions.
    Console.WriteLine("Great, now my paint is all dented");
  }
}

public class Program
{
  // one function that will be attached
  // to the Button's Pushed event.  Notice
  // it can be attached because it has
  // no arguments and return type void.
  public static void ButtonPusher()
  {
    Console.WriteLine("HI THERE!!");
  }

  // another function that will be attached
  // to the button's Pushed event
  public static void func2()
  {
    Console.WriteLine("HELLO!!");
  }

  // notice because of our use of the ACTION delegate
  // type in the Pushed event declaratino, we CANNOT
  // attach THIS functino to the Pushed event.  THe
  // signature of functions you attach to the Pushed event
  // MUST MATCH the signature of the delegate type you used
  // in the declaration of the event.  In this case the Pushed
  // event uses the Action delegate type, which is defined
  // in the .NET framework to be a delegate of return type void,
  // and accepts no arguments.
  public static void sayHi( int howMany )
  {
    Console.WriteLine( howMany + " hi's to yoU!" ) ;
  }

  static void Main( string[] args )
  {
    Button b = new Button();

    // Attach 3 functions to execute
    // when the Pushed event fires
    // from within the button
    b.Pushed += new Action( ButtonPusher );

    b.Pushed += new Action( func2 );

    b.Pushed += new Action( ButtonPusher );

    // Illegal:  sayHi does not match the Action delegate type,
    // and the Pushed event requires that the functions chained on
    // match the Action delegate type.
    ////////b.Pushed += new Action( sayHi ) ;

    // now push the button, (which in turn,
    // FIRES THE EVENT)
    b.PushButton();

    // Finally, notice this is illegal
    /////b.Pushed() ;
    // The error is:
    // Error 1 The event 'Button.Pushed' can only appear on the
    // left hand side of += or -= (except when used from
    // within the type 'Button')

    // Reason:  basically the EVENT member itself
    // is kind of private to the class.  You're not
    // allowed to "invoke it" from outside the Button class.

    // But you can, as we did here, define a function
    // within the Button class that in turn, invokes/fires
    // the event.

  }

}

I think events are rooted in the observer pattern, but you don’t have to know the observer pattern to apply what we’re working on here.

Ah, so, declaring a custom event in C# is fun. To summarize, here’s what you need:

1. A public delegate, which effectively specifies the type of function (argument list, return type) that can be chained onto the event. In this example, we just used the .NET defined Action delegate, which has return type void and no arguments passed to it.
2. Declaration of the event itself, inside the class that the event can “happen to”
3. Lastly, you TRIGGER the event from within the class in which the event is declared. You MAY NOT trigger the event from outside the class in which it is declared (you may NOT type eventName() OUTSIDE THE CLASS, EVER.)

Well, C# DOES have a typedef.

using Num = System.Int32 ;  // PRETTY MUCH typedef equivalent

static class Program
{
  static void Main()
  {
    Num x = 5 ;  // Num is completely equivalent to System.Int32;
    int y = 78 ;

  }
}

I KNOW I KNOW. But its MORE COMMON than you think.

I just was misguided on answers to TWO QUESTIONS in a row.. which I believed. One was the C# keyword IS equivalent in C++ doesn’t exist (which it does) and the other was there is no equivalent of keyword base in c++ (which there is).

There are all these noob posters on forums that .. post a wrong answer and .. there’s nobody to hold them accountable..

That said, who’s to say I’m not a noob poster.. I try my best to research problems I run into (guess how.. via the web).

The web isn’t all bad, just be careful, and don’t ever take the first response you get as CORRECT.

Equivalent of C# keyword is in C++

typeid()

Equivalent of C# keyword base in C++

BaseClassName::FunctionName()

Public vs private inheritance in C++

see

yet another post about spam comments.. but they’ve been getting really offensive lately. i mean, they mix the words sex and poop and whatever else that’s sufficiently disgusting they can think of, and just cram it up on your blog.

its really rude. i mean, downright rude.

i avoid namespaces in C# because of the extra indentation

what’d be nice if there was an option in visual studio to NOT INDENT namespaces like we indent other blocks.

so it’d be like


namespace ns
{
class c
{
  public static int x ;
  public void method()
  {
    if( x == 5 )
    {
      Console.WriteLine("Everything indents normally except for the NAMESPACE");
    }
  }
}
}

I still think Java’s package statement is by far superior notation because it doesn’t indent the whole file. namespace declarations that were Java-like WERE ALLOWED in .NET 1, but they’re not allowed anymore.

Adding them is easy

Say we have 3 tables, users, sports, and users_sports_hobbies. The user_sports_hobbies table relates the users and sports table to tell what sports, each user likes.


-- drop tables with REFERENCES to table
-- because you can't drop the users or sports
-- tables WHILE users_like_sportsx refers
-- to it!
-- drop table users_like_sports1;
-- drop table users_like_sports2;
-- drop table users_like_sports3;
-- drop table users;
-- drop table sports; 

-- create the users table
create table users(

  user_id int not null primary key identity,
  username varchar( 255 )

) ;

-- and the sports table
create table sports(

  sport_id int not null primary key identity,
  sport_name varchar( 255 )

) ;

-- create the users_like_sports1 table
-- with foreign keys
-- compact notation, not naming the foreign key
-- constraints
create table users_like_sports1 (

  rel_id int not null primary key identity,

  user_id_fk int not null
  FOREIGN KEY REFERENCES users( user_id ),

  sport_id_fk int not null
  FOREIGN KEY REFERENCES sports( sport_id )

) ;

-- now here's the same thing, a users_like_sports table
-- only using a different notation to declare the
-- foreign keys.  this is completely functionally
-- equivalent to the above way, only in this
-- way i'm showing you here, I am NAMING
-- the foreign key constraints.  This is useful
-- for DROPPING the foreign key constraint off
-- the table later.
create table users_like_sports2 (

  rel_id int not null primary key identity, -- this is the "relationship id",
  -- i am in the habit of ALWAYS having a primary integer key for
  -- every field, even if it doesn't obviously serve any purpose here
  -- It may come in useful later, and its a real ass-biter to NOT
  -- have put in a simple integer primary key  

  -- Here is one way to do it:
  user_id_fk int not null
  CONSTRAINT fk_1a FOREIGN KEY REFERENCES users( user_id ),
  -- now we've said that the user_id_fk field
  -- is constrained by a constraint named "fk_1"
  -- and its a foreign key constraint, referencing
  -- the user_id column from the users table.
  -- (the name of the constraint "fk_1"
  -- is useful for deleting this constraint later, if need be)

  sport_id_fk int not null
  CONSTRAINT fk_2a FOREIGN KEY REFERENCES sports( sport_id )

) ;

-- Finally here is a different notation.  This is a
-- more common blown out notation
-- listing the foreign key references
-- at the bottom of the table specification.
create table users_like_sports3 (

  rel_id int not null primary key identity,

  user_id_fk int not null,
  sport_id_fk int not null,

  CONSTRAINT fk_1b FOREIGN KEY (user_id_fk) REFERENCES users( user_id ),
  CONSTRAINT fk_2b FOREIGN KEY (sport_id_fk) REFERENCES sports( sport_id )

) ;

-- ***
-- DROPPING THE CONSTRAINTS
-- Now here is how you drop the foreign key constraints
alter table users_like_sports2
drop constraint fk_1a ;

alter table users_like_sports2
drop constraint fk_2a ;

-- users_like_sports2 table now has
-- NO CONSTRAINTS AT ALL.  They
-- have been DROPPED.

-- Dropping the constraints for
-- table users_like_sports3
alter table users_like_sports3
drop constraint fk_1b ;
alter table users_like_sports3
drop constraint fk_2b ;

-- we can't easily drop the
-- constraints for users_like_sports1
-- since we don't have the constraint
-- names.
drop table users_like_sports1 ;

-- now that all references and constraints
-- to these two tables have been dropped,
-- we can safely drop the users and sports tables.
drop table users;
drop table sports;

If you don’t really need web history, just turn it off in firefox. A lot of what bogs firefox down (slow startup, slow action when typing something into the address bar) is because of the immensely detailed history it tries to keep for you.

Sheesh. It even keeps track of which letter sequences you type into the address bar, and which address you end up selecting (for instance, when I start to type “gm”, then I usually press the down arrow to pick gmail.com”). This is how firefox is smarter, but also slower. For me, I’m happier with the faster performance.

windows 3.1 i wanted windows 95.
windows 95. i wanted windows 98, kinda.

windows 95. i REALLY wanted winxp.

winxp. wanted vista.

vista. back to xp.

xp. want windows 7? eah, not sure.

xp is good.

windows 7 RC? use it for a year? eah. I want xp.

do you see how one mess up, one “bad release” (yes, I HAVE tried it) – you just can’t have an o/s start up, look all fine, then it jump down your throat for “needing permission” to move a basic file.

i created my login name as “root”! what more do you want?

sheesh. i mean, if they want to shove security issues down my throat, they really shouldn’t do it this way.

also being a developer, I don’t like the “toy” messages – “this application has stopped working”

What? then start it back up again! vista, why are you screwing with me?

I mean, saying “the application BROKE” would make more sense. But “has stopped working” is just too gay and “politically correct” – it still makes me think that vista is behind the application “stopping to work”.

I do not like the vista LOOK. the aero scheme, and the new window layouts, i think its because i’m sour on vista. what was so sleek and cool when it first come out turned out to be a lie and a signature for “SLOW” – the one thing I cannot stand from my machine.

I’m HAPPY to hear that Windows 7 is a huge improvement over vista – that its like the “new XP” that everyone wanted for christmas in 2006. I’m not trying the beta or the RC, I don’t think. I’m just going to wait and hope it doesn’t suck.

General tools

  • Winspector for examining Windows messages
  • Winmerge for code file diffing
  • WinDiff for diffing either single files, or entire folders. This is a powerful program, don’t let its simple appearance deceive you. Comes with Windows SDK, if you develop for Windows you probably already have it.
  • Regex Coach for testing out regular expressions
  • TCPView for looking at net connections that are active, and what program is using it
  • the rest of the SysInternals suite (great tools!)
  • PuTTY for telnet
  • a href=”http://www.oldversion.com/download_WS_FTP_LE_6.html”>ws_ftp 6 for FTP file transfers, before it became bloatware
  • DaemonTools – mounts DVD images to your hard disk, though i like poweriso as well (*poweriso is not free, its shareware)
  • Teracopy. For copying files between disks. This application is BLAZINGLY fast, you won’t believe it – if you’re used to Windows Explorer copies.

media/mp3

  • GoldWave – a fantastic recorder/wav/sound editor
  • Winamp – just THE BEST media player. Now plays FLV!
  • VLC for all those avi’s that just refuse to play with anything else

NES and games

Web

(this section lacking, i know)

  • Not so much these days, but multiple ie gives you ie 6

Windows directory comparison tool

I was LOOKING for one for a long time. I finally found one, right on my own system!!

C:\Program Files\Microsoft SDKs\Windows\v6.1\Bin\x64\WinDiff.Exe

So it comes with the Windows SDK. Try searching for WinDiff on your computer

If you don’t already have it, then you can get it here.

I use it mostly because I keep redundant copies of entire folders, a lot of the time. For example, when my laptop was going down (lost ability to recharge from wall.. it was gonna go in for repairs!) i made an emergency dump of all the files that were on it. Some of the code files I had several copies of already, so WinDiff expedites the process of being able to blow away entire folders that are completely redundant -

Its pretty neat.

You can also blow out the thing, to see the actual file that is causing the diff

Well, to quote the great master:

When Windows needs to load a DLL module before running a program that requires it, the library file must be stored in the directory containing the .EXE program, the current directory, the Windows system directory, the Windows directory, or a directory accessible through the PATH string in
the MS-DOS environment. (The directories are searched in that order.)

Programming Windows 5th edition, page 962

MSDN ref

i was trying to run my ogre apps from the root..

and you know what happened?

yeah. delta 3d hijacked my setup.

debug output:

‘aiSimulator.exe’: Loaded ‘C:\CPP\Projects\2009\grad\aiSimulator\Debug\aiSimulator.exe’, Symbols loaded.
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\SysWOW64\kernel32.dll’
‘aiSimulator.exe’: Unloaded ‘C:\WINDOWS\SysWOW64\kernel32.dll’
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\SysWOW64\ntdll.dll’
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\SysWOW64\kernel32.dll’
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\SysWOW64\user32.dll’
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\SysWOW64\gdi32.dll’
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\SysWOW64\advapi32.dll’
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\SysWOW64\rpcrt4.dll’
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\SysWOW64\secur32.dll’
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\WinSxS\x86_Microsoft.VC90.DebugCRT_1fc8b3b9a1e18e3b_9.0.30729.1_x-ww_f863c71f\msvcp90d.dll’
‘aiSimulator.exe’: Loaded ‘C:\WINDOWS\WinSxS\x86_Microsoft.VC90.DebugCRT_1fc8b3b9a1e18e3b_9.0.30729.1_x-ww_f863c71f\msvcr90d.dll’
‘aiSimulator.exe’: Loaded ‘C:\Program Files (x86)\Delta3D_REL-2.2.0\ext\bin\CEGUIBase_d.dll’
LDR: LdrpWalkImportDescriptor() failed to probe C:\Program Files (x86)\Delta3D_REL-2.2.0\ext\bin\CEGUIBase_d.dll for its manifest, ntstatus 0xc0150002
Debugger:: An unhandled non-continuable exception was thrown during process load
The program ‘[2860] aiSimulator.exe: Native’ has exited with code 128 (0×80).

But I’m running an OGRE game.. ah. because CEGUIBASE_d.dll is found first in the delta3d folder, windows it tries to load IT, and because ogre came after in the path setting.. something got screwed up

so all i did was remove delta 3d fro the path setting, RESTART and voila, its fine

Well, in Python, you can attach an ELSE to a WHILE statement like so:

# python
while oi.hasNext() :
  print oi.value
else :
  print 'oi had no values'

You can’t do that in C++, but you can do this instead:

// C
if( ! oi.hasNext() )
  print 'oi has no values' ;
else do
{
  print oi.value ;
} while( oi.hasNext() ) ;

I used else do instead of


if( ! oi.hasNext() )
  print 'oi has no values' ;
else while( oi.hasNext() )
{
  print oi.value ;
} 

In case that oi.hasNext() has a side effect (such as advancing an iterator).. in this case, oi.hasNext() gets called twice before we ever try to read oi.value.

#include <stdio.h>
#include <map>
#include <string>

using namespace std;

// C++ affords PLENTY of mechanisms
// to make its code much less ugly.

// using namespace declarations,
// #defines and typedefs - but yet
// so many developers choose not
// to use these features and are
// perfectly content seeing lines
// of code like
// for( map::iterator iter = history.begin() ;iter != history.end(); ++iter )

// While it could look like
// foreach( HTIterType, iter, hash )

// I show how here.

int main()
{
  typedef map Hashtable;

  map history ;

  history[ "first" ] = "bob" ;
  history[ "second" ] = "mcnugget" ;

  //string val = history[ "first" ];
  //printf( "val is %s", val.c_str() );

  for( map::iterator iter = history.begin() ;
       iter != history.end();
       ++iter )
  {
    printf("key: %s / val: %s\n", iter->first.c_str() , iter->second.c_str() );
  }

  // Here's a more elegant way of doing that same thing

  // Create a new type called Hashtable, which
  // is going to be exactly equivalent to
  // the map type
  typedef map<string,string> Hashtable ;

  // now define the HashtableIterator type
  typedef map<string,string>::iterator HTIterType ;

  // now create a hashtable
  Hashtable hash ;
  hash[ "firstentry" ] = "hello" ;
  hash[ "another"] = "there" ;

  // now use a "foreach" loop
  #define foreach( x, y, z ) for( x y = z.begin(); y != z.end(); ++y )

  // this is supposed to read "foreach ( HTIterType iter in hash )"
  foreach( HTIterType, iter, hash )
  {
    printf("key: %s / val: %s\n", iter->first.c_str(), iter->second.c_str() );
  }

  // Because the #define above turns:
  // foreach( HTIterType, iter, hash )

  // into:
  // for( HTIterType iter = hash.begin(); iter != hash.end(); ++iter )

  // which is in turn equivalent to
  // for( map::iterator iter = hash.begin(); iter != hash.end(); ++iter )
}

Well, the problem with my application was I wasn’t capturing the mouse.

bool frameRenderingQueued( const FrameEvent & evt ) override
{
mKeyboard->capture();
mMouse->capture();

return true;
}

The secret to a fresh-smelling butt is

shave your asshole
use damp toilet paper

I just looked up “fey”, as in tina fey, and can you believe fey means “slightly insane”??

i’m watching through the first season of studio 60 right now.
last week, i watched through season 1 of 30 rock.

i’m just thinking, about the differences between the two.

first thing i’m noticing is the ATMOSPHERE of studio 60: darker, MORE CONFRONTATIONAL.

studio 60 is about a bunch of actors who are constantly surrounded by drama. the show is in a way extremely melodramatic.

30 rock on the other hand isn’t AT ALL like that. 30 rock is airy and fluffy – its light and its funny. the jokes are about silly things that have no consequences – like getting an illegal fish -

THE CAST. 30 rock is filled with fun and UNIQUE characters you don’t see often – Kenneth – I love kenneth and his mannerisms. Lemon. Tracy. They all bring something to the show – they fight among each other but its not a nabbling kind of fighting.

I don’t know. The first episode of Studio 60 was GREAT. It was dramatic and it kind of made your head spin. I’m on the 4th episode and the show is rapidly decaying. The entire premise – the whole idea of the show being about struggling to produce a show is a bit too – I don’t want to say “prophetic” – but it seems like the writers of the show really aren’t getting the show itself together.

Also 1 hour /44 minutes is too long. There’s SO MUCH TALK about “filling 90 seconds” – I mean, they spend 90 seconds of the show itself worrying about how they’re going to fill 90 seconds of their “live” show -

If these shows came out at the exact same time, 30 rock would have absolutely steamrolled over studio 60 (if they were in any kind of competition).

Where was I in 2006? I don’t know. I didn’t watch either show back then.

Dear Interweb,

Can I propose class:gets()?

I mean, come on, this method is used COMMONLY everywhere. Can’t we all just agree to save keystrokes and just use class::gets() as a standard instead of class::getSingleton()?

Well, one thing I love about C++ is #define

I’m going through Ogre now, and I’m seeing A LOT of

CEGUI::WindowManager::getSingleton()

The great thing about C++ is I’m replacing this ugly call with

#define WinMan CEGUI::WindowManager::getSingleton()

So this makes it MUCH better to look at

CEGUI::Combobox* objectComboBox = (CEGUI::Combobox*)CEGUI::WindowManager::getSingleton().getWindow(“OgreGuiDemo/TabCtrl/Page2/ObjectTypeList”);

VS

CEGUI::Combobox* objectComboBox = (CEGUI::Combobox*)WinMan.getWindow(“OgreGuiDemo/TabCtrl/Page2/ObjectTypeList”);

huh?

self-fulfilling prophecy
A situation where “a false definition, in the beginning… evokes a new behavior which makes the original false conception come true.”

Canadians start with a false definition of who the best nine- and ten-year-old hockey players are. They’re just picking the oldest every year. But the way they treat those “all-stars” ends up making their original false judgement look correct. As Merton puts it: “this specious validity of the self-fulfilling prophecy perpetuates a reign of error. For the prophet will cit the actual course of events as proof that he was right from the very beginning.”

From Blink, by Malcolm Gladwell, page 25

We’ve all seen this.

Well, some people say there isn’t one.

But there is.

The short of it is, instead of writing base.FunctionName() as you would in C#, you write BaseClassName::FunctionName(). And NO, you DO NOT have to pass “this” to the base class.. although you do not use THIS in the invocation of the base class function in any way, C++ passes it automatically.

Short and long example follow.

Short and sweet

class BaseClass
{
public:
  BaseClass()
  {
  }

  virtual void OverrideMe()
  {
  }
}

class DerivedClass : public BaseClass
{
public:
  DerivedClass() : BaseClass() // explicit call base class ctor.
  {
  }

  void OverrideMe()
  {
    // run some stuff

    // call the OverrideMe() function of
    // the base class, "this" will be passed
    // automatically.  Clearly can't do this if
    // base class has purely virtual function
    BaseClass::OverrideMe() ;

    // The REASON for the non-existence
    // of base:: or super:: is because
    // of multiple inheritance
  }
}

Longer example

#include <stdio.h>

class Sprite
{
public:
  char * name ;

  Sprite()
  {
    name = "Dartagnian" ;
    printf( "Sprite alive, named %s\n", name );
  }

  Sprite( char* desiredName )
  {
    printf("Sprite '%s' alive\n",desiredName);
    name = desiredName ;
  }

  virtual void Speak()
  {
    printf( "  %s [ the Sprite ] saying hello\n", name );
  }
};

class Grunt : public Sprite
{
public:
  Grunt()
  {
    printf("A new grunt is alive and kicking, the base class ctor will pass the default name in.\n");
  }

  Grunt( char* desiredName ):Sprite( desiredName )
  {
    printf("RRU?? '%s' alive\n",desiredName);
  }

  void Speak()
  {
    printf( "  rrru?  me %s say Hi!\n", name );

    // C++ has no SUPER keyword
    // and no BASE keyword, on account
    // of multiple inheritance, or so
    // it is said.  But we can still access
    // the base class functionality
    // by casting "this" to being a pointer
    // to an instance of the base class.
    //( (Sprite*)this )->Speak();
    // HOWEVER, this is a BAD WAY TO DO IT.

    // The reason is, if the base class function
    // is marked "VIRTUAL", then what will happen is
    // THIS (the Grunt's) Speak() function will
    // be called repeatedly.

    // So to call the base class
    Sprite::Speak();
  }
} ;

int main()
{
  Grunt g("Grom!!");

  g.Speak();
}

Ref 1, ref 2

source

Access control of base class members (C++ only)

When you declare a derived class, an access specifier can precede each base class in the base list of the derived class. This does not alter the access attributes of the individual members of a base class as seen by the base class, but allows the derived class to restrict the access control of the members of a base class.

You can derive classes using any of the three access specifiers:

* In a public base class, public and protected members of the base class remain public and protected members of the derived class.
* In a protected base class, public and protected members of the base class are protected members of the derived class.
* In a private base class, public and protected members of the base class become private members of the derived class.

When trying to compile/run my new Ogre app in release mode, I came up with this error:

Assertion failed!

Program: …
File: f:\codingextra\ogre\shoggoth_vc9\ogr…\ogreroot.cpp
Line: 103

Expression: ms_Singleton

For information on how your porgram can cause an assertion failure, see the Visual C++ documentation on asserts

(Press Retry to debug the application – JIT must be enabled)

Abort/Retry/Ignore

OK here’s the image

It turns out that this problem comes up because you tried to build in Release mode while still linking to the DEBUG MODE (ending in _d.dll) libraries.

The libraries that ogre will link to are in plugins.cfg:

# Defines plugins to load

# Define plugin folder
PluginFolder=.

# Define plugins
Plugin=RenderSystem_Direct3D9_d
Plugin=RenderSystem_GL_d
Plugin=Plugin_ParticleFX_d
Plugin=Plugin_BSPSceneManager_d
Plugin=Plugin_CgProgramManager_d
Plugin=Plugin_PCZSceneManager_d.dll
Plugin=Plugin_OctreeZone_d.dll
Plugin=Plugin_OctreeSceneManager_d

So I just changed this file to:

# Defines plugins to load

# Define plugin folder
PluginFolder=.

# Define plugins
Plugin=RenderSystem_Direct3D9
Plugin=RenderSystem_GL
Plugin=Plugin_ParticleFX
Plugin=Plugin_BSPSceneManager
Plugin=Plugin_CgProgramManager
Plugin=Plugin_PCZSceneManager.dll
Plugin=Plugin_OctreeZone.dll
Plugin=Plugin_OctreeSceneManager

Just basically taking away all the _d at the end of the file names.

I also made sure to LINK TO the correct libraries – I prefer inline linking instead of fiddling with the Visual Studio Project options dialog boxes, so I have this code:

#ifdef _DEBUG
#pragma comment( lib, "CEGUIBase_d.lib" )
#pragma comment( lib, "OgreGUIRenderer_d.lib" )
#pragma comment( lib, "OIS_d.lib" )
#pragma comment( lib, "OgreMain_d.lib" )
#else
#pragma comment( lib, "CEGUIBase.lib" )
#pragma comment( lib, "OgreGUIRenderer.lib" )
#pragma comment( lib, "OIS.lib" )
#pragma comment( lib, "OgreMain.lib" )
#endif

This is my problem with MSVC++

What on EARTH does _Kty, _Ty, _Pr, _Alloc even ___MEAN___ ??? Through 3 VERSIONS of MSVC++ i’ve seen (VC 7, VC8, and even now in VC9) we haven’t seen __ANY__ improvement whatsoever in making standard library function autocomplete not stupid.

I like the idea of an ITNERFACE that provides.. more capabilities. (or less).

HTMLDocumentClass htmlDoc = new HTMLDocumentClass();

IHTMLDocument2 iHTML = htmlDoc ;

Because HTMLDocumentClass IMPLEMENTS IHTMLDocument2, we can look at the HTMLDocumentClass object AS IF IT WERE JUST an object AS DESCRIBED BY the IHTMLDocument2 interface.

The INTERFACE is like a JOB.

ME. I can implement: ISoftwareProgrammer, IMan, IHusband, IBoxer, IMotorcyleRider.

Say I implement all those interfaces. I am an instance of class Human, implementing the above listed interfaces.

In your interaction with me, your interaction with me is LIMITED. So, say you are a woman who takes no sexual interest in me whatsoever. So you will basically view me from my PROFESSIONAL INTERFACE: my ISoftwareProgrammer interface. Your view of me is going to only be .. seeing me as a SoftwareProgrammer, and not as a boxer, husband or anything else that I AM. Because you dael with me THROUGH the ISoftwareProgrammger interface, you SEE ME AS just someone who implements the ISoftwareProgrammer interface requirements and you WILL NOT SEE any of the other interfaces that I implement.

In other words, dealing with me through an INTERFACE makes me … a pawn.

Dealing with people through the correct interface insures correct behavior. Knowing which interface to use, prevents lawsuits such as using your IBarAttendee interface on a coworker.

Because I am a Boxer, I COULD punch your lights out. But when you deal with me professionally, you actually won’t see that, because you deal with me exclusively through my ISoftwareProgrammer interface.

Now when I’m down at the track, riding my motorcycle, all the people THERE are seeing me as implementing the IMotorcycleRider interface. They don’t know and they don’t care what other interfaces I implement. I implement, IMan, IHusband and ISoftwareProgrammer interfaces, so they COULD interact with me through those interfaces .. through my softwareProgrammer interface I can be asked to .Code something – ( (ISoftwareProgrammer)me ).code() ;

REALLY, I have these methods:
me.Eat() // due to me being of base class Human
me.Sleep() // due to me being of base class Human

me.Code() // due to software programmer interface, i implement .code()
me.Grunt() // due to man interface, i implement .grunt()
me.Serve() // due to the husband interface, I implement .serve()
me.Punch() // due to IBoxer

But when you deal with me through the ISoftwareProgrammer interface, you actually do not see my other capabilities, really. If you dealth with me through the Human base class interface, you might see I only do .Eat() and .Sleep().

Doesn’t that make sense?

So, WHY program to an interface.

Programming to an interface makes it so that the way to interact with the underlying code remains fixed, even though the code itself might change radically.

To understand this, say you get work done on your car. You want to soup it up, you want to make it go faster. What kind of mods done to your car will _not bother you_? Mods that change / improve how the car works inside, WITHOUT CHANGING THE WAY YOU AS THE DRIVER INTERFACE TO THE CAR.

The interface of your car is standard. It has pedals to stop and go, and a wheel to steer. If you did a soup up that changed your steering wheel to a stick, then you WOULD have SERIOUS problems getting used to the new steering “wheel” (or stick). If suddenly the pedals were put on the roof, it would be very hard for you to get used to that. In fact, you would probably be angry.

Is it any wonder software programmers get angry when libraries change their interfaces? When a programming library changes its interface (ALA D3D, DirectX SDK is ALWAYS doing this) then it means that we as programmers must change our code that uses those interfaces. Microsoft has gone and made a wheel a stick, or a stick a wheel, and our program code must change to accomodate that fact.

Ideally interfaces are CONCRETE and do not change often. When an interface does NOT change, it means your code that uses an interface has a WAY easier time handling “upgrades”. Its like dropping a new engine into your car, and you finding the car equally easy to drive. The interface – or how you interact with the car – has not changed – the steering wheel and pedals are still the same. But something internal to the car – the engine in this case – has been improved and replaced – so while you still use your car the same way, it just works better.

In an ideal world that is what Interfaces are SUPPOSED to do for software. An Interface is SUPPOSED TO be written in stone, something that doesn’t change, and it is the “outline” of functions and data members that a class exposes for YOUR CODE to use. Upgrading the code of a class that IMPLEMENTS an interface should not require changes to the code that USES that class.

you can’t create an instance of an interface directly because.. well you can’t just have a SOFTWARE PROGRAMMER. There is no such thing.. there’s only people who are software programmers.. PEOPLE that IMPLEMENT the ISoftwareProgrammer interface. Invariably you’re going to get a PERSON who can do many more things than just software program.

I had this problem that kept coming up again and again, so I’m recording it here.

The problem is when you have a server that listens for UDP packets. Its fine, its open, no firewalls are causing issues at that end. Say its at 200.100.205.70:10006

Now, you want to connect to that server using a UDP sockets program on your local machine. Because you have a firewall, you need to DICTATE from which IP:Port your local sockets program will send sockets.

So naturally, you first go to your firewall software (in your router) and you open port 10007 on 192.168.1.105 (which is your IP address assigned to you by your router).

Now from your client sockets program, you send UDP packets out on a UDP socket which is bound to 127.0.0.1:10007.

It doesn’t work.

WHY??? BECAUSE YOU DIDN’T OPEN 127.0.0.1 ON YOUR ROUTER/FIREWALL, NINNY, YOU OPENED 192.168.1.105!!

Even though the UDP socket is being sent from “THIS MACHINE” (which is probably what you intended when you used the loopback), LOOPBACK != EXTERNAL IP ADDRESS!!

Sending data from the loopback address is actually completely different to the router.. than sending data from your externally assigned ip address. So, yes, if you are connected to the internet, your computer DOES have minimum 2 ip addresses (loopback and the external ip address the router gives you). Actually it has 5: 127.0.0.1, 127.0.0.2, 127.0.0.3, 127.0.0.4 are all loopback. Then the external ip (which for me was 192.168.1.105).

OK!! So how do you fix it?

You bind the UDP socket to

192.168.1.105

OR

bind it to (IPADDRESS.ANY, 10007) (like, 0.0.0.0:10007).

Hmm. That DOESN’T MAKE SENSE, does it?

Aaron Zupancic (from web archive) says its Microsoft’s fault.

This is basically what the Microsoft article says:

If sending a datagram using the sendto function results in an “ICMP port unreachable” response … the subsequent call to recvfrom does not work with a WSAECONNRESET (10054) error response.

Isn’t that STUPID?? Isn’t that like, totally against the spirit of UDP? Isn’t the UDP protocol supposed to like, “not care” if the message doesn’t get there? Why are you throwing this error in my face now when I don’t expect it, Microsoft?

Anyway, here it is again: On a UDP-datagram socket this error indicates a previous send operation resulted in an ICMP Port Unreachable message.

Anyway, it only happens once PER TIME you call sendto() on an (address,port) that isn’t set up to receive a UDP packet. Basically, when you send something to an (address,port) that CANNOT RECEIVE IT, you get this error on your NEXT call to recvfrom(). Its a pretty roundabout and counter intuitive way of doing stuff, but hey, so are a lot of other things in sockets (EWOULDBLOCK on nonblocking socket when you try to receive, zero-length packet when someone closes a TCP connection..), but it CAN BE pretty useful to know that SOMEONE has gone away and you should check the whether each of the clients you THINK is there, if any of them has gone away (which one of them certainly has).

You know what song, I just heard, which took me back to camp times..

“I’d like to teach the world to sing..”

I’d pay .. a million dollars to hear it by KT Tunstall

I wish we could request artists to do covers of songs we think they’d sound cool doing.. alas, radio shows, for songs we already know..

1. in solving problem with logarithms

n log2(n) = 8

What is the solution?

nn = 28

seems wrong.

2. in solving selection sort complexity

What is this summation?

I thought it was to pull out ( n – 1 )*( n + 2 ) term, but I’m not SURE that is correct (though it seems correct)

#include <stdio.h>

void p( int a[], int len )
{
  for( int i = 0; i < len - 1; i++ )
    printf( "%d, ", a[i] ) ;
  printf( "%d\n", a[ len - 1 ] ) ;
}

int main()
{
  int a[] = { 3, 6, 2, 11, 59, 5782, 2 } ;
  int len = sizeof(a) / sizeof(int) ;

  p(a, len) ;

  // selection sort

  // Imagine you have 6 pieces of pasta, all
  // of different lengths.

  // |
  // |         |
  // | |     | |
  // | | | | | |
  // 0 1 2 3 4 5

  // Now you want to put them in order of increasing height.
  // Here's what you do with selection sort.

  // You start at the very left side.
  // You pass through all sticks,
  // in the rest of the collection
  // LOOKING FOR THE SMALLEST ONE.

  // You identify the smallest one
  // as index 2.

  // |
  // |         |
  // | |     | |
  // | | | | | |
  // 0 1 2 3 4 5

  // Swap with the item at index 0.

  //     |
  //     |     |
  //   | |   | |
  // | | | | | |
  // 0 1 2 3 4 5

  // Now you are on index 1.  You need to
  // pass through array elements 2-5 and
  // find the smallest one in THAT set
  // of the collection.

  // You identify the smallest as index 3.
  // swap.

  //     |
  //     |     |
  //     | | | |
  // | | | | | |
  // 0 1 2 3 4 5

  // Keep going.
  // 2 swaps with 3

  //       |
  //       |   |
  //     | | | |
  // | | | | | |
  // 0 1 2 3 4 5

  // 3 swaps with 4

  //         |
  //         | |
  //     | | | |
  // | | | | | |
  // 0 1 2 3 4 5

  // 4 swaps with 5
  //           |
  //         | |
  //     | | | |
  // | | | | | |
  // 0 1 2 3 4 5

  // and we're done

  //////////
  // The algorithm.
  // We will walk through the array ONE TIME
  // from the first element to the SECOND LAST
  // element.  We don't need to "sort" the very
  // last element.  Think about it.
  for( int i = 0 ; i < len - 1 ; i ++ )
  {
    // Now, at each element, we want to
    // find the SMALLEST ELEMENT TO THE
    // RIGHT OF IT, so we can swap the
    // current element (at i) with the
    // smallest element in the rest of the list.

    // set the mini = minimum index to be
    // ASSUMED to be the one immediately
    // to the right of the element we are
    // currently sorting.
    int mini = i + 1 ;

    // now, walk through the rest
    // of the list .. everything to the right
    // of the current element we are sorting
    // must be examined... NOTHING to the left
    // will be examined because that part
    // HAS ALREADY BEEN SORTED.

    // Once we reach the 3rd element, for example,
    // you should realize that THE FIRST 2 SLOTS
    // WILL ALREADY CONTAIN THE TWO SMALLEST
    // ELEMENTS IN THE WHOLE ARRAY.  Take a
    // look at what this next loop does to understand
    // why.

    for( int j = i + 1 ; j < len ; j++ )
      if( a[ j ] < a [ mini ] )   // if this jth element is smaller than the smallest we found so far
        mini = j ;   // then set the smallest to being j

    // swap a[ i ] with the SMALLEST ELEMENT
    // we could find
    int tmp = a[ i ] ;
    a[ i ] = a[ mini ] ;
    a[ mini ] = tmp ;
  }

  p(a, len) ;
}

The question is: How many bits do you need to represent the following numbers in a computer?

a) 3000

b) 3

c) 20

d) 598225

The answer to each is found by this formula:

numBits = 1 + log2( n )

If you are on a hand-calculator, you can always get log2 by doing:

numBits = 1 + log10n
log10(2)

Dividing by log102 gives you the right answer.

#include <stdio.h>

void p( int a[], int len )
{
  for( int i = 0; i < len - 1; i++ )
    printf( "%d, ", a[i] ) ;
  printf( "%d\n", a[ len - 1 ] ) ;
}

int main()
{
  int a[] = { 5, 9, 1, 22, 6, 7, 7, 90 } ;
  int len = sizeof( a ) / sizeof( int ) ;  // *note:
  // sizeof() doesn't work for pointer (int * a) style arrays 

  p( a, len ) ;

  // The insertion sort algorithm is here, and
  // every line is explained in comments.

  // UNDERSTANDING INSERTION SORT
  // The best analogy for understanding insertion
  // sort is if you think of holding a hand of cards.

  // Say you have this hand:
  // 7, 2, 5, 8 

  // Now you like to see things in order, so you
  // want them to have the order 2, 5, 7, 8.  What's
  // the easiest way to order the cards without
  // putting them down flat on the table?

  // You'd probably do this.  Start at the
  // very left hand side.  Skip the first card,
  // and PULL OUT the second card
  // so now you're looking at the 2.

  // In left hand:  7, ___,  5, 8
  // In right hand:  2

  // (the empty space is where the 2 WAS)

  // FROM the place where the 2 WAS,
  // work backwards until
  // you find where that 2 "SHOULD GO"
  // in the GREEN ("already sorted") section.

  // Clearly the 2 should go in front of the 7.

  // Thinking like a computer...

  // To make the 2 go in front of the 7, we have
  // to SLIDE the 7 over to occupy the space
  // where the 2 WAS:

  // In left hand:  ___, 7,  5, 8
  // In right hand:  2

  // Now we can insert the 2 into that blank spot:

  // In left hand:  2, 7,   5, 8
  // In right hand:  ___

  // You just keep going
  // until you INSERT all the cards from the
  // UNSORTED section
  // into their correct positions in the SORTED section

  // Next step:  We're on the 5.

  // Pull it out.

  // In left hand:  2, 7, ___  8
  // In right hand:  5

  // WORK BACKWARDS FROM the ___ spot.

  // AS WE STEP BACKWARDS,
  // we are looking for an entry in
  // the already sorted section that
  // is SMALLER than the number
  // we have plucked out in our right hand
  // (the 5 in this case)

  // In left hand:  2, 7, ___  8
  // ** NO, 7 is not SMALLER than 5.
  // So we simply siddle the 7 up

  // In left hand:  2, ___, 7  8
  // ** YES, 2 is smaller than 5, so
  // our 5 will belong right after the
  // 2 (where the blank space happens
  // to be right now!!)

  // We simply insert the 5 here,
  // and we are done with the 5.
  // In left hand:  2, 5, 7  8

  // last step:  remove the 8:

  // In left hand:  2, 5, 7, ___

  // Start by looking at the 7.  7
  // is less than 8, so the 8 goes
  // in after the 7 (where it was
  // basically)

  // In left hand:  2, 5, 7, 8

  // And that's the algorithm.

  // NOTICE the method you use.  At every card
  // you attempt to sort, you count BACKWARDS
  // from the place you pulled it out from,
  // until you find a number that is SMALLER
  // than the card you are trying to insert.

  //////////////
  // THE C CODE: 

  // the outer for loop.  the outer loop walks us
  // THRU the array, FORWARDS, ONCE.

  // In this SINGLE PASS through the array
  // we are sorting, at EVERY number we hit
  // we will STOP, look back through the
  // beginning part of the list, and put that
  // number WHERE IT BELONGS.

  for( int j = 1;  // start at the SECOND element of the list
       j < len ;   // go until the end of the list
       j++ )       // one at a time.
  {
    // { 5, 9, 1, 22, 6, 7, 7, 90 } ;
    //     ^^^
    //    ( START HERE, not at the very beginning )

    // Now, at EACH number you're at
    // first, we must SAVE IT OFF.

    // Reason:  Its going to be overwritten.
    int KEY = a[ j ] ;

    // This is equivalent to "pulling
    // the card out" in the explanation above.

    // Next, we walk BACKWARDS through
    // the array, STARTING at the position
    // JUST BEFORE the card we "pulled out"

    int i ;
    for( i = j - 1 ;  // start at position JUST BEFORE item we pulled out
         i >= 0 ;     // we'll walk down until the VERY BEGINNING of the list
         // ** UNLESS WE FIND A NUMBER IN THE LIST
         // THAT IS SMALLER THAN KEY (in which case
         // we will BREAK out of this loop)

         i-- )        // we're walking backwards thru the list
    {
      // Now, we are LOOKING FOR
      // a number in a[] that is
      // SMALLER than the KEY we
      // have in our hand.

      // Once we find a number that
      // is SMALLER than the KEY,
      // we will know where to
      // insert the KEY (right
      // after THAT number which is
      // smaller than the KEY.)

      // Notice how this assumes that
      // everything to the left of the KEY
      // IS ALREADY SORTED (which it will be
      // as this algorithm works through
      // the list).
      if( a[ i ] < KEY )
      {
        // Found spot for KEY.  Stop "siddling"
        // (see ELSE statement below for "siddle").

        break;
      }
      else
      {
        // siddle.  copy element over.

        a[ i + 1 ] = a[ i ] ;

        // on the first iteration, this
        // operation will overwrite the KEY
        // in the array (hence the need to
        // save it off in a separate variable).
      }
    }

    // Insert the key.
    a[ i + 1 ] = KEY ;
  }

  p( a, len ) ;
}

liz owns..

I just love how the other girl tucks her hand away.

The internet2is dissent.

Come on. You can’t form a separate network and call it Internet2. This is totally against the spirit of the Internet and I can just see myself having to dial up to different networks.. No. This doesn’t sound right.

this youtube video on Bush’s statement about the “internets” was actually correct.

Actually the original subtitle of this blog was “technology and the internets”. mwtss.

I’ve never seen this before: VIDEO SPAM!!

just wanted to record this before askimet says bye-bye. thanks askimet!

TCP VS UDP

And why TCP is unsuitable for games

OK, so I did some comparisons using a server of mine.

The thing is, TCP and UDP ARE pretty much equal when it comes to transportation times across the internet.

In my tests, I sent 10,000 messages across about 50km (my server is located about 50km from where I am now).

The results:

UDP: Average round-trip time: 30ms

TCP: Average round-trip time: 500ms

Now you’re saying WTF???? YOUR TEST IS WRONG!! But allow me to explain.

The reason the TCP tests were so awful, is, well, here, take a glance at numerics of the results first.

UDP RESULTS:
DIFF=0.0278434801501
DIFF=0.0305130913992
DIFF=0.0277071201201
DIFF=0.027180660817
DIFF=0.0300143798507
DIFF=0.0273463786314
DIFF=0.0335492180775
DIFF=0.0280604430992
DIFF=0.0330231491187
DIFF=0.0273172101218

// And it looks the same for all 10000 messages.. no huge latencies at all.
// these are in SECONDS, so it translates to about 30ms per datagram.

// BTW, in this test, I sent 10000 messages and received 9994 of them.

Now for the TCP results..

// First few, at the beginning when the application first launched…
DIFF=0.0373954983804
DIFF=0.0373870345209
DIFF=0.0373785706613
DIFF=0.0373701068017
DIFF=0.0373617621515
DIFF=0.0373534175012

// HMM, that looks pretty much the same as TCP
// Scrolling down a bit… it gets worse..
DIFF=0.0669155569774
DIFF=0.0669068546993
DIFF=0.066898510049

// further down still..
DIFF=0.0961061779911
DIFF=0.0960975949222
DIFF=0.0960886542255

// ok, further down…
DIFF=0.232780874127
DIFF=0.232772767895
DIFF=0.232756436223

// and take a look at THIS interesting section ..
DIFF=2.25679475173
DIFF=2.25677114829
DIFF=2.2567289482
DIFF=2.17196494445

DIFF=1.80040103301
DIFF=1.10465389594
DIFF=0.114454568475
DIFF=0.114441693871
DIFF=0.114434064477

So what’s going on here? What’s happening, especially in the very last block where the round-trip time varies from 2.35 seconds to 0.11 seconds is the PRIMARY REASON why I wouldn’t recommend to use TCP for games, EVER.

Its because of the BUFFERING. You know that when you call .send() on a TCP socket, TCP WILL NOT NECESSARILY DELIVER THE MESSAGE IMMEDIATELY! TCP has a buffer BOTH at the sender (messages might pile up for a number of seconds before actually being fired off across the net) __AND__ at the recipient (messages might stock up for a number of seconds before the remote user’s TCP subsystem alerts HIM that you have sent some bytes). This is precisely what makes TCP so inappropriate for use for games: it might withhold the data from you, even if its already at your machine, as you can see here, for up to 2 seconds (or more!).

In the context of a fast paced game, this will give a stupid 2 second lag in game play (likely the game will freeze up for the player, as if he had temporarily disconnected.. depending on how you programmed it of course) which really is not good.

The TCP system is basically like having customs at the airport. Before you can travel, you have to pass through customs, and after you arrive, you also have to pass through customs. You might be held up at customs (the outgoing buffer) for very short (“anything to declare? no? good!”) or you might be there for hours (seconds). You then get into the same plane as the UDP packets, travel across the internet, and when you arrive at the remote host, you as a TCP message must go through customs AGAIN (while the UDP packet simply runs off into the crowd). UDP packets don’t have customs (buffering). But TCP packets do. And because of the customs (buffering) there’s this UNPREDICTABLE, UNCONTROLLABLE (just like customs!!) extra wait that makes TCP totally unsuitable for games.

UDP, as you can see from the results listed above (0.03s, 0.03s…), CONSISTENTLY delivers the messages in 30ms .. UDP is completely stateless and connectionless – you fire off a message, and away across the net it goes. UDP has no sense of buffers or any of the heavyweight stuff that TCP employs. When you use UDP to send messages across the internet, the only delay that will be encountered as the messages goes across the web is because of congestion on the web itself. A UDP message WILL NOT be held up in some buffer EITHER on the local machine from which you send it, or at the remote host that receives it.

Often when people build games, you see them building a TCP-like system (with message acknowledgement and re-sending in case the message doesn’t arrive), but you might wonder WHY they bother to you see people using UDP if they need message acknowledgement. Well, the reason is simple. More CONTROL. UDP doesn’t have that annoying buffer! When you implement “TCP in UDP”, you are in complete control and can achieve the same reliability you get with TCP using UDP. And its worth it.

Conclusions: On Windows it SEEMS that TCP “gets lazy” after about 10 seconds of using it. When a program is sending thousands of really small (8-byte, in this case) messages, the TCP implementation in Windows XP really starts to buffer the packets up and you start to see big honking 1024k messages being transmitted, which ultimately translates to ADDITIONAL DELAY for your game.

So, this is the PRIMARY REASON that TCP isn’t suitable for games. Its not that “TCP is slower” in any absolute sense – actual transmission speeds between TCP and UDP are pretty much the same across the same segment of the ‘net. WHAT IS different is that TCP MAY WITHHOLD THE DATA FROM YOU for longer than you might like in its buffers. And that (the buffering) is what makes TCP unsuitable for games. You can’t control the buffering of TCP – its a FEATURE, not a bug/problem.

The scripts used are below. You launch the server script on your server, then you run the client script and tell it whether you want (U)DP test to run (type U) or the TCP test to run (T).

The UDP test takes about 100 seconds to run, because there is a 0.01s pause between the .send for each of the 10000 messages (something about the UDP buffer overflowing and getting MASSIVE packet loss if you try and send UDP packets too rapidly).

See also Topics in High-Performance Messaging, by Robert A. Van Valzah. It has some very interesting notes on reasons for UDP packet loss, and a section on UDP buffering.

SERVER SCRIPT

Run on the server you are using. It launches BOTH a UDP listener AND a TCP listener (on separate threads), so you can run either test by running this single server script.

#SERVER SCRIPT
#Python 2.5
from socket import *
from select import select
from struct import *
from time import *

import thread

import sys

TCPServer = socket( AF_INET, SOCK_STREAM )
TCPPort = 10007
TCPDone = False

UDPServer = socket( AF_INET, SOCK_DGRAM )
UDPPort = 10008
UDPDone = False

""" UDP server startup """
def UDPServerStart():

  global UDPDone

  try :
    # just bind UDP socket
    UDPServer.bind( ( '', UDPPort ) )
    print '\nUDP socket bound successfully on port %d' % UDPPort

  except :
    #only get here if something bad happened in try block above
    print "\nServer couldn't startup! Reason:",sys.exc_info()
    UDPServer.close()
    sys.exit()  # bail if failed

  while( UDPDone is False ):

    try :
      ( buf, senderAddr ) = UDPServer.recvfrom( 1024 )
      #print 'I got something'

    except :
      print '\nudp: could not recvfrom'
      break

    # now just return that message to the sender
    UDPServer.sendto( buf, senderAddr )

    # we are done when the message is a 0
    if( buf[ 0 ] == 0 ):
      UDPDone = True

  #end while

  print '\nShutting down the UDP server'
  UDPServer.close()

""" TCP Server startup """
def TCPServerStart():

  global TCPDone

  try :
    #bind
    TCPServer.bind( ( '', TCPPort ) )
    print '\nTCP socket bound on port %d' % TCPPort

    #listen
    print '\nTCP socket is listening'
    TCPServer.listen( 5 )

    #Accept
    (sock,senderAddr) = TCPServer.accept()
    print '\nTCP socket has accepted connection',senderAddr

  except :
    #only get here if something bad happened in try block above
    print "Server couldn't startup! Reason:",sys.exc_info()
    TCPServer.close()
    sys.exit()  # bail if failed

  # now
  TCPDone = False

  while( TCPDone is False ):

    try :
      buf = sock.recv( 1024 )
    except:
      print '\nproblem in tcp receive'
      TCPDone = True
      break #will drop us out of the loop

    # now just return that message to the sender
    sock.send( buf )
    ##print 'Got',buf

    # we are done when the message is a 0
    if( len(buf) == 0 or buf[ 0 ] == 0 ):
      TCPDone = True

  # end while

  print '\nshutting down the connected socket'
  sock.close()

  print '\nShutting down the TCP server'
  TCPServer.close()

def Unstick():

  udpunsticker = socket( AF_INET, SOCK_DGRAM )
  udpunsticker.sendto( '', ( '127.0.0.1', UDPPort ) )
  udpunsticker.close()

  # unstick sticky socket
  tcpunsticker = socket( AF_INET, SOCK_STREAM )

  # connect to MAINSOCKET to basically unstick (unblock) it
  tcpunsticker.connect( ('127.0.0.1', TCPPort) )

  tcpunsticker.close()

# end def Unstick

def main():

  global TCPDone
  global UDPDone

  # Start up 2 threads, one for the TCP server, and one
  # for the UDP server.

  # thread.start_new_thread( RunGame, ( player1sock, player2sock ) )
  thread.start_new_thread( TCPServerStart, () )
  thread.start_new_thread( UDPServerStart, () )

  inputs = raw_input("Press any key to shut down")

  TCPDone = True
  UDPDone = True

  Unstick()

main()

CLIENT SCRIPT

Launch after already having launched SERVER SCRIPT on your server

#Python 2.5
from socket import *
from select import select
from struct import *
from time import *

import thread
import sys

class Packet :

  def __init__( self, ID ) :
    self.ID = ID
    self.constructionTime = clock()

  def packMe( self ) :
    packed = pack( 'ff', self.ID, self.constructionTime )
    return packed

  def unpackMe( self, data ) :
    unpacked = unpack( 'ff', data )
    return unpacked

  def getDataAsTuple( self ):
    return ( self.ID, self.constructionTime )

LocalIPAddress = '127.0.0.1'
RemoteIPAddress = '127.0.0.1'  # CHANGE TO YOUR REMOTE SERVER ADDRESS
TCPSocket = socket( AF_INET, SOCK_STREAM )
TCPPort = 10007

UDPSocket = socket( AF_INET, SOCK_DGRAM )
UDPLocalPort = 10006
UDPRemotePort = 10008
Done = False

cumDiff = 0
cumMsgs = 0

StartTime = clock()

SaveOver = ''

TotalReceivedMessages = 0

def TCPTest():

  global cumDiff
  global cumMsgs
  global SaveOver
  global TotalReceivedMessages

  def TCPListener() :

    global cumDiff
    global SaveOver
    global TotalReceivedMessages

    output = open( "tcplisteneroutput.txt", "w" )
    output.write( 'Listener start'+ '\n'  )

    while( Done is False ) :

      try :
        data = TCPSocket.recv( 1024 )
        datalen = len(data)
        output.write( "Now I got "+str(data)+" which is "+str(datalen)+" bytes."+ '\n'  )

      except :
        output.write( 'I couldnt recv '+str(sys.exc_info())+ '\n'  )

      # This is some packet we already sent
      # and its being echo'd back to us here

      # what time is it NOW?
      timeNow = clock()

      # the difference is how long it took to transport
      # there and BACK
      packet = Packet( 1 )

      # Now, if there IS something saved over from last time, prepend
      # those elements to the array.
      if len( SaveOver ) is not 0 :
        # prepend those leftovers

        data = SaveOver + data

      # now compute if there's any
      # left over on THIS iteration
      overChop = datalen % 8

      # save over
      lastGood = datalen - overChop
      SaveOver = data[lastGood:]

      try :

        output.write( "Processing " + str( datalen-overChop ) + "\n" )

        for i in range( 0, datalen - overChop, 8 ) :
          unpacked = packet.unpackMe( data[i:i+8] )
          diff = timeNow - unpacked[1]
          output.write( "DIFF="+str(diff)+ '\n'  )
          cumDiff += diff
          TotalReceivedMessages += 1

      except :
        output.write( 'problems unpacking'+str( sys.exc_info())+ '\n'  )

    output.close()

  f = open( "tcpTest.txt", "w" )

  # connect to the TCP server and rapidly
  # fire off messages.  the server will send
  # the messages back to you, so you can measure
  # round-trip time
  f.write( "TCP test begin"+ '\n'  )

  try :
    # connect to the server
    addr = ( RemoteIPAddress, TCPPort )
    TCPSocket.connect( addr )
    f.write( 'TCPSocket connected to '+str(addr)+ '\n'  )

  except :
    #only get here if something bad happened in try block above
    f.write( "Server couldn't startup! Reason: " + str(sys.exc_info())+ '\n'  )
    TCPSocket.close()
    sys.exit()  # bail if failed

  # start up the listener thread
  thread.start_new_thread( TCPListener, () )

  ### TCP TEST
  for i in range( 1, 10000 ) :

    f.write( 'sending packet '+str(i)+ '\n'  )
    packet = Packet( i )

    # serialize and send that packet, also saving it
    # so we can know when it came back.
    data = packet.packMe()

    try :
      TCPSocket.send( data )
      cumMsgs += 1
    except :
      f.write( 'data send failed!' + str(sys.exc_info() )+ '\n'  )

  #Done = True
  sleep( 2 )

  # done now, so print the average.
  avg = cumDiff / TotalReceivedMessages

  endStr = "cumDiff="+str(cumDiff) + \
    " TotalReceivedMessages="+str(TotalReceivedMessages)+ \
    ' The TCP average transport time was '+str(avg)

  f.write( endStr + '\n' )
  print endStr

  f.close()

  return #/TCPTest

def UDPTest():
  print "UDP test begin"

  global cumDiff
  global cumMsgs
  global TotalReceivedMessages

  def UDPListener() :

    global cumDiff
    global TotalReceivedMessages

    output = open( "udplisteneroutput.txt", "w" )
    output.write( 'UDP listener start'+ '\n'  )

    while( Done is False ) :

      try :
        ( data, senderAddr ) = UDPSocket.recvfrom( 1024 )
        output.write( "Now I got "+str(data)+" which is "+str(len(data))+" bytes, from "+str(senderAddr)+ '\n' )

      except :
        output.write( 'I couldnt recv'+str( sys.exc_info() )+ '\n' )

      # This is some packet we already sent
      # and its being echo'd back to us here

      # what time is it NOW?
      timeNow = clock()

      # the difference is how long it took to transport
      # there and BACK
      packet = Packet( 1 )

      try :
        # all packets from UDP will always be the same length.

        unpacked = packet.unpackMe( data[0:8] )
        diff = timeNow - unpacked[1]
        output.write( "DIFF="+str(diff) + '\n')
        cumDiff += diff
        TotalReceivedMessages += 1

      except :
        output.write( 'problems unpacking '+str( sys.exc_info() )+ '\n' )

  # connect to the TCP server and rapidly
  # fire off messages.  the server will send
  # the messages back to you, so you can measure
  # round-trip time
  f = open( "udpTest.txt", "w" )

  f.write( "UDP test begin"+ '\n' )

  try :
    # bind this UDP socket.. because we want to be
    # able to receive on it.  we still could if
    # we didn't bind, but it would be a random port
    # and the ports are usually all closed.

    addr = ( '', UDPLocalPort )
    UDPSocket.bind( addr )
    f.write( 'UDPSocket BOUND to '+str(addr)+ '\n' )

  except :
    #only get here if something bad happened in try block above
    f.write( "Server couldn't startup! Reason: "+str(sys.exc_info())+ '\n' )
    UDPSocket.close()
    sys.exit()  # bail if failed

  # start up the listener thread
  thread.start_new_thread( UDPListener, () )

  ### UDP TEST
  for i in range( 1, 10000 ) :

    f.write( 'sending packet '+str(i)+ '\n' )
    packet = Packet( i )

    # serialize and send that packet, also saving it
    # so we can know when it came back.
    data = packet.packMe()

    try :
      UDPSocket.sendto( data, ( RemoteIPAddress, UDPRemotePort ) )

      print 'Sending',data
      sleep( 0.01 )   # if you send packets too rapidly
      # you will get severe packet loss (possibly due to
      # UDP buffer overflow at the remote host

      cumMsgs += 1
    except :
      f.write( 'data send failed! '+str( sys.exc_info() )+ '\n' )

  #Done = True
  sleep( 5 )
  # done now, so print the average.
  avg = cumDiff / TotalReceivedMessages

  endStr = "cumDiff="+str(cumDiff) + \
    " TotalReceivedMessages="+str(TotalReceivedMessages)+ \
    ' The UDP average transport time was '+str(avg)

  print( endStr + '\n' )
  f.write( endStr + '\n' )

  return #/TCPTest

def UnstickTCP():
  # unstick sticky socket
  tcpunsticker = socket( AF_INET, SOCK_STREAM )

  # connect to MAINSOCKET to basically unstick (unblock) it
  tcpunsticker.connect( ('127.0.0.1', TCPPort) )

  tcpunsticker.close()

def UnstickUDP():

  udpunsticker = socket( AF_INET, SOCK_DGRAM )
  udpunsticker.sendto( '', ( '127.0.0.1', UDPPort ) )
  udpunsticker.close()

# end def Unstick

# rapidly send out
def main():

  inputs = raw_input("(T)CP or (U)DP?")

  if( inputs.startswith( 'T' ) ) :
    TCPTest()
    Done = True

  elif( inputs.startswith( 'U' ) ) :
    UDPTest()
    Done = True

main()
raw_input("Press enter to continue . . .")

. . . IN A CRUMMY EDITOR!!

Sometimes we forget how SHITTY a dev experience can get when you’re using a crummy code editor.

I have a huge habit of using CTRL+SHIFT together to select “one word at a time”

For instance copy this code into IDLE

x = 'IDLE exhibits "shitty"' \
' behavior'

Now in IDLE, start at the ‘x’, hold down CTRL and press RIGHT. It jumps STRAIGHT to the I in IDLE. Now hold shift down as well. While holding CTRL+SHIFT, press right 3 times, noting what gets highlighted with each step. See how on the third press, it highlights THE WHOLE DADGAM LINE? This makes me furious.

I’d recommend Pydev for eclipse. SO much better. Its really great.

From google cache

 pythonhacker  pythonhacker is offline
Junior Member

Join Date: Feb 2007
Posts: 11
Default Re: Does Python have static methods ? If not what is the equivalent ?
Python does not have many of the frills and bits that languages like C++ and Java add to OOP.
For example, Python does not have access specifiers like public, protected & private. All member
functions and data are public by default. Privateness can be enforced by certain Pythonic tricks
such as prefixing private attributes with a '__' (double underscore) etc.

In a similar fashion, Python does not have static data members. Any data member defined at the
class level defaults to static in Python. Also since Python has no support for qualifiers (since it is
a dynamic language) it is not easy to support such syntax.

However Python does have support for static functions though they are not exactly the same as
those in C++ or Java. In Python a static function is nothing but a function that is unbounded i.e
it does not define the explicit "self" as the first argument. It also needs to be converted to a static
method by using the "staticmethod" typing for functions. This can be done by an explicit cast
after the function definition or by using a decorator (Python 2.4 & later).

Example...

# Before Python 2.4
class C(object):

def func():
print 'Hi, I am a function!'

func = staticmethod(func)

# Python 2.4 or later
class C(object):

@staticmethod
def func()
print 'Hi, I am a function!'

This can be called on the class or on an instance similar to C++ or Java.

>>> C.func()
'Hi, I am a function!'
>>> c = C()
>>> c.func()
'Hi, I am a function!'

Just like C++ or Java, a static function can only access static attributes, not non-static ones.

Example...
>>> class C(object):
... X = 100
... @staticmethod
... def func():
... print 'Hi I am a function'
... print C.X
... # Try calling a non-static member
... self.func2()
... def func2(self):
... print 'This is function number 2!'

>> c= C()
>>> c.func()
Hi I am a function
100
Traceback (most recent call last):
File "", line 1, in ?
File "", line 8, in func
NameError: global name 'self' is not defined

This is because all instance functions have to define 'self' as an explicit first parameter. This is not
there for static functions.

A point to note is that if you try to convert an instance function to a static member function using
@staticmethod, Python silently allows you to do it. But the function is "lost", i.e it becomes uncallable
from either the instance level or class level because the interpreter gets confused.

Example...
>>> class C(object):
... @staticmethod
... def func(self):
... print 'Hi I am a function!'
...
...
>>> c=C()
>>> c.func()
Traceback (most recent call last):
File "", line 1, in ?
TypeError: func() takes exactly 1 argument (0 given)
>>> C.func()
Traceback (most recent call last):
File "", line 1, in ?
TypeError: func() takes exactly 1 argument (0 given)

This is because, staticmethod conversion is normally done for methods which do not define
the explicit 'self' parameter. When you did the conversion, the interpreter wraps up the original
function in a method wrapper which removes the 'self' from the list of arguments. However the
original function still has 'self' as the first argument. The method wrapper does not pass it.
The error comes out of it.

So be careful when writing static member functions in Python

I’m just wondering.


class Grunt :
  """ Defines a Grunt """
  hp = 650
  attackDamage = 21

  def attack( self, enemy ) :
    print 'Time for killing the %s'%enemy
    return self.attackDamage

  def kill( memememe, myENEMY ) :
    print '%s killing = %s'%(memememe, myENEMY)

print 'Testing classes'
g = Grunt()

dmg = g.attack( 'ogre' )

print 'The grunt did %d damage'%(dmg)

g.kill( 'Centaur' )

It seems so dumb to make the programmer pass “self” into every single member function he defines. Sure, you can rename it apparently

Now that I look at it longer, perhaps this guy has a point.

But still.

its just

test = “hello there”
test[0:5] # gives you characters 0 TO 5 of the string test

You know, Google sucks sometimes.

When doing just a plain old search for “digital audio recorder” the shit floats to the top and the good stuff just isn’t to be seen.

I mean, there are a shitload of really crappy ones at this nextag search result that Google pointed me to at first.

It was only through word of mouth that I heard about the Roland Edirol R-1.

So, I guess the message is, consult all major “sound” companies and see what sound products they create with your needs. Call companies if you have to. Google searching isn’t the end all response (“there aren’t any”).

This is what I use

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

public class Game1 : Microsoft.Xna.Framework.Game
{
  GraphicsDeviceManager graphics;
  SpriteBatch spriteBatch;

  public Game1()
  {
    graphics = new GraphicsDeviceManager( this );
    Content.RootDirectory = "Content";

    this.IsMouseVisible = true ;
  }

  protected override void LoadContent()
  {
    spriteBatch = new SpriteBatch( GraphicsDevice );

  }

  protected override void Update( GameTime gameTime )
  {
    // Allows the game to exit
    if( Keyboard.GetState().IsKeyDown( Keys.Escape ) )
      this.Exit();

    base.Update( gameTime );
  }

  protected override void Draw( GameTime gameTime )
  {
    GraphicsDevice.Clear( Color.CornflowerBlue );

    base.Draw( gameTime );
  }
}

ALSO, I wrap BasicEffect in something I call SimpleEffect. Its also less annoying when you’re just trying to get prims on the screen quick.


public class SimpleEffect : BasicEffect
{
  public SimpleEffect( GraphicsDevice gpu, EffectPool ep )
    : base( gpu, ep )
  {

  }

  public new void Begin()
  {
    base.Begin();

    this.CurrentTechnique.Passes[ 0 ].Begin();
  }

  public new void End()
  {
    this.CurrentTechnique.Passes[ 0 ].End();

    base.End();
  }

}

I’m watching through Mad About You now, and I’m on season 2, episode 20.

I’m so thoroughly disappointed and frustrated with the characters. Well, moreso the relationship between the actors. Something happened, starting from season 2 episode 15 – Virtual Reality. Its hilarious. I laughed out loud quite a few times that episode, hardest at the end.

“I was wrong.”

But that episode is the last good one before things go really downhill for this season.

Its not the writing. Its the actors and how they’re acting. They’re ruining it for me.

Paul acts like he hates his wife. They don’t seem to get along together at all. Yet they go through the motions of the “romantic” stuff that’s part of the script.

The fight scenes are .. disturbing. There’s real anger coming out there, it seems as if everyone’s against Paul.

It seems Paul is a dick.

It seems .. I don’t know. After watching these past few episodes, I started to feel this show is a lie.

They should change the title of this show from Mad About you to just Mad At You.

They’re not mad about each other. All the romance is completely gone and they seem to do nothing but get on each others nerves.

This show _should_ tank after this season, but something good must happen because apparently it doesn’t.

HLSL starter shader

A little background. I find the shader that gets filled in automatically when you .Add new Effect.fx file in XNA 3.0 a little annoying.

For starters, its too long and has too many silly comments that mean nothing to someone who doesn’t know what they’re doing, and are redundant and useless to someone who knows what they’re doing. So the first thing I do is strip them out.

Next, I don’t like/approve of the use of STRUCTS in a shader. Its annoying and bulks up the code. Observe what I mean below. Instead of structs and return values, I’m attaching keyword out to the output parameters. This works perfectly well and doesn’t have any problems or difference from using structs – only it appears cleaner – to me.

float4x4 World;
float4x4 View;
float4x4 Projection;

void VertexShaderFunction(

  float4 Position : POSITION0,
  float4 Color : COLOR0,

  // Outputs (feed directly into the PixelShaderFunction)
  out float4 oPosition : POSITION0,
  out float4 oColor : COLOR0
)
{
  // See http://http.developer.nvidia.com/CgTutorial/cg_tutorial_chapter04.html

  // Take vertex to world space
  float4 worldPosition = mul( Position, World );

  // Take vertex to eye-space
  float4 viewPosition  = mul( worldPosition, View );

  // Take vertex to clip-space
  oPosition            = mul( viewPosition, Projection );

  // Simply pass through the color.  If we were using lighting,
  // the color would be affected by the light.
  oColor = Color ;
}

void PixelShaderFunction(

  float4 Color : COLOR0,

  out float4 oColor : COLOR0

)
{
  // just pass through the color as calculated
  // by the vertex shader
  oColor = Color ;
}

technique Technique1
{
  pass Pass1
  {
    VertexShader = compile vs_3_0 VertexShaderFunction();
    PixelShader = compile ps_3_0 PixelShaderFunction();
  }
}

on the qwerty keyboard, you type the following words with the left hand only (more being added all the time!)

words that can be pluralized (e.g. fad and fads) are only included once in the singular (fad only).

see this article also, and this colemak site

bastard

ear
east
eat
ed

daft
deft
dart
dare
dastard

face
fad
fart
fast
fat
fear
fed
feed
fees
fez

gaffer
gas
gat
gear

rasta
recede
receded
red
regressed

sac
sad
sax
saw
seed
sex
swear
sweat
sweet
street

were
waste

right hand

hull
hum

ion

kin
kim

lip

nip
nippy

yuk
yup

WELL! That was a fun day-and-a-half.

I had a project that wasn’t working and I kept working on it for 15 minutes and leaving it for 8 hours, working on it and then leaving it again. It was a really frustrating problem stream 0 size is too small when I was trying to DrawIndexedPrimitives.

Well, now I got it.

DrawIndexedPrimitivesworks as follows:

graphicsDevice.DrawIndexedPrimitives(

  PrimitiveType.TriangleList,  // the prim type to draw

  0,
  0,

  vertexCount, // THIS is the thing
  // that I screwed up.  I kept putting INDEXCOUNT here, which is
  // WRONG.  This is the base number of vertices you will VISIT
  // in this draw call.  If 4 vertices are used to draw 4 triangles
  // (as in a tet), then this number will be 4, NOT 12.

  0,

  indexCount / 3  // now THIS is the number of primitives that
  // you will end up drawing.  So HERE you take into account
  // the number of tris you are drawing.  If drawing a tet, then
  // this number would be 4.

);

See Shawn Hargreaves hair-follicle-saving example (but its still complex, mind you) about instanced models

Drawing using the INDEX BUFFER in XNA

BEFORE READING, this post explains vertex buffers and how you download vertices to the GPU using .SetData in greater detail

#region using...
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
#endregion

public class Game1 : Microsoft.Xna.Framework.Game
{
  GraphicsDeviceManager graphics;

  ////
  // To draw INDEXED primitives, we'll need 4 basic objects:
  //   1.  A BasicEffect.  Used to DRAW.
  //   2.  A VertexBuffer.  Used to STORE ALL THE VERTICES of
  //        the object we wish to draw.
  //   3.  A VertexDeclaration.  Explains to the GPU what PROPERTIES
  //        each vertex has.  In this example, each vertex will
  //        simply have a POSITION in space, and a COLOR.  Could
  //        also have had texture coordinates, but we're not using those here.
  //   4.  An INDEX BUFFER:  Explains to the GPU what
  //       ORDER the vertices in the VertexBuffer should be visited.
  //       That is what the INDEX BUFFER is for.

  //       Imagine you are a kid again going trick or treating.
  //       This is your neighbourhood:

  //     ^       ^       ^        ^        ^
  //    |_|     |_|     |_|      |_|      |_|
  //    100     102     104      106      108
  //
  //
  //
  //    101     103     105      107      109
  //     ^       ^       ^        ^        ^
  //    |_|     |_|     |_|      |_|      |_|

  // Before leaving your house, you look at this map
  // of houses and you identify the houses you know
  // NEVER have candy.  You mark the ones that
  // DO with an X.

  //     ^       ^       ^        ^        ^
  //    |X|     |_|     |X|      |_|      |X|
  //    100     102     104      106      108
  //
  //
  //
  //    101     103     105      107      109
  //     ^       ^       ^        ^        ^
  //    |_|     |X|     |_|      |X|      |_|

  // OK, so you want to tell everyone in the
  // neighbourhood what order your are visiting
  // these houses.

  // The thing is, each of these houses has
  // real space coordinates right?

  // Vertex space coordinates of the center
  // of each home:

  // House 100:  ( 10, 40, 5 )
  // House 101:  ( 20, 40, 30 )
  // House 102:  ( 30, 40, 5 )
  // House 103:  ( 40, 40, 30 )
  // House 104:  ( 50, 40, 5 )
  // .. and so on ..

  // So you could EITHER tell everyone the
  // physical location (coordinates) of each
  // house you plan to visit:

  // I am visiting:
  // ( 10, 40, 5 ), ( 40, 40, 30 ) ...

  //     ^       ^       ^        ^        ^
  //    |X|     |_|     |X|      |_|      |X|
  //    100     102     104      106      108
  //       \            /  \             /
  //         \        /       \        /
  //            \  /             \  /
  //    101     103     105      107      109
  //     ^       ^       ^        ^        ^
  //    |_|     |X|     |_|      |X|      |_|
  //  

  // Or you could simply list the INDICES
  // ("house numbers") of the homes you
  // would like to hit.

  // Which would be:
  // 100, 103, 104, 107, 108

  // The house numbers are kind of like
  // indices ("indexes").

  // Does that kind of make sense?

  ////////////////////////
  // Lets talk more about this.

  // Now say you're crazy and you're going to fire
  // eggs at each of the houses who are participating
  // in Halloween this year using your patented
  // egg-launcher.

  // So, you have two options to pass the data
  // about the coordinates of the homes to hit
  // for your egg launcher.

  // You could:
  // 1.  Feed the egg launcher the coordinates of
  //      the homes to hit with eggs directly (looks like
  //      ( 20, 40, 30 )... etc)

  // OR 2.  Pass the egg launcher TWO arrays:
  // The array of "positions of each home" (akin to
  // a "vertex array"), and THEN, SEPARATELY, pass it
  // an array of "homes to hit, by index", (INDEX BUFFER).

  // The INDEX BUFFER basically lists the houses to HIT
  // by index, and the machine would know
  // to LOOK UP the physical coordinates of the
  // homes to hit FROM the "positions of each home" array
  // (the vertex buffer).

  // VERTEX BUFFER:
  // Positions of each home, stored in an array:
  // +---------------+----------------+---------------+
  // | ( 10, 40, 5 ) | ( 20, 40, 30 ) | ( 30, 40, 5 ) |
  // +---------------+----------------+---------------+
  //       100              101              102

  // INDEX BUFFER
  // Homes to hit (also stored in an array):
  // +-----+-----+
  // | 101 | 103 |
  // +-----+-----+
  //  

  // As you work through the INDEX BUFFER, firing
  // eggs at each home listed there,
  // to know the physical coordinates of a house
  // at fire time, you simply look it up in the
  // "VERTEX BUFFER",
  // which is that "positions of each home" array.

  // So, when drawing graphics, the VERTEX BUFFER
  // is a list of all the vertices that make up the model.
  // The INDEX BUFFER is the visitation order that the
  // GPU should use to "weave" triangle.

  // So you notice immediately that the INDEX BUFFER
  // way has a really great advantage.  Say you really
  // hate Mr. Smithers and you want his home hit (home 104) with
  // 2 eggs in a row.  Instead of passing the machine
  // data with repeated vertices like this:

  //  ( 20, 40, 30 ), ( 40, 40, 30 ), ( 50, 40, 5 ), ( 50, 40, 5 )

  // Your index buffer could look like this:
  //
  // +-----+-----+-----+-----+
  // | 101 | 103 | 104 | 104 |
  // +-----+-----+-----+-----+

  // So that's a bit more compact notation for
  // when a certain vertex is visited more than once
  // (which happens QUITE often when drawing a model!)

  // Include the fact that each vertex in D3D gets passed with
  // texture coordinates (2 floats) AND normals (3 floats),
  // and its easy to see where the savings comes in.

  ///////////////////////////
  // OK, last thing, then I'll get to the code, I promise.
  // The other thing that this is like is PEGS ON A KNITTING LOOM.
  // If you've seen one of those things, it has these pegs that
  // you weave the yarn about over and over again.  A loom might
  // have 15-20 pegs or so

  // 

  /*
            3 4 5
          2 * * * 6
        1 *       * 7
        *           *
        1 *       *
        3 1 * * * 8
          2 1 1 9
            1 0

    My sweet sweet knitting loom
    with sweet numbered pegs

  */

  // So to knit a sock or glove or something,
  // you might visit pegs in the following order:
  // 4, 10, 5, 11, 6, 12, 7, 13.. 

  // In this example, the actual PHYSICAL PEGS are
  // the VERTEX BUFFER (the pegs have
  // actual physical space coordinates don't they?)

  // The "winding order" or the order that I want you
  // to spin the yarn about the pegs, is NOT specified
  // by physical space coordinates (I'm not giving you the
  // physical distance to travel the yarn from peg 4 to peg 10,
  // I'm not saying "start at 4 cm horizontally from the top (4, 0, 0)
  // and connect with (4, -4, 0)).

  // Same goes for drawing using an index buffer.
  // INSTEAD of directly specifying physical Vertex positions
  // in space while drawing, we specify vertex positions
  // ONCE and store them off in a VERTEX BUFFER.

  // We THEN AFTER THAT create a SECOND array called
  // the INDEX BUFFER which specifies the ORDER TO
  // VISIT THE VERTICES THAT ARE ALREADY STORED IN
  // (and numbered off!) in that VERTEX BUFFER.

  // Each VERTEX actually has a position in space.
  // So we store the vertices as this array:

  // pointList ARRAY:
  //
  // +-----------------+-----------------+-----------------+
  // |   ( 1, 1, 1 )   |   ( 2, 5, 9 )   |   ( 8, 5, 7 )   |
  // +-----------------+-----------------+-----------------+
  //          0                 1                 2

  // This forms the VERTEX BUFFER.
  // (Each triplet in the array represents a vector)

  // So, to DRAW A TRIANGLE, between the points I'd specify
  // 0, 2, 1 in the INDEX BUFFER.

  // INDEX BUFFER ibData:
  //
  // +-------+-------+-------+
  // |   0   |   2   |   1   |
  // +-------+-------+-------+
  //     0       1       2

  // When the GPU goes to draw that
  // it puts the two together (the INDEX BUFFER values, which
  // reference the VERTEX BUFFER values) and so it would draw
  // a triangle between (1,1,1), (8,5,7), (2,5,9), winding it
  // in that EXACT order.

  //
  ////

  // Vars for rotating the tetrahedron when you run the program.
  float rot ;
  Vector3 axis ;

  BasicEffect renderer;

  VertexBuffer vb;
  VertexPositionColor[] pointList ;

  VertexDeclaration vd;

  IndexBuffer ib ;
  short[] ibData ;

  public Game1()
  {
    graphics = new GraphicsDeviceManager( this );
    Content.RootDirectory = "Content";

    this.IsMouseVisible = true ;

    axis = new Vector3( random( 0, 1 ), random( 0, 1 ), random( 0, 1 ) );
    axis.Normalize();
  }

  protected override void LoadContent()
  {
    /////
    // Initialization.
    // This is a really long set of steps we need to do
    // to load vertex data INTO THE GPU.

    // "preload" the GPU up with all the vertices
    // you want it to draw.

    // 1.  Initialize the renderer as a BasicEffect:
    renderer = new BasicEffect( GraphicsDevice, null );
    renderer.VertexColorEnabled = true;

    renderer.View = Matrix.CreateLookAt( -10 * Vector3.UnitZ, Vector3.Zero, Vector3.UnitY );
    renderer.Projection = Matrix.CreatePerspectiveFieldOfView( MathHelper.PiOver4, 1.0f, 1.0f, 1000.0f );
    //
    //////

    //////
    // 2.  Next, we will create and set up a bunch of vertices
    // that we can draw.

    // Define the vertices of a tetrahedron and put them in
    // the vertex buffer.
    float edgeLength = 1.0f ;
    float a = edgeLength / (float)( 2.0 * Math.Sqrt( 2.0 ) );

    Vector3 topFront0 = v( a, a, a );
    Vector3 bottomFront1 = v( -a, -a, a );

    Vector3 topBack2 = v( -a, a, -a );
    Vector3 bottomBack3 = v( a, -a, -a );

    pointList = new VertexPositionColor[]
    {

      vpc( topFront0, Color.Black ),

      vpc( bottomFront1, Color.Red ),

      vpc( topBack2, Color.GreenYellow ),

      vpc( bottomBack3, Color.AliceBlue )

    };

    // Load verts onto GPU
    vb = new VertexBuffer(
      GraphicsDevice, VertexPositionColor.SizeInBytes * pointList.Length, BufferUsage.None
    );
    vb.SetData<VertexPositionColor>( pointList );

    // 3.  don't forget the vertex declaration
    vd = new VertexDeclaration(

      GraphicsDevice,
      VertexPositionColor.VertexElements

    );

    // And so there we have the 4 vertices of a tetrahedron.

    // But oh!  A tet has 4 vertices, and 4 FACES!  This means
    // we need to draw _4_ triangles between these 4 vertices.

    // Now normally, you might think, "well, ok, to draw these
    // 4 triangles, we'll just issue 4 triangle-draw calls, and
    // simply REPEAT/overlap a few of those vertex."

    // Nah son.  Repeating vertices?  Nah.

    // Instead, we'll use an INDEX BUFFER.  Refer to the
    // Halloween example above for a quick understanding
    // of what we're doing here.. we're basically going to
    // list out the VISITATION ORDER of the vertices that
    // we already specified above.  So we declare the
    // vertices ONE TIME, in ONE PLACE, and then we
    // say the order that these vertices should be
    // visited at draw time.

    // Sure beats having to specify the same vertex several
    // times over, but it means that each vertex can only have
    // ONE COLOR (so coloration will be less customizable).

    // 4.  Index buffer.  First define the order in which the vertices
    // (of the VERTEX BUFFER!) will be visited

    // How did I work out this visitation order?  Using Wikipedia and a pen and paper!

    ibData = new short[]{

      0, 3, 1,
      0, 1, 2,
      0, 2, 3,
      2, 1, 3

    };

    // Now set them down into the GPU.
    ib = new IndexBuffer( GraphicsDevice, typeof(short), ibData.Length, BufferUsage.None );

    ib.SetData<short>( ibData );

    //end setup
  }

  protected override void Update( GameTime gameTime )
  {
    // Esc. to exit.
    if( Keyboard.GetState().IsKeyDown( Keys.Escape ) )
      this.Exit();

    rot += (float)gameTime.ElapsedGameTime.Ticks / TimeSpan.TicksPerSecond ;
    renderer.World = Matrix.CreateFromAxisAngle( axis, rot ) ;

    base.Update( gameTime );
  }

  protected override void Draw( GameTime gameTime )
  {
    GraphicsDevice.Clear( Color.DarkGray );

    renderer.GraphicsDevice.VertexDeclaration = vd;
    renderer.GraphicsDevice.Indices = ib ;

    renderer.Begin(); // start rendering.

    foreach( EffectPass pass in renderer.CurrentTechnique.Passes )
    {
      pass.Begin();

      // Set the size of the points
      renderer.GraphicsDevice.RenderState.PointSize = 8.0f;

      // Tell the GPU what vertex array to pull vertex data from.
      renderer.GraphicsDevice.Vertices[ 0 ].SetSource( vb, 0, VertexPositionColor.SizeInBytes );

      // Actually draw.
      renderer.GraphicsDevice.DrawIndexedPrimitives(

        PrimitiveType.TriangleList,  // draw Tris, every 3 vertices
        // listed in the INDEX BUFFER are going to produce ONE TRIANGLE
        // on the screen.

        0, // ... start at the beginning of the list ...
        0, // lowest vertex index from VB that can be drawn

        pointList.Length,  // draw as many vertices as are specified by the VERTEX BUFFER (_NOT_ the INDEX buffer).
        // This is very important to get right, and it is a bit counter-intuitive.
        // Say we're drawing a tetrahedron (as we are in this case).  That shape
        // has 4 TRIANGLES drawn between 4 POINTS.. a total of 4 triangles
        // are drawn, so essentially that's 12 vertices that are visited.
        // HOWEVER, the value that gets passed here is __4__, NOT 12.
        // Because we visit 4 vertices, over and over again, to draw
        // the 4 triangles.

        0,
        ibData.Length / 3 // how many total triangles are we drawing?
        // we're hitting 12 vertices, to draw 4 triangles, so we
        // are drawing.. uh, 4 triangles.  DUH! :)

      );

      // end the rendering pass.
      pass.End();
    }

    // Stop rendering.
    renderer.End();

    ////
    base.Draw( gameTime );
  }

  #region aux
  /// <summary>Convenience</summary>
  public static Vector3 v( double x, double y, double z )
  {
    return new Vector3( (float)x, (float)y, (float)z );
  }

  /// <summary>Convenience.  After all, Shakespeare did say
  /// that brevity is the soul of with.  He didn't say anything
  /// about efficiency, however.</summary>
  public static VertexPositionColor vpc( Vector3 p, Color c )
  {
    return new VertexPositionColor( p, c );
  }

  public static Color c( double r, double g, double b )
  {
    return new Color( (float)r, (float)g, (float)b );
  }

  static Random rand = new Random();
  public static float random( float low, float high )
  {
    return MathHelper.Lerp( low, high, (float)rand.NextDouble() ) ;
  }
  #endregion

  static void Main( string[] args )
  {
    Game1 game = new Game1();
    game.Run();
  }
}

This is sad. A couple lost their daughter.

She’s a cute British girl. She was lost in portugal. She was 4. She is now 6.

My feelings are for the couple.

Sorry about your girl. I hope you find her.

As soon as she has access to the Internet, she will be able to contact you.

Something that occurs to me is we should teach our children if they are abducted, to contact THE POLICE anytime, anyhow they can.

Easy to say, but how can you do that thing when you’re a kid, when the kidnappers can say anything they like to the child and the child (being a child) may believe them?

Sometime last week, I discovered Andrew Furmanczyk’s lypur’s “how to play piano” lessons on youtube.

They’re really good!

To prove he can really play (important if you’re learning from him!)

WELL.

I would write about my recent experiences, but that would be a lot of detailed.

I will just summarize my observations:

  1. beautiful women with brains do exist. This is not a myth.
  2. When you see a woman you like, talk to her immediately. DO NOT HESITATE. If you do not do this in a public place, then you’ll lose her in probably 4 seconds. She’ll leave if you make the eye contact then you shy out. In a place where you will have repeated contact, talking to her immediately avoids build up and pain and fear.
  3. Women who stick to their girlfriends and never go anywhere alone do it because they are insecure. If you’re not VERY good/persistent in your approach then you won’t be able to get anything from them. Insecure women are afraid of being rejected, passed over, or ignored. So if you look at them, a few times, and they know you have looked at them, then it quickly goes from interest to threatening to pass over, and they really do not like this, so they will run away. Solution: TALK TO THEM IMMEDIATELY. Express interest by just casual conversation. Oh, and be interesting, or SHE will drop you as uninteresting. Being interesting varies and you really need to equip yourself with things to talk about that you know they can get into.
  4. Don’t get attached. Its so easy to start to think about the girls in the room and put stupid names to them when you don’t know their actual names and get all attached and tied up into a few of them. DON’T.
  5. DO NOT LOOK ANGRY, FRUSTRATED, SCARED. Look like you just smoked a blunt. Really. I have never smoked marijuana in my life, but you need to look relaxed without trying to look relaxed. You have to be actually relaxed. DRop your facial muscles. Talk to anyone.
  6. ALREADY BEING TALKING TO SOMEONE is attractive to the girls. Stupid insecure girls won’t __approach__ two chatting people. Other girls may
  7. Intelligent girls behave differently from stupid girls. Stupid girls hang out in groups of two, and the really insecure ones talk to each other a lot. Even if you try really hard to break in on their conversation, they might respond for a few words, then drop out into conversation with their friend. They are trying to talk to you, they just don’t know how. Its too hard.
  8. WHEN YOU talk to a girl, you must LOCK HER GAZE and make extreme eye contact with her. She interprets looking away or down at the floor or around as DISINTEREST, BOREDOM, A BAD SIGN, YOU ARE UNTRUSTWORTHY, YOU ARE DANGEROUS. A girl has to be able to look into your eyes to communicate with you, and if your eyes FLIT when she looks into them, she sees a criminal and she will avoid you.
  9. When you look into her eyes, you’d be surprised at the extra degree of communication your conversation has acquired, BOTH WAYS. Watch for topics that make her eyes widen with interest, or her pupils dialate with fear. For me, I particularly noticed a bit of concern/this being an “edge” topic when I said something about parenting. I expressed disdain for high school, saying there was too much “parenting” in it. I’m not sure what the fear was, it could have been: “Does he not want children? Is he already a parent?” COuld have been either. Don’t know. Anyway.
  10. Now what you really think is in your face, and she can see it. So, if you don’t find what she’s saying interesting, and you don’t look it, you can’t just fake it with no effort like you could on the phone – your facial expression gives it all away. So she knows if you appear disinterested, she’ll quickly become disinterested as a defense mechanism.

  11. While intelligent girls .. can be a lot like birds. They used to call women birds.. they travel in flocks and they “perch” together. If several beautiful women perch, this is your chance. ENGAGE THEM. EACH. INDIVIDUALLY. OR CHOOSE ONE and capture her interest. If you are boring they will fly away. If you don’t say anything they will talk to each other, again, bad. If they start getting wrapped up in conversation with each other, its probably going to be a lot harder to “break in” (metaphor or pun not intended, and eww). The BEST TIME
  12. Smart women are every bit as driven .. by musculature and bulk, and tight buttocks and being good-looking, they just have an additional FILTER of “NO MEATHEADS”. If you are stupid, that’s fatal.
  13. COME PREPARED. BRING a “device” you can use as an excuse to exchange contact information, like an interesting website that you can totally describe whose URL you just can’t remember (offer her she can google search the keywords, or tell her, you know what, I’ll just send it to you. What’s your email address? if she likes you, she will not refuse. If she doesn’t like you, then this gives her an easy out to let you know that pretty clearly by saying she’ll just google search the keywords.)

In C++, you can serialize your data so easily by simply reading raw bytes of a struct or variable (cast base address of any variable to (unsigned char*) and you can see that variable as its underlying set of bytes that it is.)

But in C#, that ain’t so.

So in C#, you have two options when it comes to seeing the true colors of your variables.


using System;
using System.Runtime.Serialization ;
using System.IO;

public class TestBinaryOutputProgram
{
  static void Main()
  {
    // Using the BitConverter to get raw bytes of
    // any PRIMITIVE (doesn't work on a class or a struct
    // directly - would have to do member by member manually).

    float floatVar = 7.0f;
    byte[] fBytes = BitConverter.GetBytes( floatVar ) ;

    for( int i = 0; i < fBytes.Length; i++ )
    {
      Console.WriteLine( "Byte["+i+"] = "+fBytes[i] ) ;
    }

    // using a MemoryStream
    // (or some other stream object)
    // and a BinaryWriter

    MemoryStream memstream = new MemoryStream();
    BinaryWriter bw = new BinaryWriter( memstream ) ;

    // write in the var
    bw.Write( floatVar ) ; // converts to binary automatically
    byte[] memBytes = memstream.ToArray() ;

    for( int i = 0; i < memBytes.Length; i++ )
    {
      Console.WriteLine( "memBytes[" + i + "] = " + memBytes[ i ] );
    }

  }
}

well, i was a caffeine junkie for years.

then i quit. two weeks ago.

yes, i DO feel that I am somewhat.. less capable. Caffeine does something to your brain that makes it work faster. So i’m without that – naturally a bit mentally slower than I “usually” am (perpetual caffeine high).

BUT I get more work done. You know why? Because time at the computer isn’t any longer this frenetic, frenzied rush from code to website to distraction to code to website to distraction. My brain isn’t going off like that anymore – I don’t feel as distractable.

So, I AM more productive. And guess what? When I do take a mild cup of tea or two, it has a much stronger effect than the strongest coffee used to give me. It makes me feel faster, and gives me this quick boost and slight euphoria, and some focus. Because I take it when I need to focus.

I know I just said that being on caffeine all the time made time at the computer frenzied, and it does, when I’m not sure what I’m doing. But when I have a set purpose and task I must accomplish and I gulp some caffeine down to help, it does help, as long as I keep fixated on my goal.

it sucks.
mfc sucks

debugview. open it and it intercepts debug messages from system and shows them to you. very useful when debugging direct3d apps.

winspector

screen-full

MAN. How frustrating.

I spent the last 2 hours over this

Problem: I created a new virtual machine. VMWare WON’T BOOT FROM CD!! It keeps on trying to do a network boot

SOLUTION

HACK OPEN the .vmx file for your virtual machine (open in any text editor)


ide0:1.present = “TRUE”
ide0:1.fileName = “d:”
ide0:1.deviceType = “cdrom-raw”
ide0:1.autodetect = “FALSE”