  // step3d2.cpp : Defines the initialization routines for the DLL.
//

#include "stdafx.h"
#include "step3d2.h"
#include <ldefin2d.h>
#include <ldefin3d.h>

#ifdef __LIGHT_VERSION__
#include <klAPI5.h>
#else
#include <kAPI5.h>
#endif

#include <ksConstants.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

//
//	Note!
//
//		If this DLL is dynamically linked against the MFC
//		DLLs, any functions exported from this DLL which
//		call into MFC must have the AFX_MANAGE_STATE macro
//		added at the very beginning of the function.
//
//		For example:
//
//		extern "C" BOOL PASCAL EXPORT ExportedFunction()
//		{
//			AFX_MANAGE_STATE(AfxGetStaticModuleState());
//			// normal function body here
//		}
//
//		It is very important that this macro appear in each
//		function, prior to any calls into MFC.  This means that
//		it must appear as the first statement within the 
//		function, even before any object variable declarations
//		as their constructors may generate calls into the MFC
//		DLL.
//
//		Please see MFC Technical Notes 33 and 58 for additional
//		details.
//

/////////////////////////////////////////////////////////////////////////////
// CStep3d2App

BEGIN_MESSAGE_MAP(CStep3d2App, CWinApp)
	//{{AFX_MSG_MAP(CStep3d2App)
		// NOTE - the ClassWizard will add and remove mapping macros here.
		//    DO NOT EDIT what you see in these blocks of generated code!
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CStep3d2App construction

CStep3d2App::CStep3d2App()
{
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CStep3d2App object

CStep3d2App theApp;

//-------------------------------------------------------------------------------
//
// ---
unsigned int WINAPI LIBRARYID(){
	return IDR_LIB3D2;
}

KompasObject kompas( NULL );

char buf[MAX_TEXT_LENGTH];
void GetSetPartName( ksDocument3D& doc );
void FixAndStandartComponent( ksDocument3D& doc );
void GetSetColorProperty( ksDocument3D& doc );
void GetSetArrayVariable( ksDocument3D& doc );
void GetSetPlacmentComponent( ksDocument3D& doc );
void GetSetEntity( ksDocument3D& doc );
void CreateSketch( ksDocument3D& doc );
void GetArraySketch( ksDocument3D& doc );
void GetSetUserParamComponent( ksDocument3D& doc );
void UseEntityCollection();
void CreateDocument3D();
void DocIterator();

//-------------------------------------------------------------------------------
//
// ---
void GetKompas() {
	if ( !kompas.m_lpDispatch ) {
		CString filename;
		if( ::GetModuleFileName(NULL, filename.GetBuffer(255), 255) ) {
			filename.ReleaseBuffer( 255 );
			CString libname;

      #ifdef __LIGHT_VERSION__
        libname.LoadString( IDS_STRING5 );  //klAPI5.dll
      #else
        libname.LoadString( IDS_STRING4 );  //kAPI5.dll
      #endif
      
			filename.Replace( filename.Right(filename.GetLength() - (filename.ReverseFind('\\') + 1)), 
												libname );

			HINSTANCE hAppAuto = LoadLibrary( filename ); //  kAPI5.dll
			if(  hAppAuto ) {
				typedef LPDISPATCH ( WINAPI *FCreateKompasObject )(); 
				FCreateKompasObject pCreateKompasObject = 
					(FCreateKompasObject)GetProcAddress( hAppAuto, "CreateKompasObject" );	
				if ( pCreateKompasObject ) 
					kompas = pCreateKompasObject();
				FreeLibrary( hAppAuto );
			}
		}
	}
}

//-------------------------------------------------------------------------------
//
// ---
void WINAPI LIBRARYENTRY( unsigned int comm ) {
	//      .exe ,     
	//   dll   define
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	GetKompas();
	if ( kompas.m_lpDispatch ) {
    switch ( comm ) {
		  case 10 :  ::CreateDocument3D();     break;  //  
			case 11 :  ::DocIterator();          break;  //   
			case 12 :  ::UseEntityCollection();  break;  //   
      default : {
				ksDocument3D doc( kompas.ActiveDocument3D() );
				if ( doc.m_lpDispatch  ) {
					switch ( comm ) {
						case 1  : ::GetSetPartName( doc );	         break; // /  
						case 2  : ::FixAndStandartComponent( doc );	 break; //     
						case 3  : ::GetSetColorProperty( doc );      break; //      
						case 4  : ::GetSetArrayVariable( doc );  		 break; //      
						case 5  : ::GetSetPlacmentComponent( doc );	 break; //        
						case 6  : ::GetSetEntity( doc );             break; //   ksEntity        
						case 7  : ::CreateSketch( doc );             break; //  
						case 8  : ::GetArraySketch( doc );           break; //   ( )     ksEntityCollection ( IEntityCollection )
						case 9  : ::GetSetUserParamComponent( doc ); break; //       
					}
				}
			}
		}
	}
}

//-------------------------------------------------------------------------------
// /  
// ---
void GetSetPartName( ksDocument3D& doc ) {
  ksPart part( doc.GetPart(pTop_Part) ); //  
  if ( part.m_lpDispatch ) {
		::sprintf( buf, "  %s", part.GetName() );
		kompas.ksMessage( buf );
		part.SetName( "" );
		part.Update();
	}	 
}


//-------------------------------------------------------------------------------
//     
// ---
void FixAndStandartComponent( ksDocument3D& doc ) {
	if ( doc.IsDetail() ) {
		kompas.ksError("    ");
		return;
  }
  ksPart part( doc.GetPart(0) ); //    
	if ( part.m_lpDispatch ) {
		//     -       - fixedComponent
		int fix = part.GetFixedComponent();
		//     -       - standardComponent
		int stand = part.GetStandardComponent();
		kompas.ksMessage( fix ? " " : "  " );
		//     -       - fixedComponent
		part.SetFixedComponent(!fix);
		kompas.ksMessage( stand ? " " : " " );
		//     -       - standardComponent
		part.SetStandardComponent(!stand);
	}
}

//-------------------------------------------------------------------------------
//      
// ---
void GetSetColorProperty( ksDocument3D& doc ) {
  ksPart part( doc.GetPart(pTop_Part) ); //  
  if ( part.m_lpDispatch ) {
		ksColorParam colorPr( part.ColorParam() );
		if ( colorPr.m_lpDispatch ) {
			::sprintf( buf, "  = %d\n  = %g\n = %g\n  = %g\n = %g\n = %g\n = %g", 
				colorPr.GetColor(), colorPr.GetAmbient(), colorPr.GetDiffuse(), 
				colorPr.GetSpecularity(), colorPr.GetShininess(), 
				colorPr.GetTransparency(), colorPr.GetEmission() );
			kompas.ksMessage( buf );
			colorPr.SetColor(5421504);
			colorPr.SetTransparency(0.5);
			colorPr.SetAmbient(0.1);
			colorPr.SetDiffuse(0.1);
			part.Update();
			::sprintf( buf, "  = %d\n  = %g\n = %g\n  = %g\n = %g\n = %g\n = %g", 
				colorPr.GetColor(), colorPr.GetAmbient(), colorPr.GetDiffuse(), 
				colorPr.GetSpecularity(), colorPr.GetShininess(), 
				colorPr.GetTransparency(), colorPr.GetEmission() );
			kompas.ksMessage( buf );
		}
  }
//  K6 	//      
//  K6   double ambient, diffuse, specularity, shininess, transparency, emission;
//  K6 	long color;
//  K6 	part.GetAdvancedColor( &color, &ambient, &diffuse, &specularity, &shininess, &transparency, &emission );
//  K6 	::sprintf( buf, "  = %d\n  = %g\n = %g\n  = %g\n = %g\n = %g\n = %g", //"color = %d\nambient = %g\ndiffuse = %g\nspecularity = %g\nshininess = %g\ntransparency = %g\nemission = %g", 
//  K6 	           color, ambient, diffuse, specularity, shininess, transparency, emission );
//  K6 	kompas.ksMessage(buf);
//  K6 	color = 9421504; transparency = 0.5; ambient = 0.1; diffuse = 0.1;
//  K6 	part.SetAdvancedColor( color, ambient, diffuse, specularity, shininess, transparency, emission );
//  K6 	part.GetAdvancedColor( &color, &ambient, &diffuse, &specularity, &shininess, &transparency, &emission );
//  K6 	::sprintf( buf, "  = %d\n  = %g\n = %g\n  = %g\n = %g\n = %g\n = %g", //"color = %d\nambient = %g\ndiffuse = %g\nspecularity = %g\nshininess = %g\ntransparency = %g\nemission = %g", 
//  K6 	           color, ambient, diffuse, specularity, shininess, transparency, emission );
//  K6 	kompas.ksMessage(buf);
//  K6 	part.Update();
}


//-------------------------------------------------------------------------------
//      
// ---
void GetSetArrayVariable( ksDocument3D& doc ) {
	if ( doc.IsDetail() ) {
		kompas.ksError("    ");
		return;
  }
  ksPart part( doc.GetPart(0) ); //    
  if ( part.m_lpDispatch ) {
		//     
		ksVariableCollection varCol(part.VariableCollection() );
		if ( varCol.m_lpDispatch ) {
			ksVariable var;
			for ( int i = 0, count = varCol.GetCount(); i < count; i++ ) {
				var.AttachDispatch( varCol.GetByIndex(i) );
				::sprintf( buf, "       %d\n           %s\n   %g\n       %s", i, var.GetName(), var.GetValue(), var.GetNote() );
				kompas.ksMessage( buf );
				if ( i==0 ) {
					var.SetNote("qwerty");
					double d = 0;
					kompas.ksReadDouble( " ", 10, 0, 100, &d );
					var.SetValue(d);
				}
			}
			
			for ( int j = 0, count2 = varCol.GetCount(); j < count2; j++ ) { //   
				var.AttachDispatch( varCol.GetByIndex(j) );
				::sprintf( buf, "       %d\n           %s\n   %g\n       %s", j, var.GetName(), var.GetValue(), var.GetNote() );
				kompas.ksMessage( buf );
			}
			part.RebuildModel();  //  
		}
	}
}


//-------------------------------------------------------------------------------
//        
// ---
void GetSetPlacmentComponent( ksDocument3D& doc ) {
	if ( doc.IsDetail() ) {
		kompas.ksError("    ");
		return;
  }
  ksPart part( doc.GetPart(0) ); //    
  if ( part.m_lpDispatch ) {
		ksPlacement plac( part.GetPlacement() );
		if ( plac.m_lpDispatch ) {
			double x, y, z;
			plac.GetOrigin( &x, &y, &z );
			::sprintf( buf, "x = %g\ny = %g\nz = %g", x, y, z );
			kompas.ksMessage( buf );
			plac.SetOrigin( 20, 20, 20 );
			part.UpdatePlacement();
			part.Update();
		}
	}
}

//-------------------------------------------------------------------------------
//   ksEntity        
// ---
void GetSetEntity( ksDocument3D& doc ) {
  ksPart part( doc.GetPart(pTop_Part) ); //  
  if ( part.m_lpDispatch ) {
		ksEntity planeXOY( part.GetDefaultEntity(o3d_planeXOY) ); // 1-   XOY
		if ( planeXOY.m_lpDispatch ) {
			kompas.ksMessage( planeXOY.GetName() );
			planeXOY.SetName( "plane" );
			planeXOY.Update();
		}
	}
}

//-------------------------------------------------------------------------------
//  
// ---
void CreateSketch( ksDocument3D& doc ) {
  ksPart part( doc.GetPart(pTop_Part) ); //  
	if ( part.m_lpDispatch ) {
		ksEntity planeXOY( part.GetDefaultEntity(o3d_planeXOY) ); // 1-   XOY
//  	ASSERT(part.m_lpDispatch);  
		ksEntity entity( part.NewEntity(o3d_sketch) );
		if ( planeXOY.m_lpDispatch && entity.m_lpDispatch ) {
			ksSketchDefinition sketch( entity.GetDefinition() );
			if ( sketch.m_lpDispatch ) {
				sketch.SetPlane( planeXOY );
				entity.Create();
				ksDocument2D sketchDoc( sketch.BeginEdit() );//GetSketchEditor() );
  				sketchDoc.ksLineSeg( 0, 0, 100, 100, 1 );
				sketch.EndEdit();
			}
		}
	}
}

//-------------------------------------------------------------------------------
//   ( )     ksEntityCollection ( IEntityCollection )
// ---
void GetArraySketch( ksDocument3D& doc ) {
  ksPart part( doc.GetPart(pTop_Part) ); //  
  if ( part.m_lpDispatch ) {
		ksEntityCollection entityCollection( part.EntityCollection( o3d_sketch ) );
		ksEntity currentEntity;//( part.NewEntity(o3d_sketch) );
		if ( entityCollection.m_lpDispatch ) {
			for ( int k = 0; k < entityCollection.GetCount(); k++ ) {
				currentEntity.AttachDispatch( entityCollection.GetByIndex(k) );
				kompas.ksMessage( currentEntity.GetName() );
			}
		}
	}
}

//-------------------------------------------------------------------------------
//       
// ---
void GetSetUserParamComponent( ksDocument3D& doc ) {
	if ( doc.IsDetail() ) {
		kompas.ksError("    ");
		return;
  }
  ksPart part( doc.GetPart(0) ); //    
	ksUserParam par( kompas.GetParamStruct(ko_UserParam) );
  ksLtVariant item( kompas.GetParamStruct(ko_LtVariant) );
	ksDynamicArray arr( kompas.GetDynamicArray(LTVARIANT_ARR) );
	if ( !par.m_lpDispatch || !item.m_lpDispatch || !arr.m_lpDispatch || !part.m_lpDispatch )
		return;

	par.Init();
	par.SetUserArray( arr );
	item.Init();
	  item.SetDoubleVal( 12.12 );
	  arr.ksAddArrayItem( -1, item );
	item.Init();
  	item.SetDoubleVal( 21.21 );
		arr.ksAddArrayItem( -1, item );
  item.Init();
	  item.SetIntVal(666);
	  arr.ksAddArrayItem( -1, item );
  item.Init();
	  item.SetIntVal(999);
	  arr.ksAddArrayItem( -1, item );

	part.SetUserParam(par); //   
	part.Update();

	::sprintf( buf, "   %d", part.GetUserParamSize() ); //   
	kompas.ksMessage( buf );

	ksUserParam par2( kompas.GetParamStruct(ko_UserParam) );
  ksLtVariant item2( kompas.GetParamStruct(ko_LtVariant) );
	ksDynamicArray arr2( kompas.GetDynamicArray(LTVARIANT_ARR) );
	if ( !par2.m_lpDispatch || !item2.m_lpDispatch || !arr2.m_lpDispatch )
		return;

	par2.Init();
	par2.SetUserArray( arr2 );
	item2.Init();
	  item2.SetDoubleVal( 0 );
	  arr2.ksAddArrayItem( -1, item2 );
	item2.Init();
  	item2.SetDoubleVal( 0 );
		arr2.ksAddArrayItem( -1, item2 );
  item2.Init();
	  item2.SetIntVal( 0 );
	  arr2.ksAddArrayItem( -1, item2 );
  item2.Init();
	  item2.SetIntVal( 0 );
	  arr2.ksAddArrayItem( -1, item2 );

	part.GetUserParam( par2 ); //  e 
  
	struct {
		double a, b;
		int c, d;
	} d;
  arr2.ksGetArrayItem( 0, item2 );
	d.a = item2.GetDoubleVal();
  arr2.ksGetArrayItem( 1, item2 );
	d.b = item2.GetDoubleVal();
  arr2.ksGetArrayItem( 2, item2 );
	d.c = item2.GetIntVal();
  arr2.ksGetArrayItem( 3, item2 );
	d.d = item2.GetIntVal();
	::sprintf( buf, "  \na = %g\nb = %g\nc = %d\nd = %d", d.a, d.b, d.c, d.d );
	kompas.ksMessage( buf ); //     
}

//-------------------------------------------------------------------------------
//   
// ---
void CreateDocument3D() {
	ksDocument3D doc( kompas.Document3D() );
  if ( doc.Create(false/**/, true/**/) ) {
    doc.SetAuthor("");                //  
    doc.SetComment("  3D"); //   
		doc.SetFileName( "c:\\example.m3d" );  //   
    doc.UpdateDocumentParam();             //   
		doc.Save();                            //  
		kompas.ksMessage( "    " );
    doc.SaveAs( "c:\\example_1.m3d" );     //     

    char buf[256];
		//  
		sprintf( buf, " : %s", doc.GetAuthor() );
		kompas.ksMessage( buf);
		//   
		sprintf( buf, "  : %s", doc.GetComment() );
		kompas.ksMessage( buf);
    //  
		sprintf( buf, " : %s", doc.GetFileName() );
		kompas.ksMessage( buf);

		doc.close(); //  
	}
}

//-------------------------------------------------------------------------------
//        
// ---
void DocIterator() {
	char buf[256];
	ksDocument3D doc( NULL );
	ksDynamicArray arrDoc( kompas.GetDynamicArray(CHAR_STR_ARR) ); //      
	//        
  if ( arrDoc.m_lpDispatch && kompas.ksChoiceFiles( "*.m3d"," (*.m3d)|*.m3d|  (*.*)|*.*|", arrDoc, false) ) {
    ksChar255 item( kompas.GetParamStruct(ko_Char255) ); 
		if ( item.m_lpDispatch ) {
			//     
      for ( int i = 0, count = arrDoc.ksGetArrayCount(); i < count; i++ ) {
				if ( arrDoc.ksGetArrayItem(i, item) ) { 
					//          // 
					doc.AttachDispatch( kompas.Document3D() );
					doc.Open( item.GetStr(), false ); //      
				}
			}
		}

		//    
    ::sprintf( buf, " %i ", arrDoc.ksGetArrayCount() );
    kompas.ksMessage( buf ); 

		//    
		ksIterator iter( kompas.GetIterator() );
		if ( iter.m_lpDispatch ) {   //              
			if ( iter.ksCreateIterator(D3_DOCUMENT_OBJ, 0) ) {
				reference ref; //  
				if ( ref = iter.ksMoveIterator("F") ) { //     
					do { //     
						//   
						doc.AttachDispatch( kompas.ksGet3dDocumentFromRef(ref) );
						if ( doc.m_lpDispatch ) {
							//  
							sprintf( buf, " : %s", doc.GetAuthor() );
							kompas.ksMessage( buf);
							//   
							sprintf( buf, "  : %s", doc.GetComment() );
							kompas.ksMessage( buf);
							//    
							sprintf( buf, " : %s", doc.GetFileName() );
							kompas.ksMessage( buf);
							//  
							sprintf( buf, " : %s", doc.IsDetail() ? "" : "" );
							kompas.ksMessage( buf );
							//  
//							doc.DetachDispatch();
						}
					} while ( ref = iter.ksMoveIterator("N") );

				  iter.ksDeleteIterator(); //  
				}
			}
		}
	}
}


//-------------------------------------------------------------------------------
//   
// ---
void UseEntityCollection() {
  ksDocument3D doc( kompas.ActiveDocument3D() ); //    
	if ( doc.m_lpDispatch ) {
		ksPart part( doc.GetPart(pTop_Part) );       //  
		if ( part.m_lpDispatch ) {
			long count1 = 0;
			long count2 = 0; //   
			long count = 0;  //   

			//  
      ksEntityCollection collect( part.EntityCollection(o3d_face) );      
			if ( collect.m_lpDispatch ) {
				count = collect.GetCount();
				count1 = 0; 
				count2 = 0; 
				ksColorParam colorPr( NULL ); //   
				if ( collect.m_lpDispatch && count ) {
					for ( int i = 0; i < count; i++ ) {
						ksEntity ent( collect.GetByIndex(i) );
						colorPr.AttachDispatch( ent.ColorParam() );
						//   
						ksFaceDefinition faceDef( ent.GetDefinition() );
						if ( faceDef.m_lpDispatch ) {
						  // -       // -
							if ( faceDef.IsCone() || faceDef.IsCylinder() ) {      
								colorPr.SetColor( RGB(255, 255, 0) );  
								count2++;   //   
							}
              // -  
							if ( faceDef.IsPlanar() ) {
								colorPr.SetColor( RGB(0, 255, 255) ); 
								count1++;   //   
							}

//							colorPr.DetachDispatch();
							ent.Update(); //  
						}
					}
				}
			}

			//    
			if ( count == 0 ) 
				kompas.ksMessage( "    " );
			else {
        char buf[128];
				sprintf( buf, " %i   %i  ", count2, count1 );
				kompas.ksMessage( buf );
			}

			count1 = 0;
			count2 = 0;
			//  
      ksEntityCollection collect2( part.EntityCollection(o3d_edge) );      
			count = collect2.GetCount();
			if ( collect2.m_lpDispatch && count ) {
        for ( int i = 0; i < count; i++ ) {
					ksEntity ent( collect2.GetByIndex(i) );
					ksEdgeDefinition edgeDef( ent.GetDefinition() );
					if ( edgeDef.m_lpDispatch ) {
						if ( edgeDef.IsStraight() ) 
              count1++; //   
						else
              count2++; //   
					}
				}
			}

			//    
			if ( count == 0 ) 
				kompas.ksMessage( "    " );
			else {
        char buf[128];
				sprintf( buf, " %i   %i  ", count1, count2 );
				kompas.ksMessage( buf );
			}

		}
	}
}

