void OutputVertices( std::ofstream& in_mfw, CGeometryAccessor& in_ga, X3DObject& xobj)
{
	bar.PutStatusText( L"Vertices..." );
	
	// polygon vertex positions
	CDoubleArray vtxPosArray;
	CStatus st = in_ga.GetVertexPositions(vtxPosArray);
	st.AssertSucceeded( L"GetVertexPositions" );

	MATH::CTransformation localTransformation = xobj.GetKinematics().GetLocal().GetTransform();
	CString string = L"#begin " +  CString(in_ga.GetVertexCount()) + L" vertices\n";
	in_mfw << string.GetAsciiString();
	OutputArrayPositions( in_mfw, vtxPosArray, localTransformation );
	string = L"#end " +  CString(in_ga.GetVertexCount()) + L" vertices\n";
	in_mfw << string.GetAsciiString();
	in_mfw << "\n";

	if(Get3DCoatParam(L"bExpUV").GetValue())
	{
		// uv props: siClusterPropertyUVType
		CRefArray uvProps = in_ga.GetUVs();
		if(uvProps.GetCount() > 0)
		{
			OutputClusterPropertyValues( in_mfw, in_ga, uvProps );
		}
	}
	if(Get3DCoatParam(L"bExpNorm").GetValue())
	{

		// polygon node normals
		CFloatArray nodeArray;
		st = in_ga.GetNodeNormals(nodeArray);
		st.AssertSucceeded( L"GetNodeNormals" );

		//app.LogMessage(L"NormalArray: " + nodeArray.GetAsText());
		string = L"#begin " +  CString(in_ga.GetNodeCount()) + L" normals\n";
		in_mfw << string.GetAsciiString();
		OutputArray( in_mfw, nodeArray, 3,  L"vn " );
		string = L"#end " +  CString(in_ga.GetNodeCount()) + L" normals\n";
		in_mfw << string.GetAsciiString();
		in_mfw << "\n";
	}
}
XSIPLUGINCALLBACK CStatus Coat3DExport_Execute( CRef& in_ctxt )
{
	// Unpack the command argument values
	Context ctxt( in_ctxt );
	CValueArray args = ctxt.GetAttribute(L"Arguments");
	CString string;

	// A 3d object with a mesh geometry must be selected
	Selection selection(app.GetSelection());

	bool isPolymesh = true;
	for(int i =0; i< selection.GetCount(); i++)
	{
		X3DObject obj(selection[i]);
		//app.LogMessage(L"obj.IsA(siPolygonMeshID): " + CString(obj.GetType()));
		if(obj.GetType() != L"polymsh" )
		{
			isPolymesh = false;
			break;
		}
	}

	if (selection.GetCount() > 0 && isPolymesh)
	{
		gV = 0; gVn = 0; gVt = 0;
		gVprev = 0; gVnPrev = 0; gVtPrev = 0;
		// prepare the output text file
		CString strOut = Get3DCoatParam( L"tempLocation" ).GetValue();
		
		std::ofstream mfw;
		mfw.open(strOut.GetAsciiString(), std::ios_base::out | std::ios_base::trunc);
		if (mfw.is_open())
		{
			bar.PutMaximum( selection.GetCount() );
			bar.PutStep( 1 );
			bar.PutVisible( true );		

			OutputHeader( mfw);				
			// output the data
			for (int i=0; i < selection.GetCount(); i++)
			{
				gObjCnt = i;
				gVprev = gV;
				gVtPrev = gVt;
				gVnPrev = gVn;
				X3DObject xobj(selection.GetItem(i));

				bar.PutValue(i);
				bar.PutCaption( L"Exporting " + xobj.GetName());

				mfw << "\n";
				mfw << "# Hierarchy (from self to top father)\n";
				string = L"g " + xobj.GetName() + L"\n";
				mfw << string.GetAsciiString();
				mfw << "\n";

				// Get a geometry accessor from the selected object	
				Primitive prim = xobj.GetActivePrimitive();
				PolygonMesh mesh = prim.GetGeometry();
				if (!mesh.IsValid()) return CStatus::False;

				CGeometryAccessor ga = mesh.GetGeometryAccessor();

				OutputVertices( mfw, ga, xobj );
				if (bar.IsCancelPressed()) return CStatus::False;
				OutputPolygonComponents( mfw, ga );
				if (bar.IsCancelPressed()) return CStatus::False;
				//bar.Increment();		
			}
		}
		mfw.close();

		if(Get3DCoatParam(L"bExpMat").GetValue())
		{
			OutputMaterials(selection );
		}
		bar.PutStatusText( L"import.txt" );
		OutputImportTxt();
		bar.PutVisible(false);
                app.LogMessage(L"Export done!");
	}
	else
	{
		app.LogMessage(L"Please, select objects!", siWarningMsg);
		return CStatus::False;
	}

	return CStatus::OK;
}
void OutputPolygonComponents( std::ofstream& in_mfw, CGeometryAccessor& in_ga)
{
	// polygon node indices
	CLongArray polyNodeIdxArray;
	CStatus st = in_ga.GetNodeIndices(polyNodeIdxArray);
	st.AssertSucceeded( L"GetNodeIndices");
	
	//app.LogMessage(L"NodeIdx: " + polyNodeIdxArray.GetAsText());

	CLongArray polySizeArray;
	st = in_ga.GetPolygonVerticesCount(polySizeArray);
	st.AssertSucceeded( L"GetPolygonVerticesCount" );

	//app.LogMessage(L"GetPolygonVerticesCount: " + polySizeArray.GetAsText());

	// polygon vertex indices
	CLongArray polyVtxIdxArray;
	st = in_ga.GetVertexIndices(polyVtxIdxArray);
	st.AssertSucceeded( L"GetVertexIndices" );

	CString string = L"#begin " +  CString(in_ga.GetPolygonCount()) + L" faces\n";
	in_mfw << string.GetAsciiString();

	// get the material objects used by the mesh
	CRefArray materials = in_ga.GetMaterials();
	CRefArray uvProps = in_ga.GetUVs();

	// get the material indices used by each polygon
	CLongArray pmIndices;
	in_ga.GetPolygonMaterialIndices(pmIndices);

	CString prevMat = L"";
	CString curMat = L"";

	bar.PutMinimum(0);
	bar.PutMaximum(polySizeArray.GetCount());
	bar.PutStatusText(L"Faces...");

	bool bUV = (bool)Get3DCoatParam(L"bExpUV").GetValue();
	bool bNrm = (bool)Get3DCoatParam(L"bExpNorm").GetValue();
	bool bMtl = (bool)Get3DCoatParam(L"bExpMat").GetValue();
	bool bUVCnt	= (uvProps.GetCount() > 0)?true:false;
	CString strVertices;

	for (LONG i=0, offset=0; i < polySizeArray.GetCount(); i++)
	{	
		bar.PutValue(i);
		strVertices = "";
		strVertices += CString(polyVtxIdxArray[offset] + 1 + gVprev);// vertices idx[0]
		if(bUV && bUVCnt)
		{
			strVertices += L"/";
			//strVertices += CString(polyNodeIdxArray[offset] + 1 + gVtPrev);// texture nodes idx[0]
			strVertices += CString(g_aNodeIsland[offset] + 1 + gVtPrev);// texture nodes idx[0]
			
			if(bNrm)
			{
				strVertices += L"/";
				strVertices += CString(polyNodeIdxArray[offset] + 1 + gVnPrev);// normal vertices idx[0]
			}
		}
		else if(bNrm)
		{
			strVertices += L"//";
			strVertices += CString(polyNodeIdxArray[offset] + 1 + gVnPrev);// normal vertices idx[0]
		}

		for (LONG j=1; j<polySizeArray[i]; j++)
		{
			strVertices += L" ";
			strVertices += CString(polyVtxIdxArray[offset+j] + 1 + gVprev);// vertices idx[12]
			if(bUV && bUVCnt)
			{
				strVertices += L"/";
				//strVertices += CString(polyNodeIdxArray[offset+j] + 1 + gVtPrev);// texture nodes idx[12]
				strVertices += CString(g_aNodeIsland[offset+j] + 1 + gVtPrev);// texture nodes idx[0]
				
				if(bNrm)
				{
					strVertices += L"/";
					strVertices += CString(polyNodeIdxArray[offset+j] + 1 + gVnPrev);// normal vertices idx[12]
				}
			}
			else if(bNrm)
			{
				strVertices += L"//";
				strVertices += CString(polyNodeIdxArray[offset+j] + 1 + gVnPrev);// normal vertices idx[12]
			}
		}

		if(bMtl)
		{
			Material mat(materials[ pmIndices[i] ]);
			curMat = mat.GetName();
			if(curMat != prevMat)
			{
				in_mfw << "usemtl ";
				in_mfw << curMat.GetAsciiString();
				in_mfw << "\n";
				prevMat = curMat;
			}
		}

		in_mfw << "f ";
		in_mfw << strVertices.GetAsciiString();
		in_mfw << "\n";
		
		offset += polySizeArray[i];

		//bar.Increment();
	}
	string = L"#end " +  CString(in_ga.GetPolygonCount()) + L" faces\n";
	in_mfw << string.GetAsciiString();
	in_mfw << "\n";
}
void OutputClusterPropertyValues( std::ofstream& in_mfw,	CGeometryAccessor& in_ga, CRefArray& in_array)
{	
	LONG nVals = in_array.GetCount();
	double s;

	ClusterProperty cp(in_array[0]);

	CFloatArray valueArray;
	CBitArray flags;		
	cp.GetValues( valueArray, flags );

	LONG nValueSize = cp.GetValueSize();
	
	bar.PutValue(0);
	bar.PutStatusText(L"Optimize UV...");
	// polygon node indices
	CLongArray polyNodeIdxArray;
	CStatus st = in_ga.GetNodeIndices(polyNodeIdxArray);
	st.AssertSucceeded( L"GetNodeIndices");

	//app.LogMessage(L"polyNodeIdxArray: " + polyNodeIdxArray.GetAsText());
	g_aNodeIsland = polyNodeIdxArray;
	std::vector<float> newValueArray;
	newValueArray.clear();

	for ( LONG j=0; j < polyNodeIdxArray.GetCount(); j++)
	{	
		float u = valueArray[polyNodeIdxArray[j]*3];
		float v = valueArray[polyNodeIdxArray[j]*3+1];
		//app.LogMessage(L"u = " + CString(u)+ "; v = "+ CString(v));
		LONG nmb = 0;
		bool bIs = false;
		for ( ULONG k = 0; k < newValueArray.size(); k += 3 )
		{
			if(fabs(newValueArray.at(k) - u) < 0.000002 && fabs(newValueArray.at(k+1) - v) < 0.000002)
			{
				nmb = k/3;
				bIs = true;
				break;
				//app.LogMessage(L"Yarr!: g_aNodeIsland["+ CString(j)+"] = "+ CString(k/3));
			}
		}
		
		if(bIs)
		{
			g_aNodeIsland[j] = nmb;
			//app.LogMessage(L"Yarr!: g_aNodeIsland["+ CString(j)+"] = "+ CString(nmb));
		}
		else
		{
			newValueArray.push_back(u);
			newValueArray.push_back(v);
			newValueArray.push_back(0.0f);
			g_aNodeIsland[j] = (LONG)(newValueArray.size()/3-1);
			//app.LogMessage(L"g_aNodeIsland["+ CString(j)+"] = "+ CString(newValueArray.size()/3-1));
		}
	}

	in_mfw << "#begin ";
	in_mfw << CString((ULONG)newValueArray.size()/nValueSize).GetAsciiString();
	in_mfw << "\n";
	
	bar.PutStatusText(L"Clusters...");
	bar.PutMinimum(0);
	bar.PutMaximum((LONG)newValueArray.size()/nValueSize);
	for ( ULONG j=0; j < newValueArray.size(); j += nValueSize)
	{
		//bar.PutValue(j);
		s = newValueArray.at(j);
		CString strValues = FormatNumber(s);
		
		for ( LONG k=1; k<nValueSize; k++ )
		{
			s = newValueArray.at(j+k);
			strValues += L" " + FormatNumber(s);
		}
		
		in_mfw << "vt ";
		in_mfw << strValues.GetAsciiString();
		in_mfw << "\n";

		gVt++;
		bar.Increment();
	}
	CString string = L"#end " +  CString((ULONG)newValueArray.size()/nValueSize) + L"\n";
	in_mfw << string.GetAsciiString();
	in_mfw << "\n";
}
XSIPLUGINCALLBACK CStatus OutputMaterials( Selection& in_sel )
{
	// prepare the mtl file
	Project prj = app.GetActiveProject();
	Scene scn = prj.GetActiveScene();
	CString tmpLocation = Get3DCoatParam( L"tempLocation" ).GetValue();

	ULONG npos = tmpLocation.ReverseFindString(L".");
	CString substr = tmpLocation.GetSubString(0, npos+1);
	CString strOut = substr + L"mtl";	

	//app.LogMessage(L"strOut:" + strOut);

	std::ofstream matfw;
	matfw.open(strOut.GetAsciiString(), std::ios_base::out | std::ios_base::trunc);
	if (matfw.is_open())
	{
		CRefArray tempMats;

		for(int i=0; i< in_sel.GetCount(); i++)
		{
			X3DObject xobj(in_sel.GetItem(i));

			// Get a geometry accessor from the selected object	
			Primitive prim = xobj.GetActivePrimitive();
			PolygonMesh mesh = prim.GetGeometry();
			if (!mesh.IsValid()) return CStatus::False;

			CGeometryAccessor ga = mesh.GetGeometryAccessor();

			// get the material objects used by the mesh
			CRefArray materials = ga.GetMaterials();

			for (LONG n=0; n < materials.GetCount(); n++)
			{
				bar.PutStatusText( L"materials" );

				Material mat(materials[n]);
				bool inMats = false;
				//app.LogMessage(CString(n) +L" : "+ CString(i)+ L" :" + mat.GetName());

				for(int m = 0; m < tempMats.GetCount(); m++)
				{
					Material tmat(tempMats[m]);
					if(mat.GetName() == tmat.GetName())
					{
						inMats = true;
						break;
					}
				}

				//app.LogMessage(CString(inMats));

				if(!inMats)
				{
					CString string = L"newmtl " + mat.GetName() + L"\n";
					matfw << string.GetAsciiString();

					Parameter surf = mat.GetParameters().GetItem(L"surface");
					Shader lShader(surf.GetSource());
					//app.LogMessage(L"shader: " + lShader.GetFullName());
					//app.LogMessage(L"shader: " + lShader.GetProgID());
					if ( lShader.GetProgID() == L"Softimage.material-phong.1" )
					{
						float r, g, b, a;

						lShader.GetColorParameterValue(L"ambient", r, g, b, a );
						CString ka = L"Ka " + FormatNumber(r) + L" " + FormatNumber(g) + L" " + FormatNumber(b);
						lShader.GetColorParameterValue(L"diffuse", r, g, b, a );
						CString kd = L"Kd " + FormatNumber(r) + L" " + FormatNumber(g) + L" " + FormatNumber(b);
						lShader.GetColorParameterValue(L"specular", r, g, b, a );
						CString ks = L"Ks " + FormatNumber(r) + L" " + FormatNumber(g) + L" " + FormatNumber(b);
						float ns = lShader.GetParameterValue(L"shiny");
						float d = 1.0f;
						CValue illum = 2;

						matfw << ka.GetAsciiString();
						matfw << "\n";
						matfw << kd.GetAsciiString();
						matfw << "\n";
						matfw << ks.GetAsciiString();
						matfw << "\n";
						matfw << "Ns ";
						matfw << FormatNumber(ns).GetAsciiString();
						matfw << "\n";
						matfw << "d ";
						matfw << FormatNumber(d).GetAsciiString();
						matfw << "\n";
						matfw << "illum ";
						matfw << illum.GetAsText().GetAsciiString();
						matfw << "\n";

						Parameter diff = lShader.GetParameters().GetItem(L"diffuse");
						Shader lImageD(diff.GetSource());

						if (lImageD.GetProgID() == L"Softimage.txt2d-image-explicit.1")
						{
							Parameter tex = lImageD.GetParameters().GetItem(L"tex");
							ImageClip2 lTextureD(tex.GetSource());

							//app.LogMessage( L"Found texture shader: " + lTexture.GetFullName() + L", Class: " + lTexture.GetClassIDName() + L", Type: " + lTexture.GetType() );
							app.LogMessage(L"texture GetFileName: " + lTextureD.GetFileName());
							matfw << "map_Kd ";
							matfw << lTextureD.GetFileName().GetAsciiString();
							matfw << "\n";
						}

						Parameter spec = lShader.GetParameters().GetItem(L"specular");
						Shader lImageS(spec.GetSource());

						if (lImageS.GetProgID() == L"Softimage.txt2d-image-explicit.1")
						{
							Parameter tex = lImageD.GetParameters().GetItem(L"tex");
							ImageClip2 lTextureS(tex.GetSource());

							//app.LogMessage( L"Found texture shader: " + lTexture.GetFullName() + L", Class: " + lTexture.GetClassIDName() + L", Type: " + lTexture.GetType() );
							//app.LogMessage(L"texture GetFileName: " + lTexture.GetFileName());
							matfw << "map_Ks ";
							matfw << lTextureS.GetFileName().GetAsciiString();
							matfw << "\n";
						}
					}
					tempMats.Add(mat);
					matfw << "\n";
					matfw << "\n";
				}
			}		
		}
		matfw.close();
	}
	return CStatus::OK;
}