//---------------------------------------------------------------------------
// For SELMA200, 20180227, moon, 완료 및 예정
// 카메라 인덱스 변경에 따른 다국어 ID 값 변경(*.dat)
//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Calibration3D_Form.h"
#include "Environment.h"
#include "CameraSetting3D_Form.h"
#include "Message_Form.h"
#include "Waiting_Form.h"
#include "MachineControl.h"
#include "MultiLanguage.h"
#include "StudySpeedControl_Form.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "CGAUGES"
#pragma link "TntExtCtrls"
#pragma link "TntForms"
#pragma link "TntStdCtrls"
#pragma resource "*.dfm"
TCalibration3DForm *Calibration3DForm;

#define FIRST_3D_CAM_INDEX			4
#define SECOND_3D_CAM_INDEX			12

#define SELECTION_IMAGE_MARGIN_LEFT 	10
#define SELECTION_IMAGE_MARGIN_TOP 		10
//---------------------------------------------------------------------------
__fastcall TCalibration3DForm::TCalibration3DForm(TComponent* Owner)
	: TTntForm(Owner)
{
	if (DefaultLCID == 1028 || DefaultLCID == 2052 || DefaultLCID == 3076 || DefaultLCID == 4100)
		ComponentSetFontName(this, "SimSun");
  else if(DefaultLCID == 1041)
    ComponentSetFontName(this, "Meiryo UI");
  else if(DefaultLCID == 3082)
  {
    ComponentSetFontName(this, "Segoe UI");
    ComponentSetMultiLine(this);
  }

	GetDefaultString();
	CalibrationStep_3D[0] = ECS3_NONE;
	CalibrationStep_3D[1] = ECS3_NONE;
	CaptureData = NULL;

  IncreaseSpeed = 2000; // FIX

  Camera5_SetCheckLabel->Caption = "CAM : " + IntToStr(SD1_3D_FRONT_FACE_CAMERA_INDEX);
  Camera13_SetCheckLabel->Caption = "CAM : " + IntToStr(SD2_3D_FRONT_FACE_CAMERA_INDEX);

  // View image Panel Default Set
  for(int i = 0; i < 16 ; ++i)
  {
    TTntImage *tempImage = (TTntImage *)FindComponent("ViewImage5_" + IntToStr(i + 1));

    tempImage->Width = 160;
    tempImage->Height = 120;
    tempImage->Picture->Bitmap->Width = IMAGE_WIDTH_3D;
    tempImage->Picture->Bitmap->Height = IMAGE_HEIGHT_3D;
    tempImage->Picture->Bitmap->PixelFormat = pf8bit;
    Set3DPalette(tempImage->Picture->Bitmap);

    TTntImage *tempImage2 = (TTntImage *)FindComponent("ViewImage13_" + IntToStr(i + 1));

    tempImage2->Width = 160;
    tempImage2->Height = 120;
    tempImage2->Picture->Bitmap->Width = IMAGE_WIDTH_3D;
    tempImage2->Picture->Bitmap->Height = IMAGE_HEIGHT_3D;
    tempImage2->Picture->Bitmap->PixelFormat = pf8bit;
    Set3DPalette(tempImage2->Picture->Bitmap);
  }

  StartShutterSpeedEdit->Text = "40000"; //IntToStr(ThreeDCameraDefaultInformation[4].ExposureTime);

  if(StartShutterSpeedEdit->Text.Length() != 0)
  {
    EndShutterSpeedLabel->Caption = "~  "+ IntToStr(40000+(IncreaseSpeed*(PARAM_GRADE_EXP_COUNT-1)));
  }
}
//---------------------------------------------------------------------------
void __fastcall TCalibration3DForm::GetDefaultString()
{
	ImageSelectionNextButton->Caption = CALIBRATION3DFORM_BUTTON_CAPTION_01;
	CloseButton->Caption = CALIBRATION3DFORM_BUTTON_CAPTION_02;
  ReturnButton->Caption = CALIBRATION3DFORM_BUTTON_CAPTION_02;
	CaptureStartButton->Caption = CALIBRATION3DFORM_BUTTON_CAPTION_04;
	CaptureStopButton->Caption = CALIBRATION3DFORM_BUTTON_CAPTION_05;
	ImageSelectionPrevButton->Caption = CALIBRATION3DFORM_BUTTON_CAPTION_06;
	ImageSelectionButton->Caption = CALIBRATION3DFORM_BUTTON_CAPTION_07;
	ImageSelectionCam5Panel->Caption = CALIBRATION3DFORM_PANEL_CAPTION_01;
	ImageSelectionCam13Panel->Caption = CALIBRATION3DFORM_PANEL_CAPTION_02;
  SelectCameraParamButton->Caption = IMAGECAPTURE3D_BITBTN_CAPTION_01;
  ReCaptureBtn->Caption =IMAGECAPTURE3D_BITBTN_CAPTION_02;
  SpeedBtn->Caption = INSPECTIONFORM_BUTTON_CAPTION_08;
}
//---------------------------------------------------------------------------
void __fastcall TCalibration3DForm::CaptureStartButtonClick(
	TObject *Sender)
{
  if(MachineSetupData.CompanyID == INTERNATIONAL_MACHINE1)
  {
    if (!Machine.InterlockCheck())
    {
      ShowMessageFA(Machine.GetInterlockMessage());
      return;
    }
  }
  
  if (Machine.Status.OperationState != MACHINE_STATE_STOP &&
			Machine.Status.OperationState != MACHINE_STATE_CLEANING &&
			Machine.Status.OperationState != MACHINE_STATE_ATTACHING &&
			Machine.Status.OperationState != MACHINE_STATE_DETACHING)
  {
    Machine.MachineStop();
    ShowMessageFA(INSPECTIONFORM_MSG_23);
    return;
  }
  
	camMask = 0;
	bool bError = false;
  CaptureEndCheckCount = 0;

  CapturePanelBaseNumber = 0;
  // View image Panel Empty Image Set
  for(int i = 0; i < 16 ; ++i)
  {
     if(i<4)
    {
      TTntGroupBox * tempGroupBox =  (TTntGroupBox*)FindComponent("ViewGroupBox5_" + IntToStr(i + 1) );
      if(tempGroupBox)
        tempGroupBox->Caption = "Gain : X Ex : X";
      TTntGroupBox * tempGroupBox2 =  (TTntGroupBox*)FindComponent("ViewGroupBox13_" + IntToStr(i + 1) );
      if(tempGroupBox2)
        tempGroupBox2->Caption = "Gain : X Ex : X";
    }

    TTntImage *tempImage = (TTntImage *)FindComponent("ViewImage5_" + IntToStr(i + 1));

    tempImage->Canvas->Brush->Color = clBlue;
	  tempImage->Canvas->Brush->Style = bsSolid;
	  tempImage->Canvas->FillRect(Rect(0, 0, tempImage->Picture->Bitmap->Width, tempImage->Picture->Bitmap->Height));

    TTntImage *tempImage2 = (TTntImage *)FindComponent("ViewImage13_" + IntToStr(i + 1));

    tempImage2->Canvas->Brush->Color = clBlue;
	  tempImage2->Canvas->Brush->Style = bsSolid;
	  tempImage2->Canvas->FillRect(Rect(0, 0, tempImage2->Picture->Bitmap->Width, tempImage2->Picture->Bitmap->Height));
  }

  Camera5_SetCheckPanel->Color = clRed;
  Camera13_SetCheckPanel->Color = clRed;

  memset(SaveDataFlag,0,sizeof(bool)*2);

  memset(CaptureStep,0,sizeof(int)*2);
  memset(GroupStep,0,sizeof(int)*2);

	CaptureMessagePanel->BringToFront();

  for(int i = 0; i < PARAM_GRADE_GAIN_COUNT ; ++i)
  {
    for (int camIndex_3D = 0; camIndex_3D < MAX_3D_CAMERA_COUNT; camIndex_3D++)
	  {
      PreSetGainList[camIndex_3D][i] = i;
    }
  }
  for(int i = 0; i < PARAM_GRADE_EXP_COUNT ; ++i)
  {
    for (int camIndex_3D = 0; camIndex_3D < MAX_3D_CAMERA_COUNT; camIndex_3D++)
	  {
      PreSetExposureTimeList[camIndex_3D][i] = StrToInt(StartShutterSpeedEdit->Text)+ (i*IncreaseSpeed);
    }
  }
  // 사용자가 지정한 셔터 스피드 값으로 초기화

	for (int camIndex_3D = 0; camIndex_3D < MAX_3D_CAMERA_COUNT; camIndex_3D++)
	{
		CurrentExposureTime[camIndex_3D] = PreSetExposureTimeList[camIndex_3D][0];
    CurrentGain[camIndex_3D]= PreSetGainList[camIndex_3D][0];
		//CurrentThreshold[camIndex_3D] = PreSetThresholdList[camIndex_3D][0];
	}


  if (CameraMapInfo[FIRST_3D_CAM_INDEX].CameraInspectPosition != CAMERA_POSITION_DISCONNECT &&
  CameraMapInfo[FIRST_3D_CAM_INDEX].CameraInspectPosition == CAMERA_POSITION_3D && SystemLinkCameraInfo[FIRST_3D_CAM_INDEX] != 0 )
  {
    camMask |= (0x0001 << FIRST_3D_CAM_INDEX);
    Set3DCamera_CaptureParameter(FIRST_3D_CAM_INDEX,CurrentGain[0], CurrentExposureTime[0]);
  }
  if (CameraMapInfo[SECOND_3D_CAM_INDEX].CameraInspectPosition != CAMERA_POSITION_DISCONNECT &&
  CameraMapInfo[SECOND_3D_CAM_INDEX].CameraInspectPosition == CAMERA_POSITION_3D && SystemLinkCameraInfo[SECOND_3D_CAM_INDEX] != 0)
  {
    camMask |= (0x0001 << SECOND_3D_CAM_INDEX);
    Set3DCamera_CaptureParameter(SECOND_3D_CAM_INDEX,CurrentGain[1],CurrentExposureTime[1]);
  }

  if(camMask == 0)
  {
    ShowMessageFA("No 3D cameras are available.");
    return;
  }

	try
	{
		float tabletHalfLength = ProductData.TabletLength / 2;

		if (SendSPBCaptureSetup_Multi(&ProductData,camMask, tabletHalfLength, ProductData.ShutterSpeed,
			ProductData.StudyMotorSpeedList[SD1_MOTOR_INDEX][0], MachineSetupData.ServoMotorData[SD1_MOTOR_INDEX].BaseSpeed,
			ProductData.StudyMotorSpeedList[SD2_MOTOR_INDEX][0], MachineSetupData.ServoMotorData[SD2_MOTOR_INDEX].BaseSpeed,
      ProductData.SubSamplingMode, false))
		{
			if (CameraMapInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX-1].CameraInspectPosition == CAMERA_POSITION_DISCONNECT ||
      CameraMapInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX-1].CameraInspectPosition == CAMERA_POSITION_DISCONNECT ||
      SystemLinkCameraInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX-1] == 0 ||
      SystemLinkCameraInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX-1] == 0 )
		  {
        CaptureProcessGauge->MaxValue = 300;//200;
		  }
      else
      {
        CaptureProcessGauge->MaxValue = 600;//400;
      }
			CaptureCheckTimer->Enabled = true;
		}
		else
		{
			throw Exception("");
		}

		TMachineCaptureSetupData machineCaptureSetupData;

		memcpy(machineCaptureSetupData.IlluminatorMask, MachineSetupData.MachineCaptureInfo.IlluminatorMask, SYSTEM_MACHINE_CAPTURE_COUNT * sizeof(int));
		machineCaptureSetupData.TabletLength = ProductData.TabletLength;
		machineCaptureSetupData.TabletSideThick = ProductData.TabletSideThick*10;
		machineCaptureSetupData.SuctionDiskSpeed = ProductData.StudyMotorSpeedList[0][0];
		machineCaptureSetupData.StudiedTabletSensorLength = ProductData.StudiedSensor1Length;
    machineCaptureSetupData.CaptureOption = 2;
		if (!Comm_Request(COMM_HCB, CMD_MACHINE_CAPTURE, &machineCaptureSetupData, sizeof(TMachineCaptureSetupData),
			NULL, 0))
		{
			throw Exception("");
		}

		int motorSpeedList[MAX_SERVO_MOTOR_COUNT];
		for (int motorIndex = 0; motorIndex < MAX_SERVO_MOTOR_COUNT; motorIndex++)
		{
			motorSpeedList[motorIndex] = ProductData.StudyMotorSpeedList[motorIndex][0];
		}

		if (!Machine.MachineRun(PROCEDURE_MODE_CAPTURE, &ProductData.MachineRunOption,
			ProductData.NCMotorPos, motorSpeedList))
		{
			throw Exception("");
		}

		CaptureStopButton->Enabled = true;
		CaptureStartButton->Enabled = false;
		CaptureProgressPanel->Visible = true;
    RadioButton1->Enabled = false;
    RadioButton2->Enabled = false;
    SpeedBtn->Enabled = false;
    CloseButton->Enabled = false;
    CaptureMessagePanel->BringToFront();
		CaptureProcessGauge->Progress = 0;
		CaptureProcessGauge->BackColor = clWhite;
		CaptureProcessGauge->ForeColor = clBlue;
		//CaptureProgressLabel->Caption = IntToStr(CaptureProcessGauge->Progress) + "/" + IntToStr(CaptureProcessGauge->MaxValue);

		CurrentExposureTimeGrade[0] = CurrentExposureTimeGrade[1] = 0;
    CurrentGainGrade[0] = CurrentGainGrade[1] = 0;
		CurrentCapturedCount[0] = CurrentCapturedCount[1] = 0;
		TotalCapturedCount[0] = TotalCapturedCount[1] = 0;
		CalibrationStep_3D[0] = CalibrationStep_3D[1] = ECS3_ON_CAPTURE;
	}
	catch (...)
	{
		CaptureCheckTimer->Enabled = false;
		CalibrationStep_3D[0] = CalibrationStep_3D[1] = ECS3_NONE;
	}
}
//---------------------------------------------------------------------------
void __fastcall TCalibration3DForm::CaptureCheckTimerTimer(TObject *Sender)
{
	bool bCaptureExist;
	// check capture exists
	char cameraIndex;
	unsigned int data[2];
	unsigned int receivedData[2];

	int cameraGlobalIndex[MAX_3D_CAMERA_COUNT];
	int CaptureWidth_3D, CaptureHeight_3D;

	bool timerEnabled = CaptureCheckTimer->Enabled;
	CaptureCheckTimer->Enabled = false;

	cameraGlobalIndex[0] = FIRST_3D_CAM_INDEX;
	cameraGlobalIndex[1] = SECOND_3D_CAM_INDEX;
	CaptureWidth_3D = SYSTEM_CAMERA_WIDTH_3D;
	CaptureHeight_3D = SYSTEM_CAMERA_HEIGHT_3D;

	for (int cameraIndex_3D = 0; cameraIndex_3D < MAX_3D_CAMERA_COUNT; cameraIndex_3D++)
	{
    if (CameraMapInfo[cameraGlobalIndex[cameraIndex_3D]].CameraInspectPosition == CAMERA_POSITION_DISCONNECT || SystemLinkCameraInfo[cameraGlobalIndex[cameraIndex_3D]] == 0)
		{
      CalibrationStep_3D[cameraIndex_3D] = ECS3_NONE;
      continue;
		}
    else
    {
      TntLabel3->Caption = "[3D Cam 5]";
      TntLabel4->Caption = "[3D Cam 13]";

      if (CalibrationStep_3D[cameraIndex_3D] == ECS3_ON_CAPTURE)
      {

        int globalCameraIndex = cameraGlobalIndex[cameraIndex_3D];
        int spbIndex = CameraMapInfo[globalCameraIndex].SPBIndex;
        int camIndex = CameraMapInfo[globalCameraIndex].CamIndex;
        data[0] = camIndex;

        try
        {
          if (!Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_EXIST, data, sizeof(unsigned int),
            receivedData, sizeof(unsigned int) * 2))
          {
            throw Exception("");
          }

          int systemCapturedImageCount = receivedData[0];


          if (systemCapturedImageCount > 0)
          {
            bCaptureExist = true;
          }
          else
          {
            bCaptureExist = false;
          }
          if (bCaptureExist)
          {
            data[1] = CaptureWidth_3D * CaptureHeight_3D;
            if (!Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_UPLOAD, data, 2 * sizeof(unsigned int),
              CaptureData, CaptureWidth_3D * CaptureHeight_3D))
            {
              throw Exception("");
            }

            CaptureBitmap->PixelFormat = pf8bit;
            CaptureBitmap->Width = IMAGE_WIDTH_3D;
            CaptureBitmap->Height = IMAGE_HEIGHT_3D;
            SetGrayPalette(CaptureBitmap);

            ImageConversion_3D(CaptureSaveBitmap, IMAGE_WIDTH_3D, IMAGE_HEIGHT_3D, CaptureData, CaptureWidth_3D, CaptureHeight_3D);
            ImageConversion_3D(CaptureBitmap, IMAGE_WIDTH_3D, IMAGE_HEIGHT_3D, CaptureData, CaptureWidth_3D, CaptureHeight_3D);

            //AnsiString imageDir = GetProductImagePath();
            AnsiString imageDir = GetProductImagePath();
            if (!DirectoryExists(imageDir))
            {
              ForceDirectories(imageDir);
            }
            if (!DirectoryExists(imageDir+"\\Calib3D"))
            {
              ForceDirectories(imageDir+"\\Calib3D");
            }

            // 이미지 저장 이름
            // Gain + Exposuretime ~
            CaptureSaveBitmap->SaveToFile(imageDir + "\\Calib3D\\Image_"+ IntToStr(CurrentGain[cameraIndex_3D])+"_"+ IntToStr(CurrentExposureTime[cameraIndex_3D]) +
              "_" + IntToStr(CurrentCapturedCount[cameraIndex_3D]+1) + "_" + IntToStr(globalCameraIndex + 1) + ".bmp");

            // 패널 구분

            int SelectNextGroupBox = (CaptureStep[cameraIndex_3D]) /4; // +1

            if((CaptureStep[cameraIndex_3D] % 4)==0) 
            {
              if(SelectNextGroupBox > 0 )
              {
                if(GroupStep[cameraIndex_3D]+1 == 4)
                  GroupStep[cameraIndex_3D] = 0;
                else
                  ++GroupStep[cameraIndex_3D];

                 CapturePanelBaseNumber = CaptureStep[cameraIndex_3D];

                TTntGroupBox * tempGroupBox =  (TTntGroupBox*)FindComponent("ViewGroupBox" + IntToStr(globalCameraIndex + 1) + "_"+ IntToStr(CaptureStep[cameraIndex_3D] + 1 - CapturePanelBaseNumber + GroupStep[cameraIndex_3D]) );
                if(tempGroupBox)
                {
                  if(globalCameraIndex == 4)
                    tempGroupBox->Caption = "Gain: " + IntToStr(CurrentGain[0])+", Exposure: "+ IntToStr(CurrentExposureTime[0]);
                  else
                    tempGroupBox->Caption = "Gain: " + IntToStr(CurrentGain[1])+", Exposure: "+ IntToStr(CurrentExposureTime[1]);
                }
              }
              else
              {
                if(CaptureStep[cameraIndex_3D] == 0)
                {
                  TTntGroupBox * tempGroupBox =  (TTntGroupBox*)FindComponent("ViewGroupBox" + IntToStr(globalCameraIndex + 1) + "_"+ IntToStr(CaptureStep[cameraIndex_3D] + 1 - CapturePanelBaseNumber) );
                  if(tempGroupBox)
                  {
                    if(globalCameraIndex == 4)
                      tempGroupBox->Caption = "Gain: " + IntToStr(CurrentGain[0])+", Exposure: "+ IntToStr(CurrentExposureTime[0]);
                    else
                      tempGroupBox->Caption = "Gain: " + IntToStr(CurrentGain[1])+", Exposure: "+ IntToStr(CurrentExposureTime[1]);
                  }
                }
              }

            }

            TTntImage *tempImage = (TTntImage *)FindComponent("ViewImage" + IntToStr(globalCameraIndex + 1) + "_"+ IntToStr(CaptureStep[cameraIndex_3D] + 1 - CapturePanelBaseNumber + (GroupStep[cameraIndex_3D] * 4)) );

            if(tempImage)
            {
              for (int y = 0; y < tempImage->Picture->Bitmap->Height; y++)
              {
                byte *pSrc = (byte *)CaptureBitmap->ScanLine[y];
                byte *pDst = (byte *)tempImage->Picture->Bitmap->ScanLine[y];
                for (int x = 0; x < tempImage->Picture->Bitmap->Width; x++)
                {
                  pDst[x] = pSrc[x];
                }
              }
              tempImage->Repaint();
            }

            CurrentCapturedCount[cameraIndex_3D]++;
            CaptureStep[cameraIndex_3D]++;
            CaptureProcessGauge->Progress++;

            if (CurrentCapturedCount[cameraIndex_3D] == MAX_IMAGE_COUNT_PER_GRADE) // 해당 해당 게인+셔터스피드 조합의 사진을 8 장을 다찍었다.
            {
              if(CurrentExposureTimeGrade[cameraIndex_3D] != PARAM_GRADE_EXP_COUNT-1)
              {
                CurrentExposureTimeGrade[cameraIndex_3D]++;

                CurrentExposureTime[cameraIndex_3D] = PreSetExposureTimeList[cameraIndex_3D][CurrentExposureTimeGrade[cameraIndex_3D]];

                CurrentCapturedCount[cameraIndex_3D] = 0;
                Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_STOP, &camIndex, sizeof(int));

                Set3DCamera_CaptureParameter(cameraGlobalIndex[cameraIndex_3D],CurrentGain[cameraIndex_3D] ,CurrentExposureTime[cameraIndex_3D]);


                SetParamTime[cameraIndex_3D] = GetTickCount();
                CalibrationStep_3D[cameraIndex_3D] = ECS3_SETTING_PARAM;
              }
              else
              {
                if(CurrentGainGrade[cameraIndex_3D]!=PARAM_GRADE_GAIN_COUNT-1)
                {
                  CurrentGainGrade[cameraIndex_3D]++;
                  CurrentExposureTimeGrade[cameraIndex_3D] = 0;

                  CurrentExposureTime[cameraIndex_3D] = PreSetExposureTimeList[cameraIndex_3D][CurrentExposureTimeGrade[cameraIndex_3D]];

                  CurrentCapturedCount[cameraIndex_3D] = 0;
                  Comm_Request(COMM_SPB + spbIndex, CMD_CAPTURE_STOP, &camIndex, sizeof(int));

                  Set3DCamera_CaptureParameter(cameraGlobalIndex[cameraIndex_3D],PreSetGainList[cameraIndex_3D][CurrentGainGrade[cameraIndex_3D]],CurrentExposureTime[cameraIndex_3D]);
                  CurrentGain[cameraIndex_3D] =  PreSetGainList[cameraIndex_3D][CurrentGainGrade[cameraIndex_3D]];

                  SetParamTime[cameraIndex_3D] = GetTickCount();
                  CalibrationStep_3D[cameraIndex_3D] = ECS3_SETTING_PARAM;

                }
                else // 이미지 촬영 끝
                {
                  CalibrationStep_3D[cameraIndex_3D] = ECS3_NONE;
                  CaptureEndCheckCount++;
                }
              }
            }
          }
        }
        catch (Exception &ec)
        {
          timerEnabled = false;
          if (ec.Message != "")
          {
            ShowMessageFA(ec.Message);
          }
        }
      }
      else if (CalibrationStep_3D[cameraIndex_3D] == ECS3_SETTING_PARAM)
      {
        if(CalibrationStep_3D[cameraIndex_3D] ==ECS3_SETTING_PARAM)
        {
          if((CalibrationStep_3D[0] == ECS3_SETTING_PARAM|| CalibrationStep_3D[0] == ECS3_NONE )&&
          (CalibrationStep_3D[1] == ECS3_SETTING_PARAM|| CalibrationStep_3D[1] == ECS3_NONE))
          {
            if (GetTickCount() - SetParamTime[0] > 1000 && GetTickCount() - SetParamTime[1] > 1000)//CAMERA_SETUP_3D_WAITING_TIME)
            {
              if (!Comm_Request(COMM_HCB, CMD_MACHINE_CAPTURE_STOP))
              {

              }

              if(CalibrationStep_3D[0] == ECS3_NONE)
              {
                camMask &= ~ FIRST_3D_CAM_INDEX;
              }
              else
                CalibrationStep_3D[0] = ECS3_ON_CAPTURE;
                
              if(CalibrationStep_3D[1] == ECS3_NONE)
              {
                camMask &= ~ SECOND_3D_CAM_INDEX;
              }
              else
                 CalibrationStep_3D[1] = ECS3_ON_CAPTURE;
              
              float tabletHalfLength = ProductData.TabletLength / 2;

             if (SendSPBCaptureSetup_Multi(&ProductData,camMask, tabletHalfLength, ProductData.ShutterSpeed,
              ProductData.StudyMotorSpeedList[SD1_MOTOR_INDEX][0], MachineSetupData.ServoMotorData[SD1_MOTOR_INDEX].BaseSpeed,
              ProductData.StudyMotorSpeedList[SD2_MOTOR_INDEX][0], MachineSetupData.ServoMotorData[SD2_MOTOR_INDEX].BaseSpeed,ProductData.SubSamplingMode, false))
              {

              }

              TMachineCaptureSetupData machineCaptureSetupData;

              memcpy(machineCaptureSetupData.IlluminatorMask, MachineSetupData.MachineCaptureInfo.IlluminatorMask, SYSTEM_MACHINE_CAPTURE_COUNT * sizeof(int));
              machineCaptureSetupData.TabletLength = ProductData.TabletLength;
		 machineCaptureSetupData.TabletSideThick = ProductData.TabletSideThick*10;
              machineCaptureSetupData.SuctionDiskSpeed = ProductData.StudyMotorSpeedList[0][0];
              machineCaptureSetupData.StudiedTabletSensorLength = ProductData.StudiedSensor1Length;
              machineCaptureSetupData.CaptureOption = 2;
              if (!Comm_Request(COMM_HCB, CMD_MACHINE_CAPTURE, &machineCaptureSetupData, sizeof(TMachineCaptureSetupData),
                NULL, 0))
              {
                throw Exception("");
              }
            }
          }
        }
      }
    }

	}

	if (CaptureProcessGauge->Progress == CaptureProcessGauge->MaxValue)		// system all captured
	{
		if (!Comm_Request(COMM_HCB, CMD_MACHINE_CAPTURE_STOP))
		{

		}

		Machine.MachineStop();

    timerEnabled = false;
		ShowMessageFA(CALIBRATION3DFORM_MSG_06);
		CaptureStopButton->Enabled = false;
		CaptureStartButton->Enabled = true;
		ImageSelectionButton->Enabled = true;
    RadioButton1->Enabled = true;
    RadioButton2->Enabled = true;
    CloseButton->Enabled = true;
    SpeedBtn->Enabled = true;
    LastCaptureShutterSpeed = StrToInt(StartShutterSpeedEdit->Text);
    LastIncreaseSpeed = IncreaseSpeed;
	}

	CaptureCheckTimer->Enabled = timerEnabled;
}
//---------------------------------------------------------------------------
void __fastcall TCalibration3DForm::FormCreate(TObject *Sender)
{
	AnsiString ImageComponentName[MAX_3D_CAMERA_COUNT][4] =
	{
	 "CaptureImage5_1", "CaptureImage5_2", "CaptureImage5_3", "CaptureImage5_4",
	 "CaptureImage13_1", "CaptureImage13_2", "CaptureImage13_3", "CaptureImage13_4",
	};


	try
	{
		CaptureData = new char[SYSTEM_CAMERA_WIDTH_3D * SYSTEM_CAMERA_HEIGHT_3D];
		if (CaptureData == NULL) throw Exception("Out of memory.");
		CaptureBitmap = new Graphics::TBitmap;
		CaptureBitmap->Width = IMAGE_WIDTH_3D;
		CaptureBitmap->Height = IMAGE_HEIGHT_3D;
		CaptureBitmap->PixelFormat = pf8bit;
		SetGrayPalette(CaptureBitmap);

    CaptureSaveBitmap = new Graphics::TBitmap;
		CaptureSaveBitmap->Width = IMAGE_WIDTH_3D;
		CaptureSaveBitmap->Height = IMAGE_HEIGHT_3D;
		CaptureSaveBitmap->PixelFormat = pf8bit;
		SetGrayPalette(CaptureSaveBitmap);

		for (int cameraIndex_3D = 0; cameraIndex_3D < MAX_3D_CAMERA_COUNT; cameraIndex_3D++)
		{
			for (int gradeIndex = 0; gradeIndex < 4; gradeIndex++)
			{
				TTntImage *anImage = (TTntImage *)FindComponent(ImageComponentName[cameraIndex_3D][gradeIndex]);
        anImage->Width = IMAGE_WIDTH_3D * 2 / 2;
        anImage->Height = IMAGE_HEIGHT_3D / 2;
        anImage->Picture->Bitmap->Width = IMAGE_WIDTH_3D;
        anImage->Picture->Bitmap->Height = IMAGE_HEIGHT_3D;
        anImage->Picture->Bitmap->PixelFormat = pf24bit;
        Set3DPalette(anImage->Picture->Bitmap);
        /*

				anImage->Picture->Bitmap->Width = IMAGE_WIDTH_3D;
				anImage->Picture->Bitmap->Height = IMAGE_HEIGHT_3D;
				anImage->Picture->Bitmap->PixelFormat = pf8bit;
				SetGrayPalette(anImage->Picture->Bitmap);
				anImage->Stretch = true;
				anImage->Proportional = false;
				anImage->Width = IMAGE_WIDTH_3D;
				anImage->Height = IMAGE_HEIGHT_3D / 2;                 */
        ImagePanelList[cameraIndex_3D][gradeIndex] = anImage;
			}
		}
	}
	catch (Exception &ec)
	{
		ShowMessageFA(ec.Message);
	}

  if(CameraMapInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition == CAMERA_POSITION_DISCONNECT || SystemLinkCameraInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1] == 0)
  {
    ImageSelectionCam5Panel->Enabled = false;
    Camera5_SetCheckLabel->Enabled = false;
    Camera5_SetCheckPanel->Enabled = false;
  }
  else
  {
    ImageSelectionCam5Panel->Enabled = true;
    Camera5_SetCheckLabel->Enabled = true;
    Camera5_SetCheckPanel->Enabled = true;
  }

  if(CameraMapInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition == CAMERA_POSITION_DISCONNECT || SystemLinkCameraInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1] == 0)
  {
    ImageSelectionCam13Panel->Enabled = false;
    Camera13_SetCheckLabel->Enabled = false;
    Camera13_SetCheckPanel->Enabled = false;
  }
  else
  {
    ImageSelectionCam13Panel->Enabled = true;
    Camera13_SetCheckLabel->Enabled = true;
    Camera13_SetCheckPanel->Enabled = true;
  }

  

	SelectedParamGradeValue[0] = SelectedParamGradeValue[1] = -1;
	CapturePanel->BringToFront();
}
//---------------------------------------------------------------------------
void __fastcall TCalibration3DForm::FormDestroy(TObject *Sender)
{
	if (CaptureData) delete[] CaptureData;
	delete CaptureBitmap;
  delete CaptureSaveBitmap;
}
//---------------------------------------------------------------------------
void __fastcall TCalibration3DForm::CaptureStopButtonClick(TObject *Sender)
{
  CalibrationStep_3D[0] = ECS3_NONE;
  CalibrationStep_3D[1] = ECS3_NONE;

	Comm_Request(COMM_HCB, CMD_MACHINE_CAPTURE_STOP);

	if (Machine.MachineStop())
	{
		WaitingForm->WaitingMachineStop();
	}
  CaptureEndCheckCount = 0;
  CloseButton->Enabled = true;
	CaptureStartButton->Enabled = true;
	CaptureStopButton->Enabled = false;
  RadioButton1->Enabled = true;
  RadioButton2->Enabled = true;
  SpeedBtn->Enabled = true;
	CaptureCheckTimer->Enabled = false;
}
//---------------------------------------------------------------------------
void __fastcall TCalibration3DForm::ImageSelectionButtonClick(
	TObject *Sender)
{
  Panel2->BringToFront();

  if(CameraMapInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition == CAMERA_POSITION_DISCONNECT || SystemLinkCameraInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1] == 0)
  {
    GroupBox2->BringToFront();
    ImageSelectionCam13Panel->Color = clBlue;
    ImageSelectionCam13Panel->Font->Color = clWhite;
    ImageSelectionCam5Panel->Color = clBtnFace;
    ImageSelectionCam5Panel->Font->Color = clBlack;
    CurrentSelectionCamera3DIndex = 1;
  }
  else
  {
    GroupBox1->BringToFront();
    ImageSelectionCam5Panel->Color = clBlue;
    ImageSelectionCam5Panel->Font->Color = clWhite;
    ImageSelectionCam13Panel->Color = clBtnFace;
    ImageSelectionCam13Panel->Font->Color = clBlack;
    CurrentSelectionCamera3DIndex = 0;
  }

  MainMenuPanel->Visible = false;  
  ImageSelectionMenuPanel->Visible = true;
  ImageViewScroll_Gain = 0;
  ImageViewScroll_Exposure = 0;
  CurrentSelectionStep = ESS_FIRST;
  LoadImage(CurrentSelectionCamera3DIndex,ImageViewScroll_Gain,LastCaptureShutterSpeed + (LastIncreaseSpeed* ImageViewScroll_Exposure));

}
//---------------------------------------------------------------------------

void __fastcall TCalibration3DForm::ImageSelectionNextButtonClick(
	TObject *Sender)
{
  int ImageViewScroll_Exposure_Sub;
  
  ++ImageViewScroll_Exposure;
  ImageSelectionPrevButton->Enabled = true;

  ImageViewScroll_Gain = ImageViewScroll_Exposure/(PARAM_GRADE_EXP_COUNT); //PARAM_GRADE_GAIN_COUNT;
  ImageViewScroll_Exposure_Sub = ImageViewScroll_Exposure - (ImageViewScroll_Gain*(PARAM_GRADE_EXP_COUNT));

  LoadImage(CurrentSelectionCamera3DIndex,ImageViewScroll_Gain,LastCaptureShutterSpeed + (LastIncreaseSpeed* ImageViewScroll_Exposure_Sub));

  if(ImageViewScroll_Exposure == 74) ImageSelectionNextButton->Enabled = false;
}
//---------------------------------------------------------------------------
void __fastcall TCalibration3DForm::ImageSelectionPrevButtonClick(
	TObject *Sender)
{
  int ImageViewScroll_Exposure_Sub;
  ImageSelectionNextButton->Enabled = true;
  --ImageViewScroll_Exposure;

  ImageViewScroll_Gain = ImageViewScroll_Exposure/(PARAM_GRADE_EXP_COUNT);
  ImageViewScroll_Exposure_Sub = ImageViewScroll_Exposure - (ImageViewScroll_Gain*(PARAM_GRADE_EXP_COUNT));
  
  LoadImage(CurrentSelectionCamera3DIndex,ImageViewScroll_Gain,LastCaptureShutterSpeed + (LastIncreaseSpeed* ImageViewScroll_Exposure_Sub));
  if(ImageViewScroll_Exposure == 0) ImageSelectionPrevButton->Enabled = false;
}
//---------------------------------------------------------------------------


void __fastcall TCalibration3DForm::CloseButtonClick(TObject *Sender)
{
  ExitForm();
}
//---------------------------------------------------------------------------

bool __fastcall TCalibration3DForm::RefreshCameraInfo(int camIndex, int ExposureTime, int Threshold)
{
  int WriteMask = 0;

  WriteMask |= CAMERA_WRITE_MASK_3D_SH;
  WriteMask |= CAMERA_WRITE_MASK_TH;

  TROIInfo DefaultROIInfo, ApplyROIInfo;
  AnsiString filePath;
  int DiskBaseHeight;
  int tempStartY, tempEndY, tempRowCount;
  filePath = ProgramPath.Env + "\\NFACameraInformation.ini";
  DefaultROIInfo = ReadCameraInformation(filePath, camIndex);

  if(CameraMapInfo[camIndex].CameraInspectPosition != CAMERA_POSITION_3D)
  {
    memcpy(&ApplyROIInfo, &DefaultROIInfo, sizeof(TROIInfo));
    WriteMask |= CAMERA_WRITE_MASK_2D_ROI;
  }
  else
  {
    ApplyROIInfo = SetThreeDCameraROI(DefaultROIInfo, &ProductData);
    WriteMask |= CAMERA_WRITE_MASK_3D_ROI;
  }

  if(CameraMapInfo[camIndex].CameraInspectPosition == CAMERA_POSITION_3D)
  {
     WriteMask |= CAMERA_WRITE_MASK_3D_SH;
  }

  return SetCameraInformation(ApplyROIInfo, ExposureTime, Threshold,ProductData.SubSamplingMode, camIndex, WriteMask);
}

//---------------------------------------------------------------------------

void __fastcall TCalibration3DForm::ImageSelectionCam5PanelClick(
      TObject *Sender)
{
  GroupBox1->BringToFront();
  ImageSelectionCam5Panel->Color = clBlue;
  ImageSelectionCam5Panel->Font->Color = clWhite;
  ImageSelectionCam13Panel->Color = clBtnFace;
  ImageSelectionCam13Panel->Font->Color = clBlack;
  CurrentSelectionStep = ESS_FIRST;
  CurrentSelectionCamera3DIndex = 0;

  ImageSelectionNextButton->Enabled = true;
  ImageSelectionPrevButton->Enabled = false;
  
  ImageViewScroll_Gain = 0;
  ImageViewScroll_Exposure = 0;

  LoadImage(CurrentSelectionCamera3DIndex,ImageViewScroll_Gain,LastCaptureShutterSpeed + (LastIncreaseSpeed* ImageViewScroll_Exposure));
  
}
//---------------------------------------------------------------------------

void __fastcall TCalibration3DForm::ImageSelectionCam13PanelClick(
      TObject *Sender)
{
  GroupBox2->BringToFront();
  ImageSelectionCam13Panel->Color = clBlue;
	ImageSelectionCam13Panel->Font->Color = clWhite;
	ImageSelectionCam5Panel->Color = clBtnFace;
	ImageSelectionCam5Panel->Font->Color = clBlack;
	CurrentSelectionStep = ESS_SECOND;
	CurrentSelectionCamera3DIndex = 1;

  ImageSelectionNextButton->Enabled = true;
  ImageSelectionPrevButton->Enabled = false;

  ImageViewScroll_Gain = 0;
  ImageViewScroll_Exposure = 0;

  LoadImage(CurrentSelectionCamera3DIndex,ImageViewScroll_Gain,LastCaptureShutterSpeed + (LastIncreaseSpeed* ImageViewScroll_Exposure));
}
//---------------------------------------------------------------------------
void __fastcall TCalibration3DForm::LoadImage(int cameraIndex , int Gain , int ExposureTime)
{
  ValueLabel1->Caption = "Gain : " +IntToStr(Gain) + " ExposureTime : " + IntToStr(ExposureTime);
  ValueLabel2->Caption = "Gain : " +IntToStr(Gain) + " ExposureTime : " + IntToStr(ExposureTime);
  
  int globalCameraIndex;
  int cameraIndex_3D = cameraIndex;
	if (cameraIndex_3D == 0)
	{
		globalCameraIndex = FIRST_3D_CAM_INDEX;
	}
	else
	{
		globalCameraIndex = SECOND_3D_CAM_INDEX;
	}

  for (int imageIndex = 0; imageIndex < MAX_IMAGE_COUNT_PER_GRADE; imageIndex++)
  {
    AnsiString imageDir = GetProductImagePath();
    AnsiString bitmapFileName = imageDir + "\\Calib3D\\Image_" + IntToStr(Gain) + "_"+ IntToStr(ExposureTime) +
      "_" + IntToStr(imageIndex + 1) + "_" + IntToStr(globalCameraIndex + 1) + ".bmp";
    if (FileExists(bitmapFileName))
    {
      ImagePanelList[cameraIndex_3D][imageIndex]->Picture->Bitmap->LoadFromFile(bitmapFileName);
      ImagePanelList[cameraIndex_3D][imageIndex]->Repaint();
    }
  }
}
//-----------------------------------------------------------------------------
void __fastcall TCalibration3DForm::SelectCameraParamButtonClick(
      TObject *Sender)
{
  int ImageViewScroll_Exposure_Sub;

  ImageViewScroll_Gain = ImageViewScroll_Exposure/(PARAM_GRADE_EXP_COUNT); //PARAM_GRADE_GAIN_COUNT;
  ImageViewScroll_Exposure_Sub = ImageViewScroll_Exposure - (ImageViewScroll_Gain*(PARAM_GRADE_EXP_COUNT));

  if(CurrentSelectionCamera3DIndex == 0)
  {
    Camera5_SetCheckPanel->Color = clGreen;
    SaveDataFlag[0] = true;
    CurrentExposureTime[0] = LastCaptureShutterSpeed + (LastIncreaseSpeed* ImageViewScroll_Exposure_Sub);
    CurrentGain[0] = ImageViewScroll_Gain;
    Camera5_SetCheckLabel->Caption = "CAM "+ IntToStr(SD1_3D_FRONT_FACE_CAMERA_INDEX)+
    ": Gain : "+ IntToStr(CurrentGain[0])+
    " , ExposureTime : "+ IntToStr(CurrentExposureTime[0]);
  }
  else
  {
    Camera13_SetCheckPanel->Color = clGreen;
    SaveDataFlag[1] = true;
    CurrentExposureTime[1] = LastCaptureShutterSpeed + (LastIncreaseSpeed* ImageViewScroll_Exposure_Sub);
    CurrentGain[1] = ImageViewScroll_Gain;
    Camera13_SetCheckLabel->Caption = "CAM "+ IntToStr(SD2_3D_FRONT_FACE_CAMERA_INDEX)+
    ": Gain : "+ IntToStr(CurrentGain[1])+
    " , ExposureTime : "+ IntToStr(CurrentExposureTime[1]);
  }
}
//---------------------------------------------------------------------------

void __fastcall TCalibration3DForm::StartShutterSpeedEditClick(
      TObject *Sender)
{
  TTntEdit *theEdit = (TTntEdit *)Sender;
   KeyboardForm->Text = theEdit->Text;
  if (KeyboardForm->ShowKeypad() == mrOk)
	{
    theEdit->Text = KeyboardForm->Text ;
    if(StartShutterSpeedEdit->Text.Length() != 0)
    {
      EndShutterSpeedLabel->Caption = "~  "+ IntToStr(StrToInt(KeyboardForm->Text)+(IncreaseSpeed*(PARAM_GRADE_EXP_COUNT-1)));
    }
  }

}
//---------------------------------------------------------------------------



void __fastcall TCalibration3DForm::RadioButton1Click(TObject *Sender)
{
  /*if(RadioButton1->Checked)
    IncreaseSpeed = 1000;
  else if(RadioButton2->Checked)
    IncreaseSpeed = 10000;
  else
    IncreaseSpeed = 5000;

  if(StartShutterSpeedEdit->Text.Length() != 0)
  {
    EndShutterSpeedLabel->Caption = "~  "+ IntToStr(StrToInt(StartShutterSpeedEdit->Text)+(IncreaseSpeed*4));
  }  */
}
//---------------------------------------------------------------------------



void __fastcall TCalibration3DForm::ReturnButtonClick(TObject *Sender)
{
  ExitForm();
}
//---------------------------------------------------------------------------

void __fastcall TCalibration3DForm::RemoveWholeDir(AnsiString folderName)
{
	TSearchRec sr;
	int iAttributes = faAnyFile;
	if (FindFirst(folderName + "\\*.*", iAttributes, sr) == 0)
	{
		do
		{
			if (sr.Name == "." || sr.Name == "..") continue;
			if (sr.Attr & faDirectory)
			{
				RemoveWholeDir(folderName + "\\" + sr.Name);
			}
			else
			{
				//                if (MessageDlgFA(folderName + "\\" + sr.Name + " 을 정말 삭제하겠습니까?", mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
				{
					DeleteFile(folderName + "\\" + sr.Name);
				}
			}

		} while (FindNext(sr) == 0);
		FindClose(sr);
		//        if (MessageDlgFA(folderName + " 을 정말 삭제하겠습니까?", mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
		{
			RemoveDir(folderName);
		}
	}
}

void __fastcall TCalibration3DForm::ExitForm()
{
  bool Result = true;
  if((CameraMapInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition != CAMERA_POSITION_DISCONNECT&& SaveDataFlag[0] == false) ||
    (CameraMapInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition != CAMERA_POSITION_DISCONNECT&& SaveDataFlag[1] == false) ||
    (SystemLinkCameraInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1] != 0 && SaveDataFlag[0] == false) ||
    (SystemLinkCameraInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1] != 0 && SaveDataFlag[1] == false)
    )
  {
    if (MessageDlgFA(IMAGECAPTURE3D_MSG_CAPTION_01, mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
      Result = false;
    else
      return;
  }

  if(Result == true)
  {
      if( (CameraMapInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition == CAMERA_POSITION_DISCONNECT|| SaveDataFlag[0] == true) &&
    (CameraMapInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1].CameraInspectPosition == CAMERA_POSITION_DISCONNECT ||SaveDataFlag[1] == true ) &&
    (SystemLinkCameraInfo[SD1_3D_FRONT_FACE_CAMERA_INDEX - 1] == 0 ||SaveDataFlag[0] == true ) &&
    (SystemLinkCameraInfo[SD2_3D_FRONT_FACE_CAMERA_INDEX - 1] == 0 ||SaveDataFlag[1] == true ))
    {
        if(SaveDataFlag[0] == true)
        {
          ProductData.ExposureTime3D[0] = CurrentExposureTime[0];
          ProductData.AnalogGain3D[0] = CurrentGain[0];
        }
        if(SaveDataFlag[1] == true)
        {
          ProductData.ExposureTime3D[1] = CurrentExposureTime[1];
          ProductData.AnalogGain3D[1] = CurrentGain[1];
        }
        Result = true;
    }
    else
    {
      if (MessageDlgFA(IMAGECAPTURE3D_MSG_CAPTION_01, mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
        Result = false;
      else
        return;
    }
  }


  AnsiString Dir = GetProductImagePath()+"\\Calib3D";
  if(DirectoryExists(Dir))
    RemoveWholeDir(Dir);

  if(Result)
    ModalResult = mrOk;
  else
    ModalResult = mrCancel;
}
//---------------------------------------------------------------------------

void __fastcall TCalibration3DForm::SpeedBtnClick(TObject *Sender)
{
  TStudySpeedControlForm *studyspeedControlForm = new TStudySpeedControlForm(this);
	studyspeedControlForm->ShowModal();
	delete studyspeedControlForm;  
}
//---------------------------------------------------------------------------

void __fastcall TCalibration3DForm::ReCaptureBtnClick(TObject *Sender)
{
  if (MessageDlgFA(IMAGECAPTURE3D_MSG_CAPTION_02, mtConfirmation, TMsgDlgButtons() << mbOK << mbCancel) == mrOk)
  {
    MainMenuPanel->Visible = true;
    ImageSelectionMenuPanel->Visible = false;
    ImageSelectionButton->Enabled = false;
  }

}
//---------------------------------------------------------------------------

