Skip navigation

Monthly Archives: July 2009

There is an easy solution for this, if you just installed HL2, you have to LAUNCH THE GAME AND LET IT UPDATE before trying to launch the Hammer map editor.

Windows 7 has this security feature that makes some of your old software stop working.

Every vendor has to “register” a software driver to make one work.

Start > All Programs > Accessories > Right click on command prompt > Run as administrator

bcdedit /set loadoptions DDISABLE_INTEGRITY_CHECKS

REBOOT, and that’s it! “Windows requires a digitally signed driver???” No he doesn’t!

Try this page out.

Remove the <!doctype> declaration at the top of the page to see quirks mode in action.


<!doctype html>
<html>
<head>
<style>
ul
{
  list-style-type: none;
}

li
{
  /*
    ie old rules width referred to 
    the combination of borders,
    padding, AND what's inside the element.
    
    standards say WIDTH EXCLUDES PADDING, borders.
  */
  margin: 20px ;
  padding: 20px 40px;
  width: 250px;
  border: solid 2px black;
  background-color: #eee;
}
</style>
</head>

<body>
  <ul>
    <li>Digger</li>
    <li>Styx</li>
    <li>Heroes of might and magic</li>
    <li>world of warcraft</li>
  </ul>
</body>
</html>

this picture says it all..

So, I rarely use my live account, but now when I try to, it crashes firefox 3.0.11.

Not cool Microsoft. Not cool.

There has been a tendency for Microsoft to not support other browsers. I think they need to realize that this actually hurts them more than it compels users to open up IE and use that browser.

this page has a note about how to do an MSI dump (and a great DirectX book too!)

msiexec /a %MSI%

The VARIANT datatype is the worst, most error prone piece of shit i’ve ever seen.

look at this bug:


  for( int s = 0 ; s < count ; s++ )
  {
    _variant_t vi( s ) ;

    ADOField * field ;

    if( CHECK( fields->get_Item( vi, &field ), "Getting field item" ) )
    {
      BSTR name ;

      CHECK( field->get_Name( &name ), "getting name" ) ;

      wprintf( L"| %10s |", name );
    }

  }


Why did it crash? I’ll paste the correct non-crashing code below and see if you can find it



  for( short s = 0 ; s < count ; s++ )
  {
    _variant_t vi( s ) ;

    ADOField * field ;

    if( CHECK( fields->get_Item( vi, &field ), "Getting field item" ) )
    {
      BSTR name ;

      CHECK( field->get_Name( &name ), "getting name" ) ;

      wprintf( L"| %10s |", name );
    }

  }


See it? When I declared the counter variable s as an int, the variant type was the wrong type (it was an INT type instead of a SHORT type).

I only GUESSED this was the problem not from the amazing documentation that ms keeps on this, but from this article looking at how they browsed the thing.

I was shocked and amazed that the VARIANT type was ever in use by anyone at any point in time, and how EXTENSIVELY its used in ADO.

I mean, its an ugly type and this is a STUPID reason for a bug to exist.

i’m sick of these broken links to old microsoft articles.

i can’t understand WHY they remove their KB articles.

this has happened to me on more than one occassion. There is no need to DELETE kb articles, ever.

microsoft’s attitude towards the web needs to change.

OK, here it is.

Pure torture.


#define _CRT_SECURE_NO_DEPRECATE

// Before running this program, make sure you have a
// mysql32 dsn set up to connect to the 'test' database.

// Run these queries:
/*
create table users( id int, name varchar( 255 ) );

insert into users( id, name ) values ( 1, 'bob' ), ( 2, 'john' ) ;

select * from users ;
*/







#include <windows.h>
#include <stdio.h>
#include <stddef.h>     // for offsetof()
#include <cguid.h>

#include <oledb.h>
#include <oledberr.h> 
#include <msdaguid.h>
#include <msdasql.h>

#include <comdef.h>     // for _com_error()

#include <vector>
using namespace std ;


#define FIELD_NAME_LEN 255

struct User
{
  int id ;
  
  // Because the field is a varchar(255), we
  // represent that here as a char array with
  // 255 bytes maximum.
  char name[ FIELD_NAME_LEN ] ;

  User()
  {
    id = 1 ;
    strcpy( name, "unnamed user" ) ;
  }

  User( int i_id, char * i_name )
  {
    id = i_id ;
    strcpy( name, i_name ) ;
  }
} ;











///
/// Dump an error to the console,
/// including any information we can
/// get from the system about
/// the specific error.
///
void DumpError( HRESULT hr )
{
  printf( "HRESULT: %d\n", hr ) ;

  _com_error err( hr ) ;
  BSTR bstr = err.Description() ;
  printf( "Description: %s\n", bstr );
  wprintf( L"_com_error.ErrorMessage(): %s\n", err.ErrorMessage()  ) ;

  IErrorInfo * errorInfo ;
  GetErrorInfo( 0, &errorInfo );
  if( errorInfo )
  {
    BSTR description;
    errorInfo->GetDescription( & description );

    // description will be a more descriptive error message than just formatting the 
    // HRESULT because it is set by the COM server code at the point of the error

    wprintf( L"\nIErrorInfo says:  %s\n", description ) ;
  }

  printf("\n");
}



/// Its very important to CHECK ALL return codes.
/// Its a real ass-biter when something goes wrong
/// and the notification is hidden because you
/// didn't check the HRESULT of every command.
bool CHECK( HRESULT hr, char * msg, bool printSucceededMsg=false, bool quit=true )
{
  if( SUCCEEDED( hr ) )
  {
    if( printSucceededMsg )  printf( "%s succeeded\n", msg ) ;

    return true ;
  }
  else
  {
    printf( "%s has FAILED!!\n", msg ) ;

    DumpError( hr ) ;

    if( quit )  FatalAppExitA( 0, msg ) ;

    return false ;
  }
}




/// Gets you an ICommandText interface to
/// the database connected to in db.
/// ICommandText's let you send SQL queries
/// to the database.
ICommandText * GetCommand( IDBInitialize * dbInit )
{
  #pragma region talk about QueryInterface
  // QueryInterface is a funky method.

  // Basically you use it to "ask" the COM object you
  // are working with here WHETHER OR NOT IT SUPPORTS
  // ("implements") a specific interface.

  // To quote an excellent MSDN article:
  // "If an object supports an interface, it supports
  // all of the methods within that interface."
  //    http://msdn.microsoft.com/en-us/library/ms810892.aspx

  // If you're curious, take a look at the
  // "sampprov" project that comes with
  // the Windows SDK sample set
  // C:\Program Files\Microsoft SDKs\Windows\v6.1\Samples\dataaccess\oledb\sampprov

  // Therein, an implementation of the QueryInterface
  // method lies:

  /*
STDMETHODIMP CCommand::QueryInterface
(
	REFIID riid,				//@parm IN | Interface ID of the interface being queried for. 
	LPVOID * ppv				//@parm OUT | Pointer to interface that was instantiated      
)
{
	if( ppv == NULL )
		return ResultFromScode(E_INVALIDARG);

	//	This is the non-delegating IUnknown implementation
	if( riid == IID_IAccessor )
		*ppv = (LPVOID)m_pIAccessor;
	else if( riid == IID_ICommand )
		*ppv = (LPVOID)m_pICommandText;
	else if( riid == IID_ICommandText )
		*ppv = (LPVOID)m_pICommandText;
	else if( riid == IID_ICommandProperties )
		*ppv = (LPVOID)m_pICommandProperties;
	else if( riid == IID_IColumnsInfo )
		*ppv = (LPVOID)m_pIColumnsInfo;
	else if( riid == IID_IConvertType )
		*ppv = (LPVOID)m_pIConvertType;
	else if( riid == IID_IUnknown )
		*ppv = (LPVOID)this;
	else
		*ppv = NULL;
}
*/
  // OK Isn't that COOL?  All what happens is,
  // QueryInterface looks to see if "riid"
  // is one of the interface types this object
  // supports.

  // If it DOES support the interface you're
  // asking for, then it just points "ppv" to
  // its local member instance of that class.

  // If the object DOES NOT support the interface
  // you're querying for, then you get a null pointer back.

  // ISN'T THAT SIMPLE?  Its a lot simpler internally
  // than I initially thought.  Basically QueryInterface
  // is a Get_* method, only its very very generic.

  // Nothing is created in a QueryInterface method.
  // You get something that already exists within the
  // object.  QueryInterface lets you simply access it.

  // Also note that as a RULE, once a COM interface
  // is published, YOU CANNOT ADD OR REMOVE METHODS
  // FROM THAT INTERFACE.  Instead, you have to
  // define a NEW interface (hence why DirectX has
  // IDirect3D9, IDirect3D7.. etc.)
  #pragma endregion

  // So now, I ultimately want a COMMAND interface,

  // ICommandText <- IDBCreateCommand <- IDBCreateSession <- IDBInitialize
  // cmdText      <- cmdFactory       <- sessionFactory   <- dbInit
  // In words:
  // 1.  IDBInitialize spawns an IDBCreateSession
  // 2.  That IDBCreateSession is used to create an IDBCreateCommand
  // 3.  That IDBCreateCommand is used to create an ICommandText
  // 4.  The ICommandText is returned

  IDBCreateSession * sessionFactory ;
  HRESULT hr = dbInit->QueryInterface(

    IID_IDBCreateSession,      // I want an IID_IDBCreateSession interface.. which
    // I shall use to MAKE a session.

    (void**)&sessionFactory // and put it into sessionFactory variable.
  
  ) ;
  
  CHECK( hr, "creating session factory" ) ;
  
  

  // Get a command factory out of the session factory
  // We need the command factory to create ICommandText's,
  // ICommandText will hold our SQL queries eventually.
  IDBCreateCommand * cmdFactory ;
  CHECK( sessionFactory->CreateSession( NULL, IID_IDBCreateCommand, (IUnknown**)&cmdFactory ), "CreateSession" ) ;

  // Then throw away the session creator object.
  CHECK( sessionFactory->Release(), "releasing the session factory" ) ;

  // Create the command, saving in cmdText.
  // ICommandText interface contains text of an SQL query, eventually
  ICommandText * cmdText ;
  CHECK( cmdFactory->CreateCommand( NULL, IID_ICommandText, (IUnknown**) &cmdText ), "cmdFactory->CreateCommand()" ) ;
  CHECK( cmdFactory->Release(), "cmdFactory->Release()" ) ;
  

  return cmdText ;
}











///
/// Execute a prepared INSERT statement with parameters.
///
void runInsertWithParameters( IDBInitialize * db ) 
{

  //////////
  // // DBPARAMINFO.
  // This array of structs
  // will tell OLE DB the DATATYPE and NAME of the
  // columns of the table we are running our
  // prepared INSERT statement against.

  vector<DBPARAMBINDINFO> bindInfo ;
  
  // Standard type name | Type indicator table
  // contains "DBTYPE_I4" => DBTYPE_I4 mappings
  // Basically you just quote all of them, except for example
  // "DBTYPE_CHAR" => DBTYPE_STR, and
  // "DBTYPE_VARCHAR" => DBTYPE_STR as well.
  DBPARAMBINDINFO firstColumnBindInfo = { 0 } ;
  firstColumnBindInfo.pwszDataSourceType = OLESTR( "DBTYPE_I4" ) ;  // !!CAN ALSO BE "int"
  firstColumnBindInfo.pwszName = NULL ;   // The name of the __parameter__
  // Most of the time this should be NULL.
  // DO NOT SET THIS to OLESTR( "id" ),
  // or OLESTR( "@id" ), or something like this.
  // MySQL doesn't seem to support named parameters.
  // Named parameters look like this:
  //   insert into tablename (col1, col2) values ( :param1, :param2 )
  // vs UNNAMED parameters:
  //   insert into tablename (col1, col2) values ( ?, ? )
  // We're using UNNAMED parameters here.  Don't
  // mistaken this field for the name of the COLUMN
  // in the table.  Because its not that.  EVEN THOUGH
  // the MSDN example DOES get this wrong.  See this post.
  firstColumnBindInfo.ulParamSize = 4 ;   // size in bytes (obviously 4 bytes for an I4 (int-4) field)
  firstColumnBindInfo.dwFlags = DBPARAMFLAGS_ISINPUT | DBPARAMFLAGS_ISSIGNED  ; // http://msdn.microsoft.com/en-us/library/ms714917(VS.85).aspx
  firstColumnBindInfo.bPrecision = 11 ;  // bPrecision is the maximum number of digits, expressed in base 10
  firstColumnBindInfo.bScale = 0 ;

  bindInfo.push_back( firstColumnBindInfo ) ;


  DBPARAMBINDINFO secondColumnBindInfo = { 0 } ;
  secondColumnBindInfo.pwszDataSourceType = OLESTR( "DBTYPE_VARCHAR" ) ; // !!can also be "varchar(255)"
  //secondColumnBindInfo.pwszName = NULL ;
  secondColumnBindInfo.ulParamSize = FIELD_NAME_LEN ;
  secondColumnBindInfo.dwFlags = DBPARAMFLAGS_ISINPUT  ;
  secondColumnBindInfo.bPrecision = 0 ;
  secondColumnBindInfo.bScale = 0 ;

  bindInfo.push_back( secondColumnBindInfo ) ;



  
  // now, cmdText is the variable we're working with.
  // The command requires the actual text
  // as well as an indicator of its language.
  ICommandText * cmdText = GetCommand( db ) ;
  
  // Set the SQL query that will run.
  CHECK( cmdText->SetCommandText( DBGUID_DBSQL, OLESTR("insert into users ( id, name ) values (?, ?)") ), "SetCommandText" ) ;

  // Now go down into the cmdWithParams and
  // Set its ParameterInfo with the BINDINFO
  // that we just specified above.
  ICommandWithParameters * cmdWithParams ;
  CHECK( cmdText->QueryInterface( IID_ICommandWithParameters, (void**)&cmdWithParams ), "get cmdWithParams" ) ;



  // the ORDER that parameter infomation will come in inside bindInfo
  ULONG ordinals[ 2 ] = { 1, 2 } ;
  CHECK( cmdWithParams->SetParameterInfo( bindInfo.size(), ordinals, &bindInfo[ 0 ] ), "SetParameterInfo" ) ;
  CHECK( cmdWithParams->Release(), "cmdWithParams release" ) ;

  
  

  // Prepare the command.
  // MSDN:  This optional interface encapsulates command optimization,
  // a separation of compile time and run time, as found in traditional
  // relational database systems. The result of this optimization is
  // a command execution plan.
  // http://msdn.microsoft.com/en-us/library/ms713621(VS.85).aspx

  ICommandPrepare * cmdPrepare ;
  CHECK( cmdText->QueryInterface( IID_ICommandPrepare, (void**)&cmdPrepare ), "Get ICommandPrepare interface" ) ;
  CHECK( cmdPrepare->Prepare( 0 ), "Command preparation" ) ;
  CHECK( cmdPrepare->Release(), "ICommandPrepare release" ) ;



  


  // Create parameter accessors.
  #pragma region create parameter accessors
  
  IAccessor * accessor ;
  CHECK( cmdPrepare->QueryInterface( IID_IAccessor, (void**)&accessor ), "Getting IAccessor interface" ) ;

  // DBBINDING
  vector<DBBINDING> bindings ;
  
  DBBINDING firstColumnBinding = { 0 } ;
  firstColumnBinding.iOrdinal = 1 ;
  firstColumnBinding.dwPart = DBPART_VALUE ;
  firstColumnBinding.dwMemOwner = DBMEMOWNER_CLIENTOWNED ;
  firstColumnBinding.eParamIO = DBPARAMIO_INPUT ;
  firstColumnBinding.cbMaxLen = 4 ;
  
  firstColumnBinding.wType = DBTYPE_I4 ;
  firstColumnBinding.obValue = offsetof( User, id ) ;  // get byte offset of id member
  printf( "offset of id field is %d\n", firstColumnBinding.obValue ) ;

  bindings.push_back( firstColumnBinding ) ;

  DBBINDING secondColumnBinding = { 0 } ; 
  secondColumnBinding.iOrdinal = 2 ;
  secondColumnBinding.dwPart = DBPART_VALUE ;
  secondColumnBinding.dwMemOwner = DBMEMOWNER_CLIENTOWNED ;
  secondColumnBinding.eParamIO = DBPARAMIO_INPUT ;
  secondColumnBinding.cbMaxLen = FIELD_NAME_LEN ;
  
  secondColumnBinding.wType = DBTYPE_STR ;
  secondColumnBinding.obValue = offsetof( User, name ); // get byte offset of name member.
  printf( "offset of name field is %d\n", secondColumnBinding.obValue ) ;

  bindings.push_back( secondColumnBinding ) ;

  // used to get information about the validity of our binding attempt
  vector<DBBINDSTATUS> rgStatus ;
  rgStatus.resize( 2 ) ;
  


  // The hAccessor will tie the BINDING information
  // to the actual dataset used.
  HACCESSOR hAccessor ;  
  printf( "%d\n", sizeof( User ) ) ;
  
  HRESULT hr = accessor->CreateAccessor(
    
    DBACCESSOR_PARAMETERDATA,    // Accessor that will be used to specify parameter data
    
    bindings.size(),    // Number of parameters being bound
    
    &bindings[0],       // Structure containing bind information
    
    sizeof( User ), // Size of parameter structure.  This MUST be a FIXED SIZE,
    // so you cannot use a generic char* pointer in User that points to
    // a variable length string (must be predetermined size, as it is
    // char[FIELD_NAME_LEN] in this example.)

    &hAccessor,     // will contain accessor handle after this function call

    &rgStatus[0]        // will contain information about binding validity
    // after this function call is complete
  
  ) ;

  if( !CHECK( hr, "Parameter accessor creation" ) )
  {
    printf( "binding status validity: %d %d (0 means OK)\n", rgStatus[ 0 ], rgStatus[ 1 ] ) ;
    puts(
      "DBBINDSTATUS_OK = 0,\n"
	    "DBBINDSTATUS_BADORDINAL = 1,\n"
	    "DBBINDSTATUS_UNSUPPORTEDCONVERSION = 2,\n"
	    "DBBINDSTATUS_BADBINDINFO = 3,\n"
	    "DBBINDSTATUS_BADSTORAGEFLAGS = 4,\n"
	    "DBBINDSTATUS_NOINTERFACE = 5,\n"
	    "DBBINDSTATUS_MULTIPLESTORAGE = 6\n" ) ;
  }
  
  
  #pragma endregion


  #pragma region create data and insert it.
  // Create the data to insert and put it
  // into a struct.
  vector<User> users ;

  User user1( 55, "bobobo" ) ;
  users.push_back( user1 ) ;

  User user2( 56, "waniel" ) ;
  users.push_back( user2 ) ;

  
  
  // ICommand::Execute page, DBPARAMS is in it
  DBPARAMS dbParams;
  
  // pData is a pointer to an array of
  // data that contains data in the order
  // described by bindInfo.
  dbParams.pData = &users[ 0 ] ;   // the data to insert.
  dbParams.cParamSets = users.size() ;  // Number of sets of parameters
  dbParams.hAccessor = hAccessor ; // Accessor to the parameters.  tells
  // dbParams how the byte array of data
  // in pData is divided up.

  // Execute the command.
  long cRowsAffected ;
  hr = cmdText->Execute( NULL, IID_NULL, &dbParams, &cRowsAffected, NULL ) ;
  
  CHECK( hr, "Execute for the insert statement" ) ;
  printf( "%d rows inserted.\n", cRowsAffected ) ;
  

  CHECK( accessor->ReleaseAccessor( hAccessor, NULL ), "Accessor ReleaseAccessor" ) ;
  CHECK( accessor->Release(), "Release Accessor" ) ;
  CHECK( cmdText->Release(), "Release commandText" ) ;
  #pragma endregion

  
}














///
///  Delete rows just added using simple execution.
///
void myDelete( IDBInitialize*  pIDBInitialize ) 
{
  ICommandText* pICommandText = GetCommand( pIDBInitialize ) ;


  // Set the command text for first delete statement and execute
  // the command
  pICommandText->SetCommandText(
    
    DBGUID_DBSQL,
    OLESTR( "delete from users where id=6" )
    
  ) ;
  
  long cRowsAffected ;
  pICommandText->Execute( NULL, IID_NULL, NULL, &cRowsAffected, NULL ) ;

  printf( "%d rows deleted.\n", cRowsAffected ) ;

  // Do it again.
  pICommandText->SetCommandText(
    
    DBGUID_DBSQL,
    OLESTR( "delete from users where id=7" )
  
  ) ;

  pICommandText->Execute(NULL, IID_NULL, NULL, &cRowsAffected, NULL);

  printf("%d rows deleted.\n", cRowsAffected);

  pICommandText->Release();

  return;
}












void SetBSTRProperty( DBPROP & props, DWORD propertyId, OLECHAR * stringValue )
{
  props.dwPropertyID = propertyId ;
  props.vValue.vt = VT_BSTR ;
  props.vValue.bstrVal = SysAllocString( stringValue ) ;
}




























DBPROP preinitDBPROP()
{
  DBPROP prop ;
  VariantInit( &prop.vValue ) ; // equivalent: prop.vValue.vt = VT_EMPTY ;
  prop.dwOptions = DBPROPOPTIONS_REQUIRED ;
  prop.colid = DB_NULLID ;
  return prop ;
}

int main()
{
  // Init OLE and set up the DLLs.
  CoInitialize( NULL ) ;



  // We start with the IDBInitialize interface.
  // The purpose of IDBInitialize is to Initializes a data source object
  IDBInitialize * db = NULL;
  
  

  // Get the task memory allocator.
  // At this point, the original example creates
  // an IMalloc interface.
  // IMalloc can be used to allocate and manage memory.  It doesn't seem to be used in this
  // example, but I'm leaving it here for now.
  IMalloc * iMalloc = NULL;
  CHECK( CoGetMalloc( MEMCTX_TASK, &iMalloc ), "GetMalloc" ) ;
  




  #pragma region Initialize the data source
  
  // Create an instance of the MSDASQL (ODBC) provider.
  // ODBC is for connecting to an sql-based data source
  CHECK( CoCreateInstance( CLSID_MSDASQL, NULL, CLSCTX_INPROC_SERVER, IID_IDBInitialize, (void**)&db), "starting db" ) ;

  #pragma region talk about variants
  // Set properties for this connection.
  // Declaring the properties for establishing
  // a connection to the database.

  // VARIANT PROPERTY SET.
  // Now HERE is a weird structure you don't see every day.
  // The VARIANT.

  // You might think this data structure is weird.
  // That's because it is.

  // A VARIANT encapsulates ALL the primitive types
  // that are possible in a database.  Look at its
  // struct definition in the header file or on msdn if you wish.
  
  // Notice how it has inside it like EVERY CONCEIVABLE
  // datatype:  DATE*, SHORT*, BYTE*, and even IUnknown.

  // It also has a property VARTYPE.  VARTYPE is set to
  // one of the values in the VARENUM enumeration.
  // So, using a VARIANT as an argument is a way to ANY
  // data type, specifying WHAT TYPE this VARIANT ACTUALLY
  // represents (i.e. what type its internal byte data
  // is to be interpretted as.).

  // MSDN about the vt field:  Contains the type code for the variant,
  //                           which governs how the variant is interpreted.
  #pragma endregion
  
  
  // Initialize common property options.

  // You "have to" call VariantInit() before
  // passing a variant to a function.  What VariantInit does is
  // simply set the vt field to VT_EMPTY.
  
  vector<DBPROP> props ;
  
  // Level of prompting that will be done
  // to complete the connection process.
  DBPROP initPrompt = preinitDBPROP() ;

  initPrompt.dwPropertyID = DBPROP_INIT_PROMPT ;
  initPrompt.vValue.vt = VT_I2 ;      // 2 byte integer (short).
  initPrompt.vValue.iVal = DBPROMPT_NOPROMPT ; 
  
  props.push_back( initPrompt ) ;
  


  
  // Data source name-- using the same one we set up
  // in the ODBC example https://bobobobo.wordpress.com/2009/07/11/working-with-odbc-from-c/
  DBPROP dsn = preinitDBPROP() ;
  SetBSTRProperty( dsn, DBPROP_INIT_DATASOURCE, OLESTR( "mysql32" ) ) ;
  //SetBSTRProperty( dsn, DBPROP_INIT_DATASOURCE, OLESTR( "sqlserver" ) ) ;
  props.push_back( dsn ) ;

  DBPROP username = preinitDBPROP() ;
  SetBSTRProperty( username, DBPROP_AUTH_USERID, OLESTR( "root" ) ) ;   // User ID
  props.push_back( username ) ;

  DBPROP pass = preinitDBPROP() ;
  SetBSTRProperty( pass, DBPROP_AUTH_PASSWORD, OLESTR( "" ) ) ; // Password
  props.push_back( pass ) ;
  


  // Set up the propSet, and
  // link it to the DBPROP array
  // we just created above.
  DBPROPSET propSet ;

  // Now this is an initialization property set.
  propSet.guidPropertySet = DBPROPSET_DBINIT ;

  // tell it the # of properties specified
  propSet.cProperties = props.size() ;

  // And now we assign our properties structure
  propSet.rgProperties = &props[ 0 ] ;

  // Retrieve the IDBProperties interface.
  IDBProperties * dbProperties ;
  db->QueryInterface( IID_IDBProperties, (void**)&dbProperties );
  CHECK( dbProperties->SetProperties( 1, &propSet ), "Set properties" ) ;

  #pragma region free and unload
  // Free the BSTRs that were allocated using SysAllocString()
  SysFreeString( dsn.vValue.bstrVal ) ;
  SysFreeString( username.vValue.bstrVal ) ;
  SysFreeString( pass.vValue.bstrVal ) ;

  CHECK( dbProperties->Release(), "dbprops release" ) ;
  #pragma endregion




  #pragma endregion


  // Now, after we have set the properties, fire up the database by initalizing it
  CHECK( db->Initialize(), "db->Initialize" ) ;
  




  // now set up for batch insertion
  // I want to batch insert.  In order for 
  // Sets of multiple parameters
  // (cParamSets is greater than one) can be specified only if
  // DBPROP_MULTIPLEPARAMSETS is VARIANT_TRUE

  // Note that we CANNOT set this property inline with
  // the previous batch of property state settings because
  // DBPROP_MULTIPLEPARAMSETS belongs to the DBPROPSET_DATASOURCEINFO,
  // and NOT the DBPROPSET_DBINIT set.
  props.clear();

  DBPROP multipleParamsets = preinitDBPROP() ;
  
  multipleParamsets.dwPropertyID = DBPROP_MULTIPLEPARAMSETS ;
  multipleParamsets.vValue.vt = VT_BOOL ;
  multipleParamsets.vValue.boolVal = VARIANT_TRUE ;
  
  props.push_back( multipleParamsets ) ;



  // reset the propset and reuse it
  // Now this is "Data Source Information" property set,
  // which supports setting the DBPROP_MULTIPLEPARAMSETS item
  propSet.guidPropertySet = DBPROPSET_DATASOURCEINFO ;

  // tell it the # of properties specified
  propSet.cProperties = props.size() ;

  // And now we assign our properties structure
  propSet.rgProperties = &props[ 0 ] ;





  // re-get the dbProperties interface.
  db->QueryInterface( IID_IDBProperties, (void**)&dbProperties );
  CHECK( dbProperties->SetProperties( 1, &propSet ), "Set properties 2" ) ;





  CHECK( dbProperties->Release(), "dbprops release 2" ) ;

















  // Execute a prepared statement with parameters.
  runInsertWithParameters( db ) ;
  





  // Delete rows just added.
  myDelete( db ) ;



  
  if( db != NULL )
  {
    db->Uninitialize() ;
    db->Release() ;
  }

  if( iMalloc != NULL )
    iMalloc->Release() ;

  CoUninitialize() ;

  return 0 ;
}









// Glossary:  (Extracted from http://msdn.microsoft.com/en-us/library/ms810892.aspx
// DATA PROVIDER:  A data provider is one that owns data and exposes it in a tabular form.
// Some examples are relational database systems and spreadsheets.

// SERVICE PROVIDER:  A service provider is any OLE DB component
// that does not own the data but encapsulates some service by
// producing and consuming data through OLE DB interfaces.
// Examples are query processors and transaction managers.

// BSTR:  http://msdn.microsoft.com/en-us/library/ms221069.aspx

// The BSTR is a strange animal.  It is like a Pascal string
// in that its LENGTH is stored in the first (4) bytes.
// The character data itself then follows, then there are
// TWO null terminators at the end, regardless of whether
// _UNICODE is #defined or not.

// You're supposed to create BSTR's with SysAllocString()
// and to delete them with SysFreeString().






// Important links and pages.

// ADO faq:  http://support.microsoft.com/kb/183606

// Listing of ALL OLE DB Interfaces (objects that start with I):
// http://msdn.microsoft.com/en-us/library/ms709709(VS.85).aspx

// Listing of ALL OF THE OLE DB Structures And Enumerated Types with LINKS to each
// http://msdn.microsoft.com/en-us/library/ms716934(VS.85).aspx

// Listing of ALL OLE DB PROPERTIES
// http://msdn.microsoft.com/en-us/library/ms723066(VS.85).aspx

// Data type mappings:  maps VARIANT types to OLE DB data types
// (e.g. BOOLEAN => DBTYPE_BOOL)
// http://msdn.microsoft.com/en-us/library/bb231286(VS.85).aspx


// PROPERTIES BY PROPERTY GROUPS:  This is the page that tells
// you which DBPROP_* fits under what DBPROPSET_*
// http://msdn.microsoft.com/en-us/library/ms714404(VS.85).aspx

// Fixed-Length and Variable-Length Data Types
// http://msdn.microsoft.com/en-us/library/ms715955(VS.85).aspx

Download code from esnips (thanks esnips!)

While the OLE DB for the ODBC Programmer article is excellent, there is a mistake in it.

The rgParamBindInfo array should not have names for the parameters (they should be NULL) because the prepared statement doesn’t use named parameters (they are unnamed (?,?,?,?)’s)

Because the author does not check the HRESULTS that come back from his SetParameterInfo() invokation, he doesn’t know about this error. But if you check this line:

pICmdWithParams->SetParameterInfo(nParams, rgParamOrdinals, 
        rgParamBindInfo);

with

if( FAILED( pICmdWithParams->SetParameterInfo(nParams, rgParamOrdinals, 
        rgParamBindInfo) )
{
  puts( "The 1997 article by Michael Pizzo, Jeff Cochran has a mistake in it" ) ;
}

you find it throws an error because rgParamBindInfo is wrong (it should look like this:)


  DBPARAMBINDINFO     rgParamBindInfo[] = 
        {
        OLESTR("DBTYPE_CHAR"),  0 /* OLESTR("CustomerID")*/,    5, 
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("CompanyName")*/,  40, 
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("ContactName") */,  30, 
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("ContactTitle") */, 30, 
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("Address") */,      60, 
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("City") */,         15, 
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("Region") */,       15, 
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("PostalCode") */,   10, 
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("Country") */,      15, 
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("Phone") */,        24, 
             DBPARAMFLAGS_ISINPUT, 0, 0,
        OLESTR("DBTYPE_VARCHAR"), 0 /* OLESTR("FAX") */,          24, 
             DBPARAMFLAGS_ISINPUT, 0, 0,
        };

Because the prepared statement looks like this:

  WCHAR               wSQLString[] = 
    OLESTR("insert into Customers (CustomerID, CompanyName, ContactName,")
    OLESTR(" ContactTitle, Address, City, Region, PostalCode, Country,")
    OLESTR(" Phone, Fax)")
    OLESTR(" values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

If the prepared statement used named parameters, it would look something like this:

  WCHAR               wSQLString[] = 
    OLESTR("insert into Customers (CustomerID, CompanyName, ContactName,")
    OLESTR(" ContactTitle, Address, City, Region, PostalCode, Country,")
    OLESTR(" Phone, Fax)")
    OLESTR(" values (:CustomerID, :CompanyName, :ContactName, ")
    OLESTR(" :ContactTitle, :Address, :City, :Region, :PostalCode, :Country, ")
    OLESTR(" :Phone, :Fax)");

That’s why the docs also say The name of the parameter; it is a null pointer if there is no name. Names are normal names. The colon prefix (where used within SQL text) is stripped.

See I wasn’t aware of offsetof.

Its really good.

Its defined as:

#define offsetof(s,m)   (size_t)&reinterpret_cast<const volatile char&>(((s *)0)->m)

So when you do:

offsetof( STRUCT_TYPE, MEMBER_NAME )

You really get:

(size_t)&(char&)(((STRUCT_TYPE *)0)->MEMBER_NAME)

So its pretty neat. Basically what happens is, you get the number of bytes that MEMBER_NAME is from the beginning of the struct. .. refers to the address of member m in this object. Since the start address of this object is 0 (NULL), the address of member m is exactly the offset.

PRETTY cool. I can’t believe I’ve been listing numerical byte counts for this long..

and the hand of experience.

If you try and compile and run the microsoft sdk sampClnt using their instructions they leave out one important detail:

running sampclnt.exe
Sun Jul 12 11:22:41 2009


Connecting to the SampProv sample data provider...
Error at file: c:\program files\microsoft sdks\windows\v6.1\samples\dataaccess\oledb\sampclnt\sampclnt.cpp  line: 317  
CoCreateInstance: Returned <unknown>
Error at file: c:\program files\microsoft sdks\windows\v6.1\samples\dataaccess\oledb\sampclnt\sampclnt.cpp  line: 206  
GetSampprovDataSource: Returned <unknown>
Error at file: c:\program files\microsoft sdks\windows\v6.1\samples\dataaccess\oledb\sampclnt\sampclnt.cpp  line: 122  
DoTests: Returned <unknown>

so the fix for this is to first compile the sampprov project, then switch into C:\Program Files\Microsoft SDKs\Windows\v6.1\Samples\dataaccess\oledb\sampprov\Debug, (like, open a command prompt..)

cd C:\Program Files\Microsoft SDKs\Windows\v6.1\Samples\dataaccess\oledb\sampprov\Debug
regsvr32 sampprov.dll

THEN you can run the sampclnt example, making sure to put the .csv file it uses in the same directory as its executable.

I only knew this from a hint from this post, where he says

Hi, what is the problem with the OLEDB sample client, obtained from Data
Acess SDK 2.8?
I registered the sample provider as regsvr32 \sampprov, which was
successful.

Here is the log:

running sampclnt.exe
Thu Jun 23 12:44:52 2005

Connecting to the SampProv sample data provider…
Getting a DBSession object from the data source object…
Getting a rowset object from the DBSession object…
Error at file: c:\msdn\sample\sampclnt\sampclnt.cpp line: 517
IOpenRowset::OpenRowset: Returned DB_E_NOTABLE
Error at file: c:\msdn\sample\sampclnt\sampclnt.cpp line: 224
GetRowsetFromDBCreateSession: Returned DB_E_NOTABLE
Error at file: c:\msdn\sample\sampclnt\sampclnt.cpp line: 119
DoTests: Returned DB_E_NOTABLE

WHAT IS WITH Microsoft and just CHANGING Things.

They recently changed their hashing scheme on SkyDrive so that links were rewritten. I’m SO glad I’ve been using esnips and NOT skydrive (i’m not even linking there.. who knows, it may change) for anything on here.

They changed it so the URLs get COMPLETELY rewritten. The URL went from:

http://n61ofw.blu.livefilestore.com/y1pXBOTt7tQ5TePwcrFto_lrQ_qD5D_RZiP9TZpOINsRJ7omqZLzyVPG5osK3Zk73AIIV9-hicdVOEyB6WtNpJCaw/myfile.txt
http://n61ofw.blu.livefilestore.com/y1pMRpZHLOl6gwTmcXcdqiVu1DnwOdXF5XNM9rJfD4PCBXdCK35hNK5qeZzb-SV91Sn6odVUj_97CXE18b8VFiwBw/myfile.txt

The lower url is the new one.

CAN YOU BELIEVE THEY DID THAT? I can’t. They just broke.. well over a MILLION links on the web if they did this to everybody. I can’t BELIEVE they did that. It sends me reeling. I’d NEVER use SkyDRive now, knowing that this is something they MIGHT just arbitrarily decide to do in the future.

Setting up MySQL for use through ODBC.

First, recognize that THERE ARE several ways you can connect to a MySQL database from an application.

MDAC


click for larger

The 3 main ways are:

  • Native C api – compile and link-in code that can talk to MySQL WITHIN your app. This is ALMOST like making MySQL “part of your program”

  • ODBC (this article). ODBC stands for Ol’ Dirty Bastard Connector.. :) Just kidding. But it should. ODBC was first released in 1992. ODBC is short for Open Database Connectivity.

    Basically your application TALKS TO the ODBC driver THROUGH A COMMON SET OF API FUNCTIONS – the ODBC API library. The ODBC driver in turn, talks to the actual database for you. So you achieve a certain level of database API independence: you use ODBC in the same way whether programming to a MySQL database, or an MS-SQL Server database, or an Oracle database – you use the same functions and it works, as long as you have an ODBC driver for that database. So using ODBC is just ONE LEVEL of abstraction above the native C API. ODBC is still alive and kicking today and works fine.

    Aside:

    If you’re familiar with how the HAL works in Direct3D, ODBC is a little bit like the HAL.

    Direct3D function calls ODBC function calls
    HAL (hardware abstraction layer) ODBC driver
    GPU hardware itself Database software itself

    In this case, the “database” is like the GPU, and ODBC driver is that layer which transforms standard ODBC function calls into function calls that the actual database being used underneath can understand.

    If that just didn’t make any sense, ignore this whole block

    The advantage of using ODBC above the MySQL functions directly is .. well, just that you don’t have to program to the MySQL function set directly anymore. So, say you already had experience with setting up a database connection under C++/Oracle, and you want to quickly get up and running on a C++/MySQL program. Instead of going and figuring out how the MySQL native api works, you actually wouldn’t have to know any of that at all, you’d just install the ODBC driver and program “to” ODBC – this is what we’ll show how to do in this article.

  • OLE DB

    Just ANOTHER, newer, more recent library of functions that is supposed to replace ODBC. OLE DB is a low-level, high-performance interface to a variety of data stores. OLE DB, like ODBC as shown in this article, has a C-style API.

    OLE DB’s advantage over ODBC is that the underlying data provider when using OLE DB does NOT have to be a relational database.

    In fact, according to page 8 of this book

    ODBC as we have just seen, is an excellent technology for accessing SQL-based data. OLE DB incorporates this proven technology with a particular component that allows OLE DB consumers to communicate directly with ODBC providers. In other words, use OLE DB to access SQL-based data, and you gain the advantage of being able to access both relational and other forms of data with the same code.

    So it looks like this:

  • Finally, ADO, (also, ADO.NET).

    ADO is a high-level, easy-to-use interface to OLE DB.

    ADO is the NEWEST and is probably the most commonly used technology for accessing databases from MS apps. Ever heard of hibernate? Well, ADO, (which stands for ActiveX Data Objects) is BASICALLY the same idea as Hibernate. You can interact with the database through a series of functions WITHOUT EVER WRITING A LINE OF SQL. You interact with the database instead through the functionset provided by ADO.

    Can you see the layers? You can see that you should expect ADO to be somewhat slower than using ODBC directly.

    ADO is accessible in two flavors: ADO “regular” and ADO.NET. ADO.NET, clearly, is part of the .NET framework and so if you’re using a .NET application, then data access through ADO.NET is the natural standard for you.

    If you’re programming a native C++ app on the other hand, the choice whether to use native MySQL function calls, ODBC, OLE DB (directly), ADO, or ADO.NET kind of looms before you.

So, ok, on with it.

Accessing a MySQL database through ODBC

1. The first step is to install a MySQL database and create a table or two. Do it do it do it!!

2. Ok, now the SECOND step is to GET THE MySQL ODBC 5.1 DRIVER. GET THE 32-BIT DRIVER ONLY, PLEASE, EVEN IF YOU ARE ON A 64-bit MACHINE. Unless you know EXACTLY what you’re doing FOR SURE and you KNOW your compiler pushes out 64-bit applications (Visual Studio 2005/2008 pushes out 32-bit applications by default ONLY!! EVEN IF you are on a 64-bit platform!)

3. Once you’ve got that installed, OPEN UP Start -> Administrative Tools -> Data Sources (ODBC).

Note: If you DO NOT SEE “Administrative Tools” on your start menu RIGHT CLICK TASKBAR > PROPERTIES > START MENU TAB > CUSTOMIZE > FIND AND SELECT THE “DISPLAY ADMINISTRATIVE TOOLS” checkbox.

4. Ok, now in the Ol’ Dirty Bastard Connections window (ODBC Window) that you just opened in step 3, select the System DSN tab

IMPORTANT NOTE: IF YOU ARE ON A 64-BIT MACHINE, __DO NOT__, I REPEAT, __DO NOT__ USE THE ODBC Window that is accessible from the taskbar. Instead, go to START > RUN > C:\Windows\SysWOW64\odbcad32.exe.

The reason is when developing in Visual Studio 2005/2008, under normal circumstances you in fact cannot publish 64-bit applications, so you CANNOT USE the 64-bit ODBC drivers from your 32-bit application. So you must set up and use the __32-bit__ ODBC drivers instead. This is a REAL assbiter. See jlgdeveloper’s master-genius answer at http://forums.devarticles.com/microsoft-sql-server-5/data-source-name-not-found-and-no-default-driver-specified-8346.html#postmenu_203344 (repeated at bottom of this page for permanence)

5. Click ADD. You see a menu

IF YOU DO NOT SEE “MySQL ODBC 5.1 DRIVER” there, CALL 911. Or, try installing the correct version of the ODBC driver.

6. Now, pick the ODBC 5.1 item and click “FINISH” (you’re not done yet though..)

7. Fill out the connection params. This is how I filled out mine.

When you’re done click TEST. You should see the box that I see “Connection successful”

If you see this box

CALL 911, or double check your parameters and make sure your MySQL daemon is running.

8. Now that you’re done that, you should see this:

REMEMBER THAT NAME, “mysqldata” or whatever name you gave the connection in the top box. This is the name you’ll refer to from your program.

9. Now run this program. Once again I remind you IF YOU ARE ON A 64-BIT MACHINE, BE SURE TO HAVE SET UP YOUR ODBC CONNECTIONS IN THE C:\Windows\SysWOW64\odbcad32.exe WINDOW, AND NOT THE ODBC WINDOW ACCESSIBLE FROM THE START MENU. YOU HAVE BEEN WARNED.


///////////////////////////////////////////
//                                       //
// WORKING WITH OL' DIRTY BASTARD (ODBC) //
//                                       //
// You found this at bobobobo's weblog,  //
// https://bobobobo.wordpress.com         //
//                                       //
// Creation date:  July 10/09            //
// Last modified:  July 10/09            //
//                                       //
///////////////////////////////////////////
// Note also nice sample comes with
// WinSDK in C:\Program Files\Microsoft SDKs\Windows\v6.1\Samples\dataaccess\odbc\odbcsql

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

#include <sql.h>
#include <sqltypes.h>
#include <sqlext.h>

// Here is the complete Ol' Dirty Bastard function reference:
// http://msdn.microsoft.com/en-us/library/ms714562(VS.85).aspx

// This article says you need
// to link with odbc32.lib, but taking the next line of code OUT
// doesn't seem to harm anything
#pragma comment( lib, "odbc32.lib" )

bool CHECK( SQLRETURN rc, char * msg, bool printSucceededMsg=false, bool quit=true )
{
  if( SQL_SUCCEEDED( rc ) )
  {
    if( printSucceededMsg )  printf( "%s succeeded\n", msg ) ;
    
    return true ;
  }
  else
  {
    printf( "NO!!!  %s has FAILED!!\n", msg ) ;
    
    if( quit )  FatalAppExitA( 0, msg ) ;

    return false ;
  }
}

void status( SQLSMALLINT handleType, SQLHANDLE theHandle, int line )
{
  SQLCHAR sqlState[6];
  SQLINTEGER nativeError;
  SQLCHAR msgStr[256];
  SQLSMALLINT overBy ; // the number of characters that msgStr buffer was TOO SHORT..
  
  // http://msdn.microsoft.com/en-us/library/ms716256(VS.85).aspx
  // This must be the WEIRDEST ERROR REPORTING FUNCTION I've EVER seen.
  // It requires 8 parameters, and its actually pretty .. silly
  // about the amount of state information it expects YOU to keep track of.

  // It isn't so much a "GetLastError()" function
  // as it is a "GetMeStatus( something very, very specific )" function.
  
  SQLRETURN retCode ;
  
  for( int i = 1 ; i < 20 ; i++ )
  {
    retCode = SQLGetDiagRecA(
      
      handleType,  // the type of object you're checking the status of
      theHandle,   // handle to the actual object you want the status of
      
      i, // WHICH status message you want.  The "Comments" section at the 
      // bottom of http://msdn.microsoft.com/en-us/library/ms716256(VS.85).aspx
      // seems to explain this part well.

      sqlState,    // OUT:  gives back 5 characters (the HY*** style error code)
      &nativeError,// numerical error number
      msgStr,      // buffer to store the DESCRIPTION OF THE ERROR.
      // This is the MOST important one, I suppose

      255,         // the number of characters in msgStr, so that
      // the function doesn't do a buffer overrun in case it
      // has A LOT to tell you
      &overBy      // again in case the function has A LOT to tell you,
      // the 255 character size buffer we passed might not be large
      // enough to hold the entire error message.  If that happens
      // the error message will truncate and the 'overBy' variable
      // will have a value > 0 (it will measure number of characters
      // that you 'missed seeing' in the error message).
      
    ) ;

    if( CHECK( retCode, "SQLGetDiagRecA" ) )
    {
      printf( "LINE %d:  [%s][%d] %s\n", line, sqlState, nativeError, msgStr ) ;
    }
    else
    {
      // Stop looping when retCode comes back
      // as a failure, because it means there are
      // no more messages to tell you
      break ;
    }
  }
}

int main()
{
  // Following this example, just adding a bit more
  // color and making it work with our specific example.
  
  
  // 1.  Create a handle for the environment.
  SQLHANDLE hEnv ;
  SQLRETURN retCode ;
  
  retCode = SQLAllocHandle( SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv ) ;
  
  CHECK( retCode, "allocate environment handle" ) ;
  

  // 2.  Next, set the version of ODBC to use to ODBC version 3.
  // Format of this command is a bit weird, we cast the value we're passing
  // to (void*) because the function requires it, but then we say that the
  // length of the "string" we've passed in is 0 characters long, so I assume
  // that means SQLSetEnvAttr should know to interpret the "pointer value" that
  // we passed in as actually an integer value (which is what it is).
  retCode = SQLSetEnvAttr( hEnv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0 ) ; 

  CHECK( retCode, "setting the environment attribute setting to ODBC version 3" ) ;


  // 3.  Allocate the connection handle.  Note this doesn't
  // connect us to the database YET.  We're still "ALLOCATING",
  // whatever that means :) (Hey i know what allocating is,
  // but this is an awful number of steps to follow if you
  // ask me, microsoft!!  Whatever happened to a simple init()
  // function?
  SQLHANDLE hConn ;

  CHECK( SQLAllocHandle( SQL_HANDLE_DBC, hEnv, &hConn ), "allocate handle" ) ;

  
  

  // HOOK IT UP!!  Actually connect to the database.
  SQLCHAR* dsnName = (SQLCHAR*)"mysqldata" ;  // MUST BE THE SAME
  // as the name of the ODBC data source you set
  // in the Microsoft ODBC Administrator window.

  SQLCHAR* userid = (SQLCHAR*)"root";
  SQLCHAR* password = (SQLCHAR*)"";  // using a BLANK
  // Above are my own correct userid and password credentials to
  // be used when logging into the MySQL database server.

  // 4.  Open database connection.
  retCode = SQLConnectA(
    
    hConn,
    
    dsnName,  // name of data source we are connecting to,
    // AS PER REGISTERED IN ODBC Data Source Administrator.

    // If you are on a 64-bit machine, and you
    // DO NOT USE THE 64-bit driver.  As long as
    // your compiler publishes a 32-bit .exe (which
    // Visual Studio does), you'll keep getting:

    // [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

    // SO DON'T USE THE 64-BIT DRIVERS!  Instead, install
    // the 32-bit driver, and then managing/using
    // your 32-bit datasources in
    // c:\windows\syswow64\odbcad32.exe

    // Note that on a 64-bit windows machine, the 32-bit
    // drivers and the 64-bit drivers are managed
    // from COMPLETELY SEPARATE, BUT IDENTICAL-LOOKING
    // windows.  Its really weird.

    // On a 64-bit machine:
    // c:\windows\system32\odbcad32.exe    // 64-bit version [even though it SAYS system32_ in the path, this is the __64__ bit version on a 64-bit machine]
    // c:\windows\syswow64\odbcad32.exe    // 32-bit version [even though it SAYS syswow64_ in the path]

    // Call it stupid, scream, pull your hair out,
    // that's what it is.
    // http://stackoverflow.com/questions/949959/why-do-64bit-dlls-go-to-system32-and-32bit-dlls-to-syswow64-on-64bit-windows

    // and

    // http://blogs.sepago.de/helge/2008/04/20/windows-x64-all-the-same-yet-very-different-part-7/

    // Thanks again, Microsoft,
    // for making the 64-bit programming experience
    // such a pleasure.
    SQL_NTS,  // the DSN name is a NULL TERMINATED STRING, so "count it yourself"

    userid,
    SQL_NTS,  // userid is a null-terminated string
    
    password,
    SQL_NTS   // password is a null terminated string
    
  ) ;
  if( !CHECK( retCode, "SqlConnectA", false ) )
  {
    // if this fails, I want that extra status
    // information about WHY the failure happened.
    // status function is defined above.
    
    status( SQL_HANDLE_DBC, hConn, __LINE__ ) ;
  }


  // 6.  Create and allocate a statement
  SQLHANDLE hStmt ;
  CHECK( SQLAllocHandle( SQL_HANDLE_STMT, hConn, &hStmt ), "allocate handle for statement" ) ;

  
  // 7.  Form a query to run and attach it to the hStmt
  // this basically connects the hStmt up with
  // some results.
  SQLCHAR* query = (SQLCHAR*)"SELECT * from user" ;
  CHECK( SQLExecDirectA( hStmt, query, SQL_NTS ), "execute query" ) ;


  // 8.  Read data results that are now in the hStmt.
  retCode = SQLFetch( hStmt ) ;

  CHECK( retCode, "first sqlFetch" ) ;

  // How many rows got returned?
  SQLLEN numRows ;
  retCode = SQLRowCount( hStmt, &numRows ) ;
  printf( "%d rows were fetched, ruff.\n", numRows ) ;

  // With a query like the one we wrote (SELECT *),
  // we don't know how many columsn should be in
  // the result set at this point.
  // So we ask ODBC to tell us!
  SQLSMALLINT numCols ;
  retCode = SQLNumResultCols( hStmt, &numCols ); // SqlNumResultCols

  // Now print the column names.
  // SQLDescribeCol function
  SQLCHAR colName[ 256 ] ;
  
  SQLSMALLINT colNameLen, dataType, numDecimalDigits, allowsNullValues ;
  SQLUINTEGER columnSize ;

  for( int i = 1 ; i <= numCols ; i++ )
  {
    retCode = SQLDescribeColA( hStmt, i, colName, 255, &colNameLen, &dataType, &columnSize, &numDecimalDigits, &allowsNullValues ) ;
    if( CHECK( retCode, "SQLDescribeCol" ) )
    {
      printf( "Column #%d: '%s', datatype=%d size=%d decimaldigits=%d nullable=%d\n",
                       i,colName,   dataType, columnSize,  numDecimalDigits, allowsNullValues ) ;
    }
  }

  for( int i = 1 ; i <= numRows ; i++ )
  {
    // Datatypes
    // SQLGetData

    char buf[256];
    SQLINTEGER numBytes ;

    for( int j = 1 ;   // column counter starts at __1__, not 0.
      j <= numCols ;   // numCols retrieved above
      j++ )
    {
      retCode = SQLGetData(
      
        hStmt,
        j,           // COLUMN NUMBER of the data to get
        SQL_C_CHAR,  // the data type that you expect to receive
        buf,         // the place to put the data that you expect to receive
        255,         // the size in bytes of buf (-1 for null terminator)
        &numBytes    // size in bytes of data returned
      
      ) ;

      if( CHECK( retCode, "SqlGetData", false ) )
      {
        // Print the data we got.
        printf( "%10s", buf ) ;
      }
    
    } // end for.

    puts("");

    // Try and fetch the next result.
    // fall out of the loop if fetch fails
    // (meaning, no more data to get)
    retCode = SQLFetch( hStmt ) ;
    if( !SQL_SUCCEEDED( retCode ) )
    {
      // SQLFetch FAILS AS IT FETCHES the last row of data.
      printf( "And %d is the LAST row.. we're not getting any more after this one\n", i ) ;
    }
  }

  // So we used a FOR loop above to fetch
  // exactly numRows rows from the results.

  // The other (perhaps more common) 
  // way to do this is to use a loop like
  
  // while( SQL_SUCCEEDED( SQLFetch( hStmt ) ) )
  // {
  //   // Work with result data
  // }

  // When we do it that way, 
  // WE EXPECT/RELY ON SQLFetch TO TELL US
  // IT FAILED when we've reached the
  // LAST row of data.

  // free up resources.
  SQLFreeHandle( SQL_HANDLE_STMT, hStmt ) ;
  SQLFreeHandle( SQL_HANDLE_DBC, hConn ) ;
  SQLFreeHandle( SQL_HANDLE_ENV, hEnv ) ;
}


// Assbiters:
// 1. Be careful not to use the SUCCEEDED() macro
// instead of the SQL_SUCCEEDED() macro when
// checking your SQLRESULT values.
//
// 2. Do not use 64-bit ODBC drivers, even if on
// a 64-bit machine.  See information above.

/*
     ____   __   __      __   __  ___
    / _  \ /  / /  /    /  /  \ \/  /
   / _/ / /  / /  /    /  /    \   /
  / _/ \ /  / /  /__  /  /__   /  /
 /_____//__/ /______//______/ /__/

*/


Master genius John

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

I had this error and want to let you know how it was resolved.

First, this was an ASP web application using a vb 6.0 dll to get data from a sql server 2005 database on a 64 bit windows server 2008 enterprise (vista like) server. I could only get the dll to work in component services as opposed to simply registering it.

It all worked fine upon setup, but after four windows updates one night, the error above was posted in the event viewer, and the web app crashed.

Here is the resolution:

In a 64 bit windows server operating system, there are TWO odbc managers. When you pull up the usual menu for the odbc / dsn system, it is for the 64 bit odbc manager, and 32 bit applications (vb 6.0) will not work using these dsn’s.

This is where the 32 bit odbc manager is:

C:\Windows\SysWOW64\odbcad32.exe

I hope you do not have to go through what I and three Microsoft Support engineers had to to figure this out.

Jonathan

Download the code package courtesy of esnips (thanks esnips!)

Q: How do I do an overloaded constructor in PHP?

A: You don’t need them

Consider the following

class Foo
{
  var $name ;
  function __construct()
  {
    # if the default ctor is invoked, name
    # this instance "unnamed"
    $this->name = 'unnamed' ;
  }

  # Fine and dandy, but what if
  # we want to supply a name
  # in an overloaded ctor?
  
  function __construct( $iname )
  {
    $this->name = $iname ; #doesn't work
    # because overloaded ctors of this style
    # aren't supported in PHP!!
  }
  
}

OK. Well I promised in the title of this post that you didn’t need overloaded constructors in php Here’s why.

Redefine class Foo as follows:


class Foo
{
  var $name ;

  # specify a single ctor, WITH DEFAULT VALUES
  # FOR PARAMETERS.  This is equivalent, and in my
  # opinion a better syntax
  # for getting overloaded constructors to work.
  function __construct( $iname = 'unnamed' )
  {
    $this->name = $iname ;
  }
}

There. Fewer lines of code, less mess, same effect. This was an excellent design decision by the php group.

Refactoring
Rewriting something so that it is written differently, but ultimately “means” the same thing. E.g. in Math, you can refactor x + xy to x( 1 + y ). These two statements (x+xy) and (x(1+y)) mean exactly the same thing mathematically, but they’re just written differently. e.g. 2 in programming, refactor is used more loosely. You can refactor a bunch of code which means you rewrite the code to do the same intended thing, but in a better way (more efficiently, or with more adherence to OOP principles, or rewrite it to remove bugs).

Ok, so say I have:

class Thing abstract
{
  
} ;

class Person : public Thing
{
  void MoveTo( Point p ) ;
} ;

class Building : public Thing
{
  // does NOT have MoveTo( Point p ) ;
} ;

I’m maintaining a vector<Thing*> to keep track of everything in the world.

When hittesting, a user might click on either a Building or a Person. Regardless, there’s a pointer stored to the currently selected Thing* in selectedThing.

Now, depending on what TYPE of thing is currently selected, the user can do different actions with that Thing. If the Thing* is really Person*, then a right-click somewhere on the map means one thing (i.e. move there) or for a building, a right click means (do nothign) or (set rally point).

So, if selectedThing is IN FACT a Person*, then we should call MoveTo() on the selectedThing (method exists!). But if selectedThing is NOT a person, then we should NOT call MoveTo() on it, because MoveTo() is not defined for a Building*.

What’s the best way to manage this problem?

1. typeid() reflection (which is bad because its implementation dependent and just _seems_ wrong?)
i.e. find if typeid() says selectedThing is Person* or Building*

if( typeid( selectedThing ) == classTypePerson ) 
{
  selectedThing->MoveTo( p ) ;
}
else
{
  // its not a person, so it can't move.
}

2. or maintaining separate vectors and going:

vector<Person*> people ;
vector<Building*> buildings ;

vector<Thing*> things ;

// FIND whether the selectedThing is in Person* vector or Building* vector.
for( int i = 0 ; i < people.size() ; i++ )
{
  if( people[i] == selectedThing )
  {
    // selected Thing is a person, so it can be cast
    // to Person* and MoveTo() can be executed on it
    dynamic_cast( selectedThing )->MoveTo( p ) ;
    break ;
  }
}

(( ANSWER: THE PROBLEM IS WRONG. class Thing should provide handles to “right click here” and “left click there” and the CONCRETE CLASSES should provide the implementation details. You’ve used inheritance incorrectly here and the Thing* interface DOESN’T HAVE ENOUGH METHODS if this is your problem.

So, the answer to this question is:

class Thing abstract
{
  virtual void MoveTo( Point p ) { /*do nothing by default*/ }
} ;

class Person : public Thing
{
  // actually move the person
  void MoveTo( Point p ) override ;
} ;

class Building : public Thing
{
  // does NOT (bother overriding) MoveTo( Point p ) ;
} ;

Then the code simply reduces to:

selectedThing->MoveTo( p ) ;

And so, IF the selectedThing is indeed a Building*, then selectedThing->MoveTo() boils down to (nothing happening), and if its a Person*, selectedThing->MoveTo() boils down to actual movement. Later you could build out the MoveTo command to MEAN SOMETHING ELSE to a Building, and this is EXACTLY what polymorphism is supposed to do: make different objects behave differently given the same command.

class Animal abstract { virtual void Speak() { } } ;

class Dog : public Animal {
  void Speak() { puts("Woof") ; } 
} ;

class Cat : public Animal {
  void Speak() { puts("Meow") ; } 
} ;

I get this adobe acrobat bug where when i resize the window, the document doesn’t resize

i don’t want to apply any 3 hour patches, so all I do is WINDOW->SPLIT then WINDOW->REMOVE SPLIT and it makes it work!

I kept on getting this STUPID error when programming this big project when I’d try to #include header files that had class definitions in them.

The compiler would pretend like it didn’t know the type, even though I GAVE IT THE HEADER FILE.

The answer was to provide a STUPID forward declaration of the type:

class Typename ;

EVEN THOUGH I FULLY INCLUDED THE HEADER!!

How do you programmatically disable vertical sync (vsync) in Direct3D9?

Just set your PresentationInterval in your D3DPRESENT_PARAMETERS struct to D3DPRESENT_INTERVAL_IMMEDIATE

It would seem that

Ax + By + C = 0

doesn’t really have a direction. Its just an infinite line, right?

WRONG.

take

-x + y = 0

This is the line through the origin, forming the line y = x.

1. Does this line have a direction?

2. Is there another line with a different equation that DESCRIBES THE SAME LINE?

Yes there is, to the second question, and YES IT DOES, to the first question.

The answer to 2.: The equivalent line is x – y = 0. That line is EXACTLY the same as -x + y = 0, only it “points” in the opposite direction.

So which “way” is -x + y pointing, and which way is x – y = 0 pointing?

Well, I’ll tell you.

x – y = 0 points “down and to the left”

-x + y = 0 points “up and to the right”

the reason for this is clear when you use vectors and the equations

A = y1 – y2
B = x2 – x1
C = x1y2 – x2y1

Then, if you use the points

P1 = (1,1)
P2 = (0,0)

You get the equation

A = 1 – 0 = 1
B = 0 – 1 = -1
C = 0

Then

x – y = 0
POINTS DOWN AND LEFT!!

And so, the opposite equation
-x + y = 0
POINTS UP AND RIGHT!!

On the “left side” of a line is +
On the “right side” of a line is –

Taking the one that goes up and right:
plug in ( 2, 0 )
-x + y = 0
-2 + 0 = -2

So, (2,0) is negative in that line equation, meaning (2,0) is “right” of -x + y = 0

Taking (-2,0)
2 + 0 = 2
so, (-2,0) is “left” of -x + y = 0

Here’s a simple Direct3D starter that you can copy and paste into a Visual Studio 2005/2008 project.

Assumes you have the DirectX sdk installed… many of the comments from the original were deleted in this one.


#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include <d3d9.h>      // core direct3d
#include <d3dx9.h>     // aux libs

#include <dxerr.h>    // detailed error messages

#pragma comment(lib, "d3d9.lib")
#pragma comment(lib, "d3dx9.lib")  // aux libs
#ifdef _DEBUG
#pragma comment(lib,"d3dx9d.lib")
#else
#pragma comment(lib,"d3dx9.lib")
#endif

#pragma comment(lib, "dxerr.lib")


// Macros.
#define SAFE_RELEASE(ptr) if(ptr) { ptr->Release(); ptr = NULL; }
#define CAST_AS_DWORD(x) *((DWORD*)&x)
#define PI 3.14159


#pragma region define the Vertex structure
struct Vertex 
{
  float x,y,z ;
  DWORD color ;

  // Ctor starts you at origin in black
  // with alpha (opacity) set to 100%
  Vertex()
  {
    x=y=z = 0.0f;
    color = D3DCOLOR_XRGB( 0,0,0 ) ;
  }

  Vertex( float ix, float iy, float iz )
  {
    x=ix;y=iy;z=iz;
    color = D3DCOLOR_XRGB( 255,255,255 ) ;
  }

  // Ctor.
  Vertex( float ix, float iy, float iz,
    unsigned char ir, unsigned char ig, unsigned char ib )
  {
    x=ix;y=iy;z=iz;
    color = D3DCOLOR_XRGB( ir, ig, ib ) ;
  }

  // Ctor that lets you pick alpha
  Vertex( float ix, float iy, float iz,
    unsigned char ir, unsigned char ig, unsigned char ib, unsigned char ALPHA )
  {
    x=ix;y=iy;z=iz;
    color = D3DCOLOR_ARGB( ALPHA, ir, ig, ib ) ;
  }
} ;
#pragma endregion





struct Globals
{
  struct _Win
  {
    HINSTANCE hInstance;    // window app instance
    HWND hwnd;              // handle for the window
    HWND hConsole ;         // handle for the console window
    
    int width, height;
  } win ;

  IDirect3D9 * d3d ;
  IDirect3DDevice9 * gpu ; 

  struct _data
  {
    Vertex verts[ 3 ] ;

    _data()
    {
      // some global data to draw and manipulate
      // for this example
      
      // Red vertex @ ( -1, 0, 0 )
      verts[ 0 ] = Vertex( -1, 0, 0, 255, 19, 0 ) ;

      // Green vertex @ ( 0, 1, 0 )
      verts[ 1 ] = Vertex(  0, 1, 0, 0, 255, 0 ) ;

      // Blue vertex @ ( 1, 0, 0 )
      verts[ 2 ] = Vertex(  1, 0, 0, 0, 0, 255 ) ;

    }
  } data ;
};

///////////////////////////
// GLOBALS
Globals g;


///////////////////////////
// FUNCTION PROTOTYPES
inline bool CHECK( HRESULT hr, char * msg, bool stop=true ) ;  // checks for errors on the HR passed.
bool initD3D() ;         // function to initialize the BEAST that is Direct3D9
void update() ;          // changes geometry of the scene
void drawAxes() ;        // draws the ever-important axes (for finding your way around your own scene!)
void draw() ;            // drawing function containing Direct3D drawing calls

LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam );
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow );




/////////////////////////
// FUNCTION IMPLEMENTATIONS
inline bool CHECK( HRESULT hr, char * msg, bool stop )
{
  if( FAILED( hr ) )
  {
    printf( "%s. %s:  %s\n",
            msg, DXGetErrorStringA( hr ), DXGetErrorDescriptionA( hr ) ) ;

    // Pause so we can see the error and deal with it.
    if( stop )  system("pause") ;

    return false ;
  }
  
  else
    return true ;


}

/// Initializes Direct3D9.  Returns true on success.
bool initD3D()
{
  // start by nulling out both pointers:
  g.d3d = 0 ;
  g.gpu = 0 ;
  
  g.d3d = Direct3DCreate9( D3D_SDK_VERSION ) ;

  if( g.d3d == NULL )
  {
    // DEVICE CREATION FAILED!!!! OH NO!!!
    puts( "Oh.. PHOOEY!!!!!  Device creation FAILED!!! WHAT NOW???\n" ) ;
    return false ;
  }



  puts( "Direct3D9 creation success!" ) ;
  
  D3DPRESENT_PARAMETERS pps = { 0 } ;

  pps.Windowed = true ;
  pps.BackBufferCount = 1 ;
  pps.SwapEffect = D3DSWAPEFFECT_DISCARD ;
  pps.BackBufferFormat = D3DFMT_UNKNOWN ; 
  pps.EnableAutoDepthStencil = true ;
  pps.AutoDepthStencilFormat = D3DFMT_D16 ;

  HRESULT hr = g.d3d->CreateDevice(
    
    D3DADAPTER_DEFAULT, // primary display adapter
    D3DDEVTYPE_HAL,     // use HARDWARE rendering (fast!)
    g.win.hwnd,
    D3DCREATE_HARDWARE_VERTEXPROCESSING,
    &pps,
    &g.gpu

  ) ;


  if( !CHECK( hr, "OH NOS!! I could not initialize Direct3D!  Bailing...\n" ) )
  {
    return false ;
  }



  puts( "Direct3D9 GPU device creation successful" ) ;
  







  hr = g.gpu->SetFVF( D3DFVF_XYZ | D3DFVF_DIFFUSE ) ;
  CHECK( hr, "SetFVF FAILED!" ) ;
  
  D3DVERTEXELEMENT9 pos ;
  
  pos.Usage = D3DDECLUSAGE_POSITION ;
  pos.UsageIndex = 0 ;
  pos.Stream = 0 ; 
  pos.Type = D3DDECLTYPE_FLOAT3 ;
  pos.Offset = 0 ;

  pos.Method = D3DDECLMETHOD_DEFAULT ; 
  
  
  D3DVERTEXELEMENT9 col;
  
  col.Usage = D3DDECLUSAGE_COLOR ;
  col.UsageIndex = 0 ;
  col.Stream = 0 ;
  col.Type = D3DDECLTYPE_D3DCOLOR ;
  col.Offset = 3*sizeof( float ) ;
  col.Method = D3DDECLMETHOD_DEFAULT ;
  
  D3DVERTEXELEMENT9 vertexElements[] =
  {
    pos,
    col,

    D3DDECL_END()

  } ;
  
  IDirect3DVertexDeclaration9 * Vdecl ;

  hr = g.gpu->CreateVertexDeclaration( vertexElements, &Vdecl ) ;
  CHECK( hr, "CreateVertexDeclaration FAILED!" ) ;

  hr = g.gpu->SetVertexDeclaration( Vdecl ) ;
  CHECK( hr, "SetVertexDeclaration FAILED!" ) ;

  hr = g.gpu->SetRenderState( D3DRS_COLORVERTEX, TRUE ) ;
  CHECK( hr, "SetRenderState( COLORVERTEX ) FAILED!" ) ;

  hr = g.gpu->SetRenderState( D3DRS_LIGHTING, FALSE ) ;
  CHECK( hr, "Lighting off" ) ;

  hr = g.gpu->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ) ;
  CHECK( hr, "cull mode off" ) ;








  return true ;
}



void update()
{
  static float change = 0.01f ;
  g.data.verts[0].x += change;

  if( g.data.verts[0].x < -0.5f )
    change = 0.01f;
  else if( g.data.verts[0].x > 0.5f )
    change = -0.01f;
}


////////////////////////
// DRAWING FUNCTIONS
void drawAxes()
{

  static float axisLen = 2.0f ;
  static Vertex axis[] = {

    // x-axis is red
    Vertex( -axisLen, 0, 0, 255, 0, 0 ),
    Vertex( +axisLen, 0, 0, 255, 0, 0 ),

    // y-axis green
    Vertex( 0, -axisLen, 0, 0, 255, 0 ),
    Vertex( 0, +axisLen, 0, 0, 255, 0 ),

    // z-axis blue
    Vertex( 0, 0, -axisLen, 0, 0, 255 ),
    Vertex( 0, 0, +axisLen, 0, 0, 255 )

  } ;



  HRESULT hr = g.gpu->DrawPrimitiveUP( D3DPT_LINELIST, 3, axis, sizeof( Vertex ) ) ;
  CHECK( hr, "DrawPrimitiveUP FAILED!" ) ;

  static float pointSize = 8.0f ;

  g.gpu->SetRenderState( D3DRS_POINTSIZE, CAST_AS_DWORD( pointSize ) ) ;

  // Draw points at end of axis.
  static Vertex points[] = {
    Vertex( axisLen, 0, 0, 255, 0, 0 ),
    Vertex( 0, axisLen, 0, 0, 255, 0 ),
    Vertex( 0, 0, axisLen, 0, 0, 255 ),
  } ;

  hr = g.gpu->DrawPrimitiveUP( D3DPT_POINTLIST, 3, points, sizeof( Vertex ) ) ;
  CHECK( hr, "DrawPrimitiveUP FAILED!" ) ;

}

void draw()
{
  HRESULT hr ;

  hr = g.gpu->Clear( 0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 
    D3DCOLOR_ARGB( 255, 25, 25, 25 ), 1.0f, 0 ) ; 
  CHECK( hr, "Clear FAILED!" ) ;

  #pragma region set up the camera
  D3DXMATRIX projx ;
  
  D3DXMatrixPerspectiveFovRH( &projx, PI/4, (float)g.win.width/g.win.height, 1.0f, 1000.0f ) ;
  
  g.gpu->SetTransform( D3DTS_PROJECTION, &projx ) ;

  D3DXMATRIX viewx ;

  D3DXVECTOR3 eye( 4, 2, 4 ) ;
  D3DXVECTOR3 look( 0, 0, 0 ) ;
  D3DXVECTOR3 up( 0, 1, 0 ) ;
  D3DXMatrixLookAtRH( &viewx, &eye, &look, &up ) ;
  g.gpu->SetTransform( D3DTS_VIEW, &viewx ) ;
  #pragma endregion

  hr = g.gpu->BeginScene() ;
  CHECK( hr, "BeginScene FAILED!" ) ;

  
  #pragma region ACTUALLY __draw__

  drawAxes();


  hr = g.gpu->DrawPrimitiveUP( D3DPT_TRIANGLELIST, 1, g.data.verts, sizeof( Vertex ) ) ;
  CHECK( hr, "DrawPrimitiveUP FAILED!" ) ;

  #pragma endregion

  hr = g.gpu->EndScene() ;
  CHECK( hr, "EndScene FAILED!" ) ;

  // And finally, PRESENT what we drew to the backbuffer
  g.gpu->Present( 0, 0, 0, 0 ) ;



}



int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow )
{
  //////////////////
  // First we'll start by saving a copy of
  // the hInstance parameter inside our
  // "glob" of globals "g":
  g.win.hInstance = hInstance;
  // In case we need it later, we'll have it
  // with firsthand easy access.

  #pragma region part 0 - attach a console
  // Attach a console
  AllocConsole();
  AttachConsole( GetCurrentProcessId() ) ;
  freopen( "CON", "w", stdout ) ; // redirect stdout to console
  freopen( "CON", "w", stderr ) ; // redirect stderr to console

  // Move the console over to the top left
  g.win.hConsole = GetConsoleWindow();
  MoveWindow( g.win.hConsole, 0, 0, 400, 400, true ) ;

  printf( "* * Computer Program Begin * *\n" ) ;
  #pragma endregion

  #pragma region part 1 - create a window
  // The next few lines you should already
  // be used to:  create a WNDCLASSEX
  // that describes the properties of
  // the window we're going to soon create.
  // A.  Create the WNDCLASSEX
  WNDCLASSEX wcx = { 0 } ;
  wcx.cbSize = sizeof( WNDCLASSEX );
  wcx.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH );
  wcx.hCursor = LoadCursor( NULL, IDC_ARROW );
  wcx.hIcon = LoadIcon( NULL, IDI_APPLICATION );
  wcx.hInstance = hInstance;
  wcx.lpfnWndProc = WndProc;
  wcx.lpszClassName = TEXT("Philip");
  wcx.lpszMenuName = 0;
  wcx.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;

  // Register that class with the Windows O/S..
  RegisterClassEx( &wcx );

  int width = 800, height = 600;
  int leftEdge = 400, topEdge = 25 ;
  RECT rect;
  SetRect( &rect,
    leftEdge,  // left
    topEdge,   // top
    leftEdge + width, // right
    topEdge  + height ); // bottom

  // Save width and height off.
  g.win.width = rect.right - rect.left;
  g.win.height = rect.bottom - rect.top;

  // Adjust it.
  DWORD windowStyle = WS_OVERLAPPEDWINDOW ; // typical features of a normal window
  DWORD windowExStyle = 0 ; // I want the window to be topmost

  AdjustWindowRectEx( &rect, windowStyle, false, windowExStyle );

  g.win.hwnd = CreateWindowEx(
    windowExStyle,
    TEXT("Philip"),
    TEXT("DIRECT3D WINDOW"),
    windowStyle,
    rect.left, rect.top,  // adjusted x, y positions
    rect.right - rect.left, rect.bottom - rect.top,  // adjusted width and height
    NULL, NULL,
    hInstance, NULL);

  // check to see that the window
  // was created successfully!
  if( g.win.hwnd == NULL )
  {
    FatalAppExit( NULL, TEXT("CreateWindow() failed!") );
  }

  // and show.
  ShowWindow( g.win.hwnd, iCmdShow );

  // JUMP to the initD3D() method.
  if( !initD3D() )
  {
    FatalAppExit( 0, TEXT("SORRY!!!  DEVICE CREATION FAILED!!! YOU LOSE, WITHOUT EVEN PLAYING THE GAME!!!" ) ) ;
  }
  
  #pragma endregion

  #pragma region message loop
  MSG msg;

  while( 1 )
  {
    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
    {
      if( msg.message == WM_QUIT )
      {
        break;
      }

      TranslateMessage( &msg );
      DispatchMessage( &msg );
    }
    else
    {
      update();
      draw();
    }
  }
  #pragma endregion

  //////////////
  // clean up
  SAFE_RELEASE( g.gpu ) ;
  SAFE_RELEASE( g.d3d ) ;

  // and a cheesy fade exit
  AnimateWindow( g.win.hwnd, 200, AW_HIDE | AW_BLEND );

  printf( "* * This Computer Program Has Ended * *\n" ) ;
  
  return msg.wParam;
}

////////////////////////
// WNDPROC
// Notice that WndProc is very very neglected.
// We hardly do anything with it!  That's because
// we do all of our processing in the draw()
// function.
LRESULT CALLBACK WndProc(   HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam )
{
  switch( message )
  {
  case WM_CREATE:
    Beep( 50, 10 );
    return 0;
    break;

  case WM_PAINT:
    {
      HDC hdc;
      PAINTSTRUCT ps;
      hdc = BeginPaint( hwnd, &ps );
      // don't draw here.  would be waaay too slow.
      // draw in the draw() function instead.
      EndPaint( hwnd, &ps );
    }
    return 0;
    break;

  case WM_KEYDOWN:
    switch( wparam )
    {
    case VK_ESCAPE:
      PostQuitMessage( 0 );
      break;
    default:
      break;
    }
    return 0;

  case WM_SIZE:
    {
      int width = LOWORD( lparam ) ;
      int height = HIWORD( lparam ) ;
      printf( "RESIZED TO width=%d height=%d\n", width, height ) ;
    }
    break;

  case WM_DESTROY:
    PostQuitMessage( 0 ) ;
    return 0;
    break;
  }

  return DefWindowProc( hwnd, message, wparam, lparam );
}






i heard somewhere i can’t remember i think it was an interview with that guy who created the SOLID principles – but he says “migrate your complexity into the data”

WHERE was that from again?

software complexity

This is a very long, very long, very long tutorial about how to get started with D3D in C++.

Check it out!

//////////////////////////////////////////
//                                      //
// Direct3D basics                      //
//                                      //
// You found this at bobobobo's weblog, //
// https://bobobobo.wordpress.com        //
//                                      //
// Creation date:  July 1/09 (HAPPY CANADA DAY! ) //
// Last modified:  July 3/09            //
//                                      //
//////////////////////////////////////////

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include <d3d9.h>      // core direct3d
#include <d3dx9.h>     // aux libs

#include <dxerr9.h>    // detailed error messages

#pragma comment(lib, "d3d9.lib")
#pragma comment(lib, "d3dx9.lib")  // aux libs
#ifdef _DEBUG
#pragma comment(lib,"d3dx9d.lib")
#else
#pragma comment(lib,"d3dx9.lib")
#endif

#pragma comment(lib, "dxerr9.lib")


// Macros.
#define SAFE_RELEASE(ptr) if(ptr) { ptr->Release(); ptr = NULL; }
#define CAST_AS_DWORD(x) *((DWORD*)&x)
#define PI 3.14159

struct Globals
{
  // Wrapping the Win32-related variables up
  // together in their own struct so they don't
  // get in the way of the Direct3D ones
  struct _Win
  {
    HINSTANCE hInstance;    // window app instance
    HWND hwnd;              // handle for the window
    HWND hConsole ;         // handle for the console window
    
    int width, height;      // the desired width and
    // height of the CLIENT AREA
    // (DRAWABLE REGION in Window)
  } win ;

  #pragma region DIRECT3D9 stuff
  ////////////////////////////
  // Declare The IDirect3D9 INTERFACE!!
  // IDirect3D9 interface
  IDirect3D9 * d3d ;        // represents the BEAST
  // that is Direct3D9 itself.  What's it for?
  
  // MSDN SAYS about the IDirect3D9 interface:
  // "Applications use the methods of the IDirect3D9 interface
  // to create Microsoft Direct3D objects and set up the
  // environment. This interface includes methods for
  // enumerating and retrieving capabilities of the device."

  // IDirect3DDevice9
  IDirect3DDevice9 * gpu ;  // represents the GPU

  // MSDN SAYS about the IDirect3DDevice9:  "Applications use the
  // methods of the IDirect3DDevice9 interface to perform
  // DrawPrimitive-based rendering, create resources, work
  // with system-level variables, adjust gamma ramp levels,
  // work with palettes, and create shaders."
  ////////////////////////////

  // The ABOVE TWO variables are
  // very important to this application.
  
  // For both of these, notice how they
  // are BOTH POINTERS to an INTERFACE.

  // What's an interface?  Well, in a few words,
  // an INTERFACE is something you "face" to
  // interact with something.  Thru means of
  // the "INTERFACE" you get information from
  // the underlying system, or send commands
  // to the underlying system, without really
  // having to understand the underlying system
  // at all to do it.  You just have to know what
  // types of commands it expects to get.

  // For example, your car.

  // The "interface" of your car is its steering wheel,
  // its dials on the dash telling you what speed
  // you're going and the RPM's you're at so you
  // don't blow the engine redlining, and also,
  // the gas and brakes, so you can send commands
  // to the car to stop and go.

  // Notice how you don't have to know a THING
  // about how an internal combustion engine works
  // to get the car to go.  Because the car's INTERFACE
  // is SO abstract (simply PUSH THE PEDAL TO GO),
  // working the car becomes incredibly simple.

  // If the car didn't have such an abstract
  // interface (like, if REALLY crummy engineers
  // made a car), then to drive that crummy car,
  // you might have to put your hands into
  // the engine and carefully push
  // vaporized gas underneath a piston, then
  // push down on the piston until it goes POP!
  // Then the car would be going!
  
  // Anyway, point is, working with a system
  // THROUGH ITS INTERFACE that the system defines
  // makes working with the system SO easy, and
  // the system itself is a black box -- its internal
  // workings are hidden from you.  Like, you
  // don't even have to know what an internal
  // combustion engine IS to be able to
  // work a modern car.  Heck, for all you know,
  // it might not even be an internal combustion
  // engine!  (It might be electric).  That's another
  // beauty about interfaces:  You can swap out
  // the nitty gritty details of the implementation
  // (e.g. software updates / patches, or the
  // difference between Direct3D9 June 2008 release
  // and March 2009 release) without affecting 
  // the programs that USE those interfaces, so long
  // as you have not CHANGED the interface itself.

  // IN the case of Direct3D9, an IDirect3DDevice9 *
  // is a pointer to, let's just say the "dashboard" ON TOP
  // OF the Direct3D9 RENDERING MACHINE.

  // Inside, the Direct3D 3D graphics "engine" is VERY complex!
  // Especially when you get to rendering textures in 3D..
  // (see this book if you want to learn that stuff!)
  
  // But with Direct3D9, you don't have to understand
  // HOW 3d graphics actually gets drawn.  You only have to
  // understand the format that D3D expects, and pass it
  // your data that you want drawn in that format.

  // OK?  So hopefully that made a little bit of sense.
  // To me Direct3D seems slightly more "centralized"
  // than OpenGL does.  With OpenGL, the "interface"
  // is a set of C-style functions that all begin
  // with gl*.  OpenGL doesn't have an "INTERFACE"
  // in the OOP sense (but that set of gl* C functions
  // is still an 'interface' though, its just a very
  // different way of creating one!)

  // Anyway, on with it.
  #pragma endregion
};

///////////////////////////
// GLOBALS
// declare one struct Globals called g;
Globals g;
//
///////////////////////////


///////////////////////////
// FUNCTION PROTOTYPES
// Windows app functions.  If need help
// understanding these, see MostBasicWindow
// and FastWindowsProgram
LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam );
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow );

inline bool CHECK( HRESULT hr, char * msg, bool stop=true ) ;  // checks for errors on the HR passed.

bool initD3D() ;         // function to initialize the BEAST that is Direct3D9
void printSystemInfo() ; // function that prints some system info.  can ignore if not interested
void draw() ;            // drawing function containing Direct3D drawing calls

//
///////////////////////////


/// If there was an error, the ErrorString is printed out for you to see at the console.
inline bool CHECK( HRESULT hr, char * msg, bool stop )
{
  if( FAILED( hr ) )
  {
    printf( "%s. %s:  %s\n",
            msg, DXGetErrorString9A( hr ), DXGetErrorDescription9A( hr ) ) ;

    // Pause so we can see the error and deal with it.
    if( stop )  system("pause") ;

    return false ;
  }
  
  else
    return true ;


}

///////////////////////////
// FUNCTION IMPLEMENTATIONS
/// Initializes Direct3D9.  Returns true on success.
bool initD3D()
{
  // start by nulling out both pointers:
  g.d3d = 0 ;
  g.gpu = 0 ;
  
  // Create the IDirect3D9 (d3d) object now.  We need the d3d object
  // in order to be able to create the IDirect3DDevice9 interface.
  // We can also use the d3d object to find out additional information
  // about the system we are on (such as the number of displays it has, etc).

  // [[ I know, I know.  If you think its confusing/stupid to have
  // two separate Direct3D9 things both starting with I, 
  // just bear with it because you'll see that these two objects
  // will do VERY different things, and you'll see it does
  // make a whole lot of sense to separate them out into two things.
  // Granted, they could have been named a little more distinctly,
  // but whaddya gonna do... ]]
  
  // So, the IDirect3D9 object (variable 'd3d') is the "interface"
  // or means by which we will access the Direct3D9
  // beast
  
  // And the IDirect3DDevice9 (called 'gpu') is THE
  // variable that IS OUR PROGRAMMATIC HANDLE TO THE GPU and
  // we will use it A LOT to send down triangles and stuff to the
  // gpu to be drawn.

  // we'll be using 'gpu' a lot more than 'd3d'.

  // So now, to create our 'd3d' interface.
  // Remember, FROM this interface will come
  // our 'gpu' interface.

  // Direct3DCreate9
  g.d3d = Direct3DCreate9( D3D_SDK_VERSION ) ;  // Always use D3D_SDK_VERSION

  if( g.d3d == NULL )
  {
    // DEVICE CREATION FAILED!!!! OH NO!!!
    puts( "Oh.. PHOOEY!!!!!  Device creation FAILED!!! WHAT NOW???\n" ) ;
    return false ;
  }



  // Ok, if we get here without returning, it means device creation succeeded.
  puts( "Device creation SUCCESS!!!!\nWe're in business now, son..\n" ) ;
  
  // Next we'll just print a few details about the system
  // just because we can..
  // Note how we use PURELY the 'd3d' object
  // to do this (NOT the 'gpu' device, which hasn't
  // even been created yet!)
  ///// printf( "I will now tell you some \nthings ABOUT your system.\n" );
  ///// printSystemInfo(); // BOOOOORING.
  


  puts( "Ok, Now to CREATE the 'gpu' device!!" ) ;
  
  // First, create the D3DPRESENT_PARAMETERS structure.
  // This structure will basically "explain" to the
  // IDirect3D9 interface EXACTLY WHAT we want the
  // GPU rendering surface to look like once
  // it has been created.



  // D3DPRESENT_PARAMETERS structure
  D3DPRESENT_PARAMETERS pps = { 0 } ;  // Start structure all 0'd out.

  // We're using a windowed mode, NOT fullscreen in this
  // example.  Its really annoying to program little test
  // apps in fullscreen mode.  Also when using windowed mode
  // we don't have to (in fact, we should not) specify
  // some of the other parameters, such as the refresh rate.
  pps.Windowed = true ;

  // How many backbuffers do we want?  One.
  pps.BackBufferCount = 1 ;

  // This one's interesting
  // Backbuffering.  Imagine Leonardo Davinci doing
  // a live animation for you.

  // Imagine he stood in front of the canvas,
  // and blazingly quickly, painted a live scene for you.
  // Then to make the animation effect happen, he'd have
  // to erase the canvas (paint over it in all white?) then
  // paint over that white the next frame.

  // Not that great for watching an "animation!"  even if
  // he moved blazing fast, it'd still be "flickery" having
  // to "see" the canvas get all cleared out, then see each
  // shape get drawn on.

  // So instead, Davinci has a better idea.  He will
  // use TWO canvases.  He will draw to the canvas
  // in a HIDDEN place, where you can't see it.

  // When he's done painting hte first frame, BAM,
  // he slams it in your face and you can see it.
  // He then takes a SECOND canvas, and paints to it
  // blazing fast, what should be the next frame you see.
  // Then, BAM, he slams that second canvas right in your face,
  // where you can see it.  He then quietly pulls away
  // that first canvas that had the first frame on it
  // (which you can't see anymore, because you're looking
  // at the SECOND canvas he just slammed in your face),
  // and quickly paints the NEXT (3rd) frame onto it.
  // Then, BAM, he slams that first canvas in your face
  // again, but now it has the 3rd frame on it.  He then
  // takes the SECOND canvas, and draws the 4th frame on it...

  // Do you see what's happening here?  Read it again
  // if not... the whole point is to give a MUCH smoother
  // and continuous presentation of image frames.  If you
  // didn't use a backbuffer, then the animation presented
  // would look all awful and flickery and horrible because
  // you'd basically be WATCHING the gpu do its drawing work,
  // instead of looking at nice finished product painted scenes instead.

  // Swap chains
  pps.SwapEffect = D3DSWAPEFFECT_DISCARD ; // You start with
  // 2 buffers, one that displays what you're currently
  // looking at (the "frontbuffer") and
  // one that is hidden from you (the "backbuffer").
  
  // Basically FLIP means that
  // d3d should DRAW to the BACKBUFFER first, then
  // when its done doing that, it should BAM, slam
  // that backbuffer in your face, so you can see it.
  // The former front buffer, is then DISCARDED.

  // SO, the former "backbuffer" is NOW the FRONTBUFFER.
  // And the former front buffer, we will treat
  // as the NEW "backbuffer".

  // SO draw to the OTHER buffer now (which is considered
  // as the backbuffer at the moment), when you're done,
  // BAM, slam that backbuffer in the user's face
  // (so again, the former "backbuffer" has flipped
  // and become the frontbuffer).

  // The OTHER way to do this is to DRAW TO
  // the backbuffer, then to COPY OUT the backbuffer
  // in its entirety to the front buffer.  That's
  // less efficient though, for obvious reasons
  // (copying about 2,000,000 pixels has gotta take
  // at least some time!).  Discard is nice, but
  // using it REQUIRES that you completely update
  // ALL the pixels of the backbuffer before presenting it
  // (because there's NO TELLING what will happen to
  // the frontbuffer once you've "discarded" it!
  // Microsoft says "we might do anything to it..."
  // The Clear() operation is sufficient to touch every
  // pixel on the buffer, so as long as you're calling
  // Clear() every frame, there's nothing to worry about.
  // You'll see Clear() in use a bit later in this tutorial.)

  // Pixel format to use on the backbuffer.
  pps.BackBufferFormat = D3DFMT_UNKNOWN ;   // So, this doesn't mean
  // we don't KNOW the pixel format we want.. its more
  // like saying "D3DFMT_CHOOSE_IT_FOR_ME!"
  
  // What really happens is "color conversion is done by the hardware"

  // But you can think of it as D3D should picking
  // the appropriate pixel format to use.

  
  
  // Now, we WANT Direct3D to create and manage
  // a depth buffer for this surface.  That means
  // if we draw two triangles and one is "closer"
  // than the other, then the "closer" one should
  // be drawn on top of the "further" one.  That's
  // achieved using the depth buffer
  pps.EnableAutoDepthStencil = true ;
  // Now we have to say "how deep" is the depth buffer.
  // Kind of.  How precise are the depth values?
  // The more bits you use, the more "slots of depth"
  // your depth buffer can handle.  If your depth buffer
  // used 2 bits, it might be able to handle 4 levels
  // of depth.  With 16 bits, there's a lot more levels of
  // depth.  Having many different levels of depth is
  // really important because if two objects are
  // like thought by the gpu to be at the exact same
  // "depth", then there will be "z-fighting"
  // z-fighting sample1
  // Apparently some users experienced problems
  // with z-fighting when playing GTA 4 on ATI hardware.

  // We choose a fairly "deep" pixel format (16 bits)
  // Could also choose 24 bits.
  pps.AutoDepthStencilFormat = D3DFMT_D16 ;

  // Finally, make the gpu device.
  HRESULT hr = g.d3d->CreateDevice(
    
    D3DADAPTER_DEFAULT, // primary display adapter
    D3DDEVTYPE_HAL,     // use HARDWARE rendering (fast!)
    g.win.hwnd,
    D3DCREATE_HARDWARE_VERTEXPROCESSING,
    &pps,
    &g.gpu  // THIS IS where you get
    // the ACTUAL return value (the
    // GPU device!) from this function.
    // Because this function has its
    // return value as an HRESULT,
    // the return value is used to
    // indicate success or failure.

  ) ;


  if( !CHECK( hr, "OH NOS!! I could not initialize Direct3D!  Bailing...\n" ) )
  {
    return false ;
  }



  // Successfully created direct3d9 devices
  printf( "WHOO!  We SUCCESSFULLY created the Direct3D9 GPU device\n" ) ;
  


  return true ;
}


////////////////////////
// DRAWING FUNCTION
void draw()
{
  HRESULT hr ;

  #pragma region clear
  // First, we will clear the backbuffer.  This is a VERY general use
  // function and has way more capabilities than we care to use
  // at the moment.  For example, you can choose to clear little
  // sub-rectangles of the screen ONLY instead of clearing the whole
  // screen with the first 2 params.  we're not interested in that though,
  // we just wanna clear the whole screen.

  // IDirect3DDevice9::Clear()
  hr = g.gpu->Clear(

    0, // NUMBER of sub rectangles to clear.  We set to 0 because
       // we don't want to even clear any subrectangles.. we just
       // want to clear the WHOLE thing!

    0, // you can choose to clear only a sub-region of the
       // backbuffer.  But we wanna clear the WHOLE back buffer!
       // so we pass 0 here and d3d will automatically clear the WHOLE THING for us.

    // D3DCLEAR
    D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER /* | D3DCLEAR_STENCIL */,  // next is weird, but
    // here we specify WHAT exactly we want cleared.  Because a 3d
    // buffer is actually made of several LAYERS (color layer,
    // and depth layer, and stencil layer), you choose
    // what exactly what you want cleared.  If you weren't
    // doing 3d graphics for example (you used direct3d9 to draw
    // 2d graphics, which you can!) you would have no need for
    // the depthbuffer.  So you could save a bit of time
    // (clearing a buffer is a relatively expensive operation)
    // by NOT clearing the buffers you aren't going to use.
    
    // In this example we are NOT using the stencil buffer,
    // but we ARE using the color BUFFER ITSELF (like color values)
    // hence specification of D3DCLEAR_TARGET,
    // and we ARE using the depth buffer (D3DCLEAR_ZBUFFER)
    // but we are NOT using the stencil buffer (hence me omitting
    // D3DCLEAR_STENCIL).  There's no sense in clearing out a
    // buffer that's not in use.  That's like vaccumming a room
    // that's just been vaccummed squeaky clean.
    // If you're not going to be picking up any extra dirt,
    // cleaning it again is really just a waste of time and energy.
    
    D3DCOLOR_ARGB( 255, 125, 25, 237 ),  // The color to clear
    // the backbuffer out to.
    
    1.0f, // value to clear the depth buffer to.  we clear
    // it to 1.0f because 1.0f means ("furthest away possible
    // before being out of range")

    // So we clear every value in the depth buffer to this
    // value so when something is rendered that is in view range,
    // it will definitely be closer than 1.0f!
    // (0.0f means right in our faces).
    
    0  // value to clear the stencil buffer to.  since we
    // chose NOT to clear the stencil buffer (omitted
    // D3DCLEAR_STENCIL from above), this value is
    // actually going to be ignored.
    
  ) ; 
  CHECK( hr, "Clear FAILED!" ) ;

  #pragma endregion

  #pragma region set up the camera

  // First we start by setting up the viewport.
  // the viewport "Defines the window dimensions of
  // a render-target surface onto which a 3D volume projects."
  D3DVIEWPORT9 viewport ;

  // Very clear explanations of each (and advice! :) )
  // of these members are on msdn.
  viewport.X = 0 ;
  viewport.Y = 0 ;
  viewport.Width = g.win.width ;
  viewport.Height = g.win.height ;
  viewport.MinZ = 0.0f ;
  viewport.MaxZ = 1.0f ;

  g.gpu->SetViewport( &viewport ) ;


  // Technically we don't need to set the viewport here
  // BUT you can use viewport setting to draw "picture in picture" -

  // Form the 

  // Set projection matrix
  D3DXMATRIX projx ;
  
  // Create a perspective matrix
  D3DXMatrixPerspectiveFovRH( &projx, PI/4, (float)g.win.width/g.win.height, 1.0f, 1000.0f ) ;
  
  // set
  g.gpu->SetTransform( D3DTS_PROJECTION, &projx ) ;

  // Create the view matrix
  D3DXMATRIX viewx ;

  D3DXVECTOR3 eye( 4, 2, 4 ) ;
  D3DXVECTOR3 look( 0, 0, 0 ) ;
  D3DXVECTOR3 up( 0, 1, 0 ) ;
  D3DXMatrixLookAtRH( &viewx, &eye, &look, &up ) ;
  g.gpu->SetTransform( D3DTS_VIEW, &viewx ) ;
  #pragma endregion

  // Preparing to draw
  // FVF.  WTF is an FVF?
  // MSDN:  "Flexible Vertex Format Constants, or FVF codes,
  //   are used to describe the contents of vertices
  //   interleaved in a single data stream that will
  //   be processed by the fixed-function pipeline."

  // FVF stands for "FLEXIBLE VERTEX FORMAT".  If you're familiar with
  // OpenGL, this is a completely (but some might say a little bit better..)
  // way of allowing a person to say WHAT data each vertex has tagged along
  // with it.

  // So let's tell Direct3D what data exactly each VERTEX 
  // will have.  A position?  A color?  A normal?  A texture
  // coordinate?  What do you WANT TO specify for each vertex.

  hr = g.gpu->SetFVF(
    
    D3DFVF_XYZ  // THe most OBVIOUS (and most important?) aspect of a VERTEX is
    // that it have a POSITION, XYZ.  Specifying that our vertex format
    // includes an XYZ position
    
    | D3DFVF_DIFFUSE // We also specify a diffuse color for each vertex.
    
  ) ;
  CHECK( hr, "SetFVF FAILED!" ) ;
  
  // So there we have it.  We just told d3d to expect
  // to get vertices that each have an XYZ coordinate
  // AND a color specified for them.

  

  // SO NOW, before DRAWING anything, we have to 
  // do 2 more things:
  //   #1)  Create a D3DVERTEXELEMENT9 structure
  //       which will represent our vertex format.

  //   #2)  Create an array of vertices to draw!
  
  //   #3)  Just draw it!

  // #1)  This part is a bit confusing at first,
  // but if you read through it carefully, it should
  // make sense.

  // What we need to do here is create a SPECIAL
  // kind of structure called a "VERTEX DECLARATION"
  // This VertexDeclaration will MATCH UP with
  // the "FVF" format that we set up just a couple
  // of lines ago.  Read on!

  // In the specification, we actually have to
  // obey the FVF mapping
  // on msdn.

  /////////////
  #pragma region // <position vertex element decl>
  // IDirect3DVertexDeclaration9
  
  // OK in the FVF above, we promised d3d that
  // EACH AND EVERY vertex would have a POSITION
  // and a COLOR.

  // So we declare and set up TWO D3DVERTEXELEMENT9
  // structures which explain to d3d the EXACT format
  // and nature of each vertex -

  // IS this a bit redundant?  Kind of, yes.  Getting
  // on with it.

  D3DVERTEXELEMENT9 pos ;
  
  // Here is where we say that this part
  // of the vertex will specify a POSITION
  // in space.
  pos.Usage = D3DDECLUSAGE_POSITION ;

  // This part makes sense if you understand
  // that sometimes, you want to send MORE THAN
  // one position coordinate for each vertex.
  // If that makes less sense, then think about
  // sending down more than one COLOR for each
  // vertex, for some type of funky color blending.
  pos.UsageIndex = 0 ;

  pos.Stream = 0 ; // Vertex shaders have a concept
  // of "stream".
  
  // So what's a "stream" you ask?
  // This really is QUITE an advanced topic, so my honest advice
  // to you is to completely ignore the below unless you 
  // REALLY want to know what streams are.

  // <streams>
  // There is a concept in GPU programming called "shader instancing".
  // Shader instancing is when you specify a model's geometry once,
  // then draw that same model like a million times.

  // 

  // So, you specify the model vertex data with POSITIONS on
  // channel 0, for example.  Then you specify a bunch of
  // positions on channel 1 (1,000,000 positions in your game world,
  // or something) that describe places to draw ALL the vertices
  // that are on channel 0.

  // So its really quite complicated and hard to understand.
  // Channels are like TV -- like the TV station sends like,
  // 500 channels down to your TV in parallel (hey, pretend
  // they do), the vertex data you send down to the GPU
  // all goes down to the GPU in parallel, work at drawing the same thing, kind of.
    
  // Your tv can tune into one channel at a time only, and the GPU
  // will actually tune into ALL the channels when drawing..
  // </streams>  See http://msdn.microsoft.com/en-us/library/bb147299(VS.85).aspx for more detail.
    
  // UH, where were we?  Next, we specify the actual data type of
  // the position data.

  pos.Type = D3DDECLTYPE_FLOAT3 ;  // "Vertices will use
  // 3 floats to specify their position in space".
  
  // If you are familiar with GPU datatypes and HLSL,
  // this would correspond directly with the "float3"
  // datatype in the vertex shader.
  
  // If you don't know what a vertex shader is,
  // just suffice it to say, that all this means
  // is 3 floats will be used for the POSITION
  // of the vertex.
  
  // Next we set the "offset":

  pos.Offset = 0 ;

  // In the Vertex STRUCT that WE defined,
  // this is the byte offset from the start
  // of the struct where D3D SHOULD expect
  // to find this data.
  
  // Using default method.
  pos.Method = D3DDECLMETHOD_DEFAULT ; // here's more info
  
  #pragma endregion // </position vertex element decl>
  /////////////


  /////////////
  #pragma region // <color vertex element decl>
  // Next we declare the vertex element that
  // will represent the DIFFUSE COLOR component.
  D3DVERTEXELEMENT9 col;
  
  col.Usage = D3DDECLUSAGE_COLOR ; // its a color
  col.UsageIndex = 0 ; // COLOR0
  col.Stream = 0 ;

  col.Type = D3DDECLTYPE_D3DCOLOR ; // UNFORTUNATELY you MUST
  // chose D3DDECLTYPE_D3DCOLOR when using COLOR0
  // or COLOR1.  If you write your own shader,
  // then you can use a FLOAT4 color.
  // If you try and do that, you will get
  // [5052] Direct3D9: Decl Validator: X254: (Element Error) (Decl Element [2])
  // Declaration can't map to fixed function FVF because color0/color1
  // cannot have type other than D3DDECLTYPE_D3DCOLOR
  // in the d3d extended debug output.

  
  // NEXT, the OFFSET.  The offset is
  // 3*sizeof(float) because the 'POSITION'
  // comes first and takes up 3 floats as we
  // specified above.
  col.Offset = 3*sizeof( float ) ;
  col.Method = D3DDECLMETHOD_DEFAULT ;
  #pragma endregion // </color vertex element decl>
  /////////////
  

  /////////////
  #pragma region create and set vertex declaration
  // Now put the two D3DVERTEXELEMENT9's into
  // an array and create the VertexDeclaration:
  D3DVERTEXELEMENT9 vertexElements[] =
  {
    pos,
    col,

    // VERY IMPORTANT!  D3D doesn't konw
    // HOW MANY elements you will be specifying
    // in advance, so you TELL IT by passing
    // this SPECIAL D3DVERTEXELEMENT9 object
    // which is basically just like the null
    // terminator at the end of C string.
    D3DDECL_END()
  } ;
  
  IDirect3DVertexDeclaration9 * Vdecl ;

  // Now register in the "vertexElements" array
  // we just created above into the decl
  hr = g.gpu->CreateVertexDeclaration( vertexElements, &Vdecl ) ;
  CHECK( hr, "CreateVertexDeclaration FAILED!" ) ;

  // Now SET IN that vertex declaration into the GPU
  hr = g.gpu->SetVertexDeclaration( Vdecl ) ;
  CHECK( hr, "SetVertexDeclaration FAILED!" ) ;
  #pragma endregion

  #pragma region set render states
  // FINALLY, last thing before drawing, we
  // have to set the renderstate to USE
  // the DIFFUSE component to determine the
  // color of each vertex
  // Per-Vertex Color State
  hr = g.gpu->SetRenderState( D3DRS_COLORVERTEX, TRUE ) ;
  CHECK( hr, "SetRenderState( COLORVERTEX ) FAILED!" ) ;

  
  // Turn LIGHTING off.  TRUE to enable Direct3D lighting,
  // or FALSE to disable it. The default value is TRUE.
  // __Only vertices that include a vertex normal are properly lit;
  // vertices that do not contain a normal ___employ a dot product of 0___
  // in all lighting calculations.__!

  // So if you don't disable lighting, what will actually happen is,
  // since we don't specify normals for any of our vertices,
  // they will all have a normal vertex of the 0 vector, so
  // the result is they will all be completely black.
  hr = g.gpu->SetRenderState( D3DRS_LIGHTING, FALSE ) ;
  CHECK( hr, "Lighting off" ) ;


  // Turn backface culling off.  Its good to turn this off
  // when starting out because triangles that you wind
  // ccw are discarded if this is on.
  // http://msdn.microsoft.com/en-us/library/bb204882(VS.85).aspx
  hr = g.gpu->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ) ;
  CHECK( hr, "Culling off" ) ;

  #pragma endregion

  #pragma region declare a vertex structure, create verts
  // OK?? WHEW!!  THAT was a lot of work!
  // Now let's DRAW SOMETHING!!  First,
  // we have to create a STRUCT which
  // will match up the vertex declaration
  // we specified above.

  // Practically you'd probably want this struct
  // to be declared in global space, but its declared
  // inline here just to preserve the
  // flow of information for you.

  struct Vertex 
  {
    float x,y,z ;
    DWORD color ;

    // Ctor starts you at origin in black
    // with alpha (opacity) set to 100%
    Vertex()
    {
      x=y=z = 0.0f;
      color = D3DCOLOR_XRGB( 0,0,0 ) ;
    }

    // Ctor.
    Vertex( float ix, float iy, float iz,
      unsigned char ir, unsigned char ig, unsigned char ib )
    {
      x=ix;y=iy;z=iz;
      color = D3DCOLOR_XRGB( ir, ig, ib ) ;
    }

    // Ctor that lets you pick alpha
    Vertex( float ix, float iy, float iz,
      unsigned char ir, unsigned char ig, unsigned char ib, unsigned char ALPHA )
    {
      x=ix;y=iy;z=iz;
      color = D3DCOLOR_ARGB( ALPHA, ir, ig, ib ) ;
    }
  } ;

  // Now create an array full of vertices!
  Vertex verts[] = {

    // Red vertex @ ( -1, 0, 0 )
    Vertex( -1, 0, 0, 255, 19, 0 ),

    // Green vertex @ ( 0, 1, 0 )
    Vertex(  0, 1, 0, 0, 255, 0 ),

    // Blue vertex @ ( 1, 0, 0 )
    Vertex(  1, 0, 0, 0, 0, 255 )

  } ;

  float axisLen = 2.0f ;
  Vertex axis[] = {

    // x-axis is red
    Vertex( -axisLen, 0, 0, 255, 0, 0 ),
    Vertex( +axisLen, 0, 0, 255, 0, 0 ),

    // y-axis green
    Vertex( 0, -axisLen, 0, 0, 255, 0 ),
    Vertex( 0, +axisLen, 0, 0, 255, 0 ),

    // z-axis blue
    Vertex( 0, 0, -axisLen, 0, 0, 255 ),
    Vertex( 0, 0, +axisLen, 0, 0, 255 )

  } ;

  #pragma endregion

  #pragma region ACTUALLY __draw__
  // IDirect3DDevice9::BeginScene()
  // You must call BeginScene() before you start drawing anything.
  hr = g.gpu->BeginScene() ;
  CHECK( hr, "BeginScene FAILED!" ) ;

  hr = g.gpu->DrawPrimitiveUP( D3DPT_TRIANGLELIST, 1, verts, sizeof( Vertex ) ) ;
  CHECK( hr, "DrawPrimitiveUP FAILED!" ) ;

  hr = g.gpu->DrawPrimitiveUP( D3DPT_LINELIST, 3, axis, sizeof( Vertex ) ) ;
  CHECK( hr, "DrawPrimitiveUP FAILED!" ) ;

  float pointSize = 8.0f ;

  // A DWORD is 4 bytes (a WORD is 2 bytes).
  // So, what we need to do is basically cast
  // pointSize to (DWORD).  Its a bit complicated
  // about how you actually do it, so I made a macro for it.
  // The general idea is you need to "trick" SetRenderState
  // into taking your float value.. SetRenderState "thinks"
  // its a DWORD, while its actually a float.. and D3D
  // internally somehow gets it and knows to treat it as a float.
  // Kind of clunky, eh, but what can you do.
  g.gpu->SetRenderState( D3DRS_POINTSIZE, CAST_AS_DWORD( pointSize ) ) ;
  
  // Draw points at end of axis.
  Vertex points[] = {
    Vertex( axisLen, 0, 0, 255, 0, 0 ),
    Vertex( 0, axisLen, 0, 0, 255, 0 ),
    Vertex( 0, 0, axisLen, 0, 0, 255 ),
  } ;
  hr = g.gpu->DrawPrimitiveUP( D3DPT_POINTLIST, 3, points, sizeof( Vertex ) ) ;
  CHECK( hr, "DrawPrimitiveUP FAILED!" ) ;

  // endscene, and present
  // IDirect3DDevice9::EndScene()
  // You must call EndScene() to signify to the gpu that
  // you are finished drawing.  Must pair up with
  // a BeginScene() call that happened earlier.
  hr = g.gpu->EndScene() ;
  CHECK( hr, "EndScene FAILED!" ) ;

  // And finally, PRESENT what we drew to the backbuffer
  g.gpu->Present( 0, 0, 0, 0 ) ;
  #pragma endregion



}




// function that prints some system info.  can ignore this part
// if you are not interested in it.
void printSystemInfo()
{
  UINT numAdapters = g.d3d->GetAdapterCount() ;
  printf( "\n\n* * * * System information * * * *\n" ) ;
  printf( "Owner name:  Dorky Dorkinson (haha, just kidding, little easter egg there..)\n" ) ;
  printf( "Ok, the rest of this information IS real!\n" ) ;
  
  printf( "You have %d adapters\n  * (this number is bigger than 1 if you have dualview)\n", numAdapters ) ;

  // Scroll through all adapters and print some info about each
  for( int i = 0 ; i < numAdapters ; i++ )
  {
    printf( "\n\n-- ADAPTER #%d --\n", i ) ;
    printf( "On monitor #%d\n", g.d3d->GetAdapterMonitor( i ) ) ;

    // Object into which display mode info will be saved
    // by GetAdapterDisplayMode
    D3DDISPLAYMODE displayMode ;
    g.d3d->GetAdapterDisplayMode( i, &displayMode ) ;

    printf( "Has Format=%d Height=%d Width=%d RefreshRate=%d\n", displayMode.Format, displayMode.Height, displayMode.Width, displayMode.RefreshRate ) ;
    printf( "  * (format refers to the D3DFMT_ pixel mode.. e.g. 22=D3DFMT_X8R8G8B8 which is 24 bit color)\n" ) ;
    
    D3DADAPTER_IDENTIFIER9 id ; // Will hold info about the adapter
    // after call to GetAdapterIdentifier

    g.d3d->GetAdapterIdentifier( i, 0, &id ) ;
    // At this point you can see how WEIRD the API gets.
    // All I want is the adapter identifier, and here MSDN
    // says the API offers to "connect to the Internet
    // and download new MS Windows Hardware Quality Labs certificates."
    // Holy cow.  I don't want to do THAT.  So leave the flag at 0.
    
    // There's PLENTY of info here we don't care about,
    // but some of it is interesting!!  I've printed
    // only the most interesting members, leaving parts
    // like the GUID out.
    printf( "<device driver info>\n" ) ;
    printf( "  Description: %s\n  Device Id: %d\n  Device name: %s\n  Driver: %s\n",
      id.Description, id.DeviceId, id.DeviceName, id.Driver ) ;
    printf( "</device driver info>\n" ) ;
    

    UINT modeCount ;
    
    // I guess this next part just shows.. how FEW modes are
    // actually supported on a GPU.. I have an NVIDIA 8800GTS,
    // and it only supports 28 modes on D3DFMT_X8R8G8B8,
    // and 28 modes on D3DFMT_R5G6B5.  The rest, 0 modes are
    // reported as supported!

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_R8G8B8 ) ;
    printf( "D3DFMT_R8G8B8   %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_A8R8G8B8 ) ;
    printf( "D3DFMT_A8R8G8B8 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_X8R8G8B8 ) ;
    printf( "D3DFMT_X8R8G8B8 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_R5G6B5 ) ;
    printf( "D3DFMT_R5G6B5   %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_X1R5G5B5 ) ;
    printf( "D3DFMT_X1R5G5B5 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_A1R5G5B5 ) ;
    printf( "D3DFMT_A1R5G5B5 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_A4R4G4B4 ) ;
    printf( "D3DFMT_A4R4G4B4 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_R3G3B2 ) ;
    printf( "D3DFMT_R3G3B2   %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_A8 ) ;
    printf( "D3DFMT_A8       %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_A8R3G3B2 ) ;
    printf( "D3DFMT_A8R3G3B2 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_X4R4G4B4 ) ;
    printf( "D3DFMT_X4R4G4B4 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_A2B10G10R10 ) ;
    printf( "D3DFMT_A2B10G10R10 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_A8B8G8R8 ) ;
    printf( "D3DFMT_A8B8G8R8 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_X8B8G8R8 ) ;
    printf( "D3DFMT_X8B8G8R8 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_G16R16 ) ;
    printf( "D3DFMT_G16R16   %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_A2R10G10B10 ) ;
    printf( "D3DFMT_A2R10G10B10 %d modes supported\n", modeCount ) ;

    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_A16B16G16R16 ) ;
    printf( "D3DFMT_A16B16G16R16 %d modes supported\n", modeCount ) ;






    // This mode is the MOST LIKELY TO be supported on your machine.
    modeCount = g.d3d->GetAdapterModeCount( i, D3DFMT_X8R8G8B8 ) ;
    for( int j = 0 ; j < modeCount; j++ )
    {
      g.d3d->EnumAdapterModes( i, D3DFMT_X8R8G8B8, j, &displayMode ) ;

      printf( "For format=%d (D3DFMT_X8R8G8B8) Height=%d Width=%d RefreshRate=%d is SUPPORTED\n", displayMode.Format, displayMode.Height, displayMode.Width, displayMode.RefreshRate ) ;

    }


    // At this point you're thinking, "HEY!!  But i'm SURE my gpu supports
    // alpha blending!  Why are all the modes like A8R8G8B8 NOT supported!?"
    // My best stab at this is it makes no sense to DISPLAY something with
    // an alpha component still in it.  For the final image that gets displayed --
    // the alphas should already have been blended -- present day
    // monitors can only display RGB, they don't have the ability to
    // "go transparent".  Maybe one day when we work with those enormous
    // glass screens that people work with in the movies -- kinda like this one:
    // http://business.timesonline.co.uk/multimedia/archive/00339/screen-385_339034a.jpg
    // then having an ALPHA component on the display WOULD make sense.  But for
    // now, all monitors are completely opaque, and they only display colors
    // RGB.  So an alpha component makes no sense on the display itself.
    // That's why displays don't support that display mode.



    // K, FINALLY we get to the device's capabilities.
    // I love how DirectX lets you "reflect" on what
    // the hardware is in fact capable of.  Its nice.

    D3DCAPS9 caps ;
    g.d3d->GetDeviceCaps( i, D3DDEVTYPE_HAL, &caps ) ;

    // Now we have the capabilities of the device.
    // Printing all of them would be meaningless,
    // but if you want to inspect some of them, just
    // use the debugger.

  }
}





int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow )
{
  //////////////////
  // First we'll start by saving a copy of
  // the hInstance parameter inside our
  // "glob" of globals "g":
  g.win.hInstance = hInstance;
  // In case we need it later, we'll have it
  // with firsthand easy access.

  #pragma region part 0 - attach a console
  // Attach a console
  AllocConsole();
  AttachConsole( GetCurrentProcessId() ) ;
  freopen( "CON", "w", stdout ) ; // redirect stdout to console
  freopen( "CON", "w", stderr ) ; // redirect stderr to console

  // Move the console over to the top left
  g.win.hConsole = GetConsoleWindow();
  MoveWindow( g.win.hConsole, 0, 0, 400, 400, true ) ;

  printf( "* * Computer Program Begin * *\n" ) ;
  #pragma endregion

  #pragma region part 1 - create a window
  // The next few lines you should already
  // be used to:  create a WNDCLASSEX
  // that describes the properties of
  // the window we're going to soon create.
  // A.  Create the WNDCLASSEX
  WNDCLASSEX wcx = { 0 } ;
  wcx.cbSize = sizeof( WNDCLASSEX );
  wcx.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH );
  wcx.hCursor = LoadCursor( NULL, IDC_ARROW );
  wcx.hIcon = LoadIcon( NULL, IDI_APPLICATION );
  wcx.hInstance = hInstance;
  wcx.lpfnWndProc = WndProc;
  wcx.lpszClassName = TEXT("Philip");
  wcx.lpszMenuName = 0;
  wcx.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;

  // Register that class with the Windows O/S..
  RegisterClassEx( &wcx );

  /////////////////
  // Ok, AT THIS POINT, we'd normally
  // just go ahead and call CreateWindow().
  // And we WILL call CreateWindow(), but
  // there is something I must explain to
  // you first.  That thing is the RECT structure.

  /////////////////
  // RECT:
  //
  // A RECT is just a C struct meant to represent
  // a rectangle.
  //
  // The RECT structure WILL DESCRIBE EXACTLY WHERE
  // AND HOW WE WANT OUR WINDOW TO APPEAR WHEN WE
  // CREATE IT.
  //
  //         TOP
  //       --------
  //       |      |
  // LEFT  |      | RIGHT
  //       --------
  //        BOTTOM
  //
  // So, what we do is, we create the RECT
  // struct for our window as follows:
  RECT rect;
  SetRect( &rect, 420,  // left
    25,  // top
    420 + 800, // right
    25  + 600 ); // bottom

  // Save width and height off.
  g.win.width = rect.right - rect.left;
  g.win.height = rect.bottom - rect.top;

  // Adjust it.
  DWORD windowStyle = WS_OVERLAPPEDWINDOW ; // typical features of a normal window
  DWORD windowExStyle = WS_EX_TOPMOST ; // I want the window to be topmost

  AdjustWindowRectEx( &rect, windowStyle, false, windowExStyle );

  // AdjustWindowRect() expands the RECT
  // so that the CLIENT AREA (drawable region)
  // has EXACTLY the dimensions we specify
  // in the incoming RECT.

  // If you didn't just understand that, understand
  // this:  "you have to call AdjustWindowRect()",
  // and move on.  Its not THAT important, but its
  // good for the performance of your app.

  ///////////////////
  // NOW we call CreateWindow, using
  // that adjusted RECT structure to
  // specify the width and height of the window.
  g.win.hwnd = CreateWindowEx(
    windowExStyle,
    TEXT("Philip"),
    TEXT("TIGER-DIRECT3D WINDOW!"),
    windowStyle,
    rect.left, rect.top,  // adjusted x, y positions
    rect.right - rect.left, rect.bottom - rect.top,  // adjusted width and height
    NULL, NULL,
    hInstance, NULL);

  // check to see that the window
  // was created successfully!
  if( g.win.hwnd == NULL )
  {
    FatalAppExit( NULL, TEXT("CreateWindow() failed!") );
  }

  // and show.
  ShowWindow( g.win.hwnd, iCmdShow );
  #pragma endregion

  #pragma region part 2 - initialize direct3d9

  // JUMP to the initD3D() method.
  if( !initD3D() )
  {
    FatalAppExit( 0, TEXT("SORRY!!!  DEVICE CREATION FAILED!!! YOU LOSE, WITHOUT EVEN PLAYING THE GAME!!!" ) ) ;
  }
  
  #pragma endregion

  #pragma region message loop
  MSG msg;

  while( 1 )
  {
    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
    {
      if( msg.message == WM_QUIT )
      {
        break;
      }
      else
      {
        TranslateMessage( &msg );
        DispatchMessage( &msg );
      }
    }

    // 3.  DRAW USING Direct3D.
    // This region right here is the
    // heart of our application.  THE MOST
    // execution time is spent just repeating
    // this draw() function.
    draw();

  }
  #pragma endregion

  //////////////
  // clean up
  #pragma region clean up

  // Release COM objects.  
  // What's SAFE_RELEASE()?  Well, lots of people use
  // if( pointer ) pointer->Release() ; to guard
  // against null pointer exceptions.
  
  // Like the MS examples do, I've defined
  // SAFE_RELEASE at the top of this file and
  // I'm using it here.  All it does is
  // make sure the pointer is not null before releasing it.
  SAFE_RELEASE( g.gpu ) ;
  SAFE_RELEASE( g.d3d ) ;

  #pragma endregion

  // and a cheesy fade exit
  AnimateWindow( g.win.hwnd, 200, AW_HIDE | AW_BLEND );

  printf( "* * This Computer Program Has Ended * *\n" ) ;
  
  return msg.wParam;
}

////////////////////////
// WNDPROC
// Notice that WndProc is very very neglected.
// We hardly do anything with it!  That's because
// we do all of our processing in the draw()
// function.
LRESULT CALLBACK WndProc(   HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam )
{
  switch( message )
  {
  case WM_CREATE:
    Beep( 50, 10 );
    return 0;
    break;

  case WM_PAINT:
    {
      HDC hdc;
      PAINTSTRUCT ps;
      hdc = BeginPaint( hwnd, &ps );
      // don't draw here.  would be waaay too slow.
      // draw in the draw() function instead.
      EndPaint( hwnd, &ps );
    }
    return 0;
    break;

  case WM_KEYDOWN:
    switch( wparam )
    {
    case VK_ESCAPE:
      PostQuitMessage( 0 );
      break;
    default:
      break;
    }
    return 0;

  case WM_SIZE:
    {
      int width = LOWORD( lparam ) ;
      int height = HIWORD( lparam ) ;
      printf( "RESIZED TO width=%d height=%d\n", width, height ) ;
    }
    break;

  case WM_DESTROY:
    PostQuitMessage( 0 ) ;
    return 0;
    break;
  }

  return DefWindowProc( hwnd, message, wparam, lparam );
}


/*
    ____   __   __      __   __  ___
   / _  \ /  / /  /    /  /  \ \/  /
  / _/ / /  / /  /    /  /    \   /
 / _/ \ /  / /  /__  /  /__   /  /
/_____//__/ /______//______/ /__/

*/

Code package on esnips (thanks esnips!)

error: Usage field contains value that is not a member of D3DDECLUSAGE

Aka CreateVertexDeclaration() returns E_FAIL: An undetermined error occurred

Ever run into this error?

[5108] Direct3D9: Decl Validator: X281: (Element Error) (Decl Element [2]) Usage field contains value that is not a member of D3DDECLUSAGE. Value: 0xcc. Aborting decl validation.

First of all, if you’re still only getting the extent of information that DxErrorDescription9() affords you then you’re not debugging properly (though that post is directed at xna users, it still works exactly the same for d3d c++ users)

In any case, to fix this problem. Did you forget to put a D3DDECL_END() vertex declaration at the END of your vertexElements array?

“Vertex data is defined using an array of D3DVERTEXELEMENT9 structures. Use D3DDECL_END to declare the last element in the declaration.”

The D3DDECL_END() macro just gives you an initializer for a D3DVERTEXELEMENT9 structure that signifies the end of the vertex declaration. Say you intend to create a vertex declaration that has a position and a color:

  D3DVERTEXELEMENT9 vertexElements[ 2 ] =
  {
    pos, // defines a POSITION vertex element
    col   // defines a COLOR vertex element
  } ;

  IDirect3DVertexDeclaration9 * Vdecl ;

  // next line FAILS.
  hr = g.gpu->CreateVertexDeclaration( vertexElements, &Vdecl ) ;

Reason CreateVertexDeclaration fails is because its like calling strlen() on a string that doesn’t have a null-terminator at the end. D3D doesn’t know where to stop.

You get the error “Usage field contains value that is not a member of D3DDECLUSAGE.” because the random garbage memory value when D3D tries to read your “third” element (even though you don’t have one!) makes d3d angry and confused.

So you do this:


  D3DVERTEXELEMENT9 vertexElements[ 2 ] =
  {
    pos,
    col,

    // VERY IMPORTANT!  D3D doesn't konw
    // HOW MANY elements you will be specifying
    // in advance, so you TELL IT by passing
    // this SPECIAL D3DVERTEXELEMENT9 object
    // which is basically just like the null
    // terminator at the end of C string.
    D3DDECL_END()
  } ;

And now it works.

Vertex Declarations in Direct3D9

A lot of API’s do it. BUT WHY?
Passing a pointer to a pointer

#include <stdio.h>
#include <stdlib.h>



char * InitArrayGood0( char * a ) ;
void InitArrayGood1( char * &a ) ;
void InitArrayGood2( char ** a ) ;
void InitArrayEvil( char * a ) ;

int main()
{
  char * word = NULL ;
  
  // This way doesn't work
  InitArrayEvil( word ) ;

  // These 3 ways all work.
  word = InitArrayGood0( word );
  //InitArrayGood1( word );
  //InitArrayGood2( &word );

  if( word == NULL )
  {
    printf("Word is STILL NULL!!!  That init didn't do ANYTHING!!\n") ;
    exit(1);
  }
  else
  {
    word[0] = 'a' ;
    word[1] = 'b' ;
    word[2] = 0 ;

    puts( word ) ;
  }
}

// Does not work
// what happens here is
// the pointer value (0) is
// PASSED BY VALUE to this function.
void InitArrayEvil(char * a)
{
  // Say the array that (a) refers to
  // references a NULL variable.  Well,
  // when we first come into this function,
  //   InitArrayEvil( word ) ;
  // the value of (a) as we start
  // executing this function is 0.

  // We then assign (a) as a new array.
  
  a = new char[20];  // Fine and dandy.

  // BUT THE value of (word) in the
  // CALLING function is UNCHANGED!
  // You really have to think about why.

  // Its tricky because at first, you
  // should think "BUT I PASSED IT
  // BY REFERENCE!!  So any changes
  // to (a) in this function should
  // affect (word) in the calling function!"

  // PARAMETER PASSING IN THIS FUNCTION
  // is ACTUALLY BY VALUE.
  
  // What that means is, even though (a)
  // is a pointer to a char,
  // char * a gets initialized by COPYING
  // the value of (word) that is passed to it
  //    InitArrayEvil( word ) ;
  // If word starts out at NULL, then
  // a starts out at null.  If we subsequently
  // change the value of a, that DOES NOT CHANGE
  // the value of word!

  // Its confusing because say we had a function like
  //   void truncate( char * a )
  //   {
  //     a[ 0 ] = 0 ;
  //   }
  // 
  // call by:
  //   word = new char[ 20 ] ;
  //   word[0] = 'a'; word[1] = 'b'; word[2] = 0;
  //   truncate( word ) ;

  // THEN this function WOULD change whatever array
  // you passed to it.  Because what gets copied in
  // to (a) IS THE MEMORY ADDRESS VALUE of the variable
  // (word).  (word) is then actually manipulated
  // when (a) is manipulated in the truncate() function.

  // This is hard to wrap your head around, but once
  // you get it, it makes perfect sense.
}

// This function WORKS because
// we RETURN a.
char * InitArrayGood0(char * a)
{
  a = new char[20];

  // Here, we are RETURNING that new
  // memory address value for a.  So
  // as long as you write:
  //    word = InitArrayGood0( word )
  // You'll have no problem using this
  // function.  Actually this function
  // doesn't NEED (a) to come into it,
  // (this function should really take
  // NO parameters), but I left it there
  // for consistency.
  return a;
}

// Works
void InitArrayGood1(char * &a)
{
  // So, oddly, THIS function works,
  // but only in C++.

  // a is set up as a char* pointer,
  // but it is set up as AN ALIAS
  // to (word), the variable that exists
  // in the calling function.

  // As a result, (a) basically 
  // "reaches into" the scope of main()
  // and uses THAT SAME VARIABLE (word).

  // So assignment of (a) changes (word).
  // So this function works.
  a = new char[20];
}

// Works
// This function takes a POINTER TO A (char*)
// variable.
// NOW this will work too, and its the most
// common way of handling this type of thing
// (all the DirectX CreateDevice() functions
// use this method).  This way works in
// both C and C++.  Because now the value
// being copied into a is THE MEMORY ADDRESS
// OF THE VARIABLE (word) IN MAIN().
// This means that any change to (*a) directly
// change (word) in main(), which means this
// function can cause (word) to point to something
// new.

// The value COPIED here is the ADDRESS OF A,
// which happens to be a pointer.  Get it?
// its tough, but again once you get it, it makes
// perfect sense.
void InitArrayGood2( char ** a )
{
  *a = new char[20 ] ;
}