<commit_before>#include "orientationhist.h"

#include <iostream>

using namespace cimg_library;

OrientationHist::OrientationHist(CImg<float>& Im) :
    nb_classes(12)
{
    CImg<float> I = Im;

//    if( Im.spectrum() >= 3 )
//        I = Im.RGBtoHSI().get_channel(2);

    CImg<float> sobHoriz(3,3,1,1,1,0,-1,2,0,-2,1,0,-1);
    CImg<float> sobVert = sobHoriz.get_transpose();

    CImg<float> gradVert = I.get_convolve(sobVert);
    CImg<float> gradHoriz = I.get_convolve(sobHoriz);

    CImg<float> gradOrientImg(I.width(),I.height(),1,1);
    CImg<float> gradNormImg(I.width(),I.height(),1,1);

    cimg_forXY(gradOrientImg,x,y) {
        gradNormImg(x,y) = sqrt( gradHoriz(x,y) * gradHoriz(x,y) + gradVert(x,y) * gradVert(x,y) );
        gradOrientImg(x,y) = atan( gradVert(x,y)/gradHoriz(x,y) );
    }

    std::cout << "Yo j'ai calc le gradient biatch" << std::endl;

    CImg<float> bin(I.width(),I.height(),nb_classes,1);
    CImg<float> img_integrale(I.width(),I.height(),nb_classes,1);
    bin.fill(0.0f);
    img_integrale.fill(0.0f);

    cimg_forXY(bin,x,y) {
        int interval = (int)floor( ((gradOrientImg(x,y) + M_PI/2) / M_PI) * nb_classes );
        interval = (interval >= 0 && interval < nb_classes)*interval + (interval>=nb_classes) * (nb_classes-1);
        bin(x,y,interval) = gradNormImg(x,y);
    }

//    CImg<float> test = bin.get_slice(5);
    //test.display();

    std::cout << "Yo j'ai calc les bins" << std::endl;

    std::cout << img_integrale.depth() << std::endl;
    for(int z = 0; z < img_integrale.depth(); ++ z)
    {
        cimg_forXY(img_integrale,x,y) {
            for(int i = 0; i <= y; ++i)
                img_integrale(x,y,z) += bin(x,i,z);
            if(x != 0)
                img_integrale(x,y,z) += img_integrale(x-1,y,z);
            //        if( x == 0 ) {
            //            if( y == 0 ) {
            //                img_integrale(x,y,z) = bin(x,y,z);
            //            } else {
            //                img_integrale(x,y,z) = img_integrale(x,y-1,z) + bin(x,y,z);
            //            }
            //        } else {
            //            img_integrale(x,y,z) = img_integrale(x-1,y,z);
            //            for(int i = 0; i <= y ; ++ i )
            //            {
            //                img_integrale(x,y,z) += bin(x,i,z);
            //            }
            //        }

//            std::cout<<"img_integrale("<<x<<","<<y<<","<< z <<") = " << img_integrale(x,y,z) << std::endl;
        }
    }
    m_imgIntegrale = img_integrale;
    std::cout << "ru =" << m_imgIntegrale(I.width()-1,I.height()-1,1) << "\n original" << img_integrale(I.width()-1,I.height()-1,1) << std::endl;
}

CImg<float> OrientationHist::getHist(unsigned lowlx, unsigned lowly, unsigned rupx, unsigned rupy)
{
    CImg<float> hist(nb_classes,1,1,1);

    std::cout << "ll = " << m_imgIntegrale(lowlx,lowly,1) << std::endl;
    std::cout << "ru = " << m_imgIntegrale(rupx,rupy,1) << std::endl;

    cimg_forX(hist,i) {
        hist(i) = m_imgIntegrale(lowlx,lowly,i) + m_imgIntegrale(rupx,rupy,i)
                  - (m_imgIntegrale(lowlx,rupy,i) + m_imgIntegrale(rupx,lowly,i));
    }

    return hist;
}
<commit_msg>commit before merge<commit_after>#include "orientationhist.h"

#include <iostream>

using namespace cimg_library;

OrientationHist::OrientationHist(CImg<float>& Im) :
    nb_classes(12)
{
    CImg<float> I = Im;

//    if( Im.spectrum() >= 3 )
//        I = Im.RGBtoHSI().get_channel(2);

    CImg<float> sobHoriz(3,3,1,1,1,0,-1,2,0,-2,1,0,-1);
    CImg<float> sobVert = sobHoriz.get_transpose();

    CImg<float> gradVert = I.get_convolve(sobVert);
    CImg<float> gradHoriz = I.get_convolve(sobHoriz);

    CImg<float> gradOrientImg(I.width(),I.height(),1,1);
    CImg<float> gradNormImg(I.width(),I.height(),1,1);

    cimg_forXY(gradOrientImg,x,y) {
        gradNormImg(x,y) = sqrt( gradHoriz(x,y) * gradHoriz(x,y) + gradVert(x,y) * gradVert(x,y) );
        gradOrientImg(x,y) = atan( gradVert(x,y)/gradHoriz(x,y) );
    }

    CImg<float> bin(I.width(),I.height(),nb_classes,1);
    CImg<float> img_integrale(I.width(),I.height(),nb_classes,1);
    bin.fill(0.0f);
    img_integrale.fill(0.0f);

    cimg_forXY(bin,x,y) {
        int interval = (int)floor( ((gradOrientImg(x,y) + M_PI/2) / M_PI) * nb_classes );
        interval = (interval >= 0 && interval < nb_classes)*interval + (interval>=nb_classes) * (nb_classes-1);
        bin(x,y,interval) = gradNormImg(x,y);
    }

    for(int z = 0; z < img_integrale.depth(); ++ z)
    {
        cimg_forXY(img_integrale,x,y) {
            for(int i = 0; i <= y; ++i)
                img_integrale(x,y,z) += bin(x,i,z);
            if(x != 0)
                img_integrale(x,y,z) += img_integrale(x-1,y,z);
        }
    }
    m_imgIntegrale = img_integrale;
}

CImg<float> OrientationHist::getHist(unsigned lowlx, unsigned lowly, unsigned rupx, unsigned rupy)
{
    CImg<float> hist(nb_classes,1,1,1);

    cimg_forX(hist,i) {
        hist(i) = m_imgIntegrale(lowlx,lowly,i) + m_imgIntegrale(rupx,rupy,i)
                  - (m_imgIntegrale(lowlx,rupy,i) + m_imgIntegrale(rupx,lowly,i));
    }

    return hist;
}
<|endoftext|>


<commit_before>

#include "moai-core/pch.h"
#include "moai-sim/pch.h"

#include <jni.h>

#include <moai-android/moaiext-jni.h>
#include "MOAINativeEventsAndroid.h"

extern JavaVM* jvm;

//================================================================//
// lua
//================================================================//

//----------------------------------------------------------------//
/**	@name	triggerEvent
	@text	Trigger a native event

    @in		string		eventName		The name of the triggered event
    @in		string		jsonParams		A string of json data used for input parameters
	@opt	function	callback		A function to callback when event is done.
	@out 	nil
*/
int MOAINativeEventsAndroid::_triggerEvent ( lua_State* L ) {

	MOAILuaState state ( L );

	cc8* eventName = lua_tostring ( state, 1 );
	cc8* jsonParams = lua_tostring ( state, 2 );

	if ( state.IsType ( 3, LUA_TFUNCTION )) {

		MOAIDialogAndroid::Get().mEventCallback.SetRef ( state, 3 );
	}

	JNI_GET_ENV ( jvm, env );

	JNI_GET_JSTRING ( eventName, jeventName );
	JNI_GET_JSTRING ( jsonParams, jjsonParams );

	jclass javaNativeEvents = env->FindClass ( "com/whalefood/MoaiNativeEventsPlugin/MoaiNativeEvents" );
    if ( moai == NULL ) {

		ZLLog::Print ( "MOAINativeEventsAndroid: Unable to find java class %s", "com/whalefood/MoaiNativeEvents" );
    } else {

    	jmethodID jTriggerEvent = env->GetStaticMethodID ( moai, "triggerEvent", "(Ljava/lang/String;Ljava/lang/String;Z)V" );
    	if ( jTriggerEvent == NULL ) {

			ZLLog::Print ( "MOAINativeEventsAndroid: Unable to find static java method %s", "triggerEvent" );
    	} else {

			env->CallStaticVoidMethod ( javaNativeEvents, jTriggerEvent, jeventName, jjsonParams);
		}
	}

	return 0;
}

//================================================================//
// MOAINativeEventsAndroid
//================================================================//

//----------------------------------------------------------------//
MOAINativeEventsAndroid::MOAINativeEventsAndroid () {

	RTTI_SINGLE ( MOAINativeEventsAndroid )
}

//----------------------------------------------------------------//
MOAINativeEventsAndroid::~MOAINativeEventsAndroid () {
}

//----------------------------------------------------------------//
void MOAINativeEventsAndroid::RegisterLuaClass ( MOAILuaState& state ) {

	luaL_Reg regTable [] = {
		{ "triggerEvent",	_triggerEvent },
		{ NULL, NULL }
	};

	luaL_register ( state, 0, regTable );
}

//----------------------------------------------------------------//
void MOAINativeEventsAndroid::NotifyEventFinished (  cc8* rslt ) {

	if ( !mEventCallback.IsNil ()) {

		MOAIScopedLuaState state = mEventCallback.GetSelf ();

		lua_pushstring ( state, rslt );

		state.DebugCall ( 1, 0 );

		mEventCallback.Clear ();
	}
}

//================================================================//
// Miscellaneous JNI Functions
//================================================================//

//----------------------------------------------------------------//
extern "C" void Java_com_whalefood_MoaiNativeEventsPlugin_MoaiNativeEvents_NotifyEventFinished ( JNIEnv* env, jclass obj, jstring rslt ) {

    cc8* cstrRslts = env->GetStringUTFChars(rslt, JNI_FALSE);

	MOAINativeEventsAndroid::Get().NotifyEventFinished ( cstrRslts );

     env->ReleaseStringUTFChars(rslt, cstrRslts);

}<commit_msg>Android cpp bug fixes<commit_after>

#include "moai-core/pch.h"
#include "moai-sim/pch.h"

#include <jni.h>

#include <moai-android/moaiext-jni.h>
#include "MOAINativeEventsAndroid.h"

extern JavaVM* jvm;

//================================================================//
// lua
//================================================================//

//----------------------------------------------------------------//
/**	@name	triggerEvent
	@text	Trigger a native event

    @in		string		eventName		The name of the triggered event
    @in		string		jsonParams		A string of json data used for input parameters
	@opt	function	callback		A function to callback when event is done.
	@out 	nil
*/
int MOAINativeEventsAndroid::_triggerEvent ( lua_State* L ) {

	MOAILuaState state ( L );

	cc8* eventName = lua_tostring ( state, 1 );
	cc8* jsonParams = lua_tostring ( state, 2 );

	if ( state.IsType ( 3, LUA_TFUNCTION )) {

		MOAINativeEventsAndroid::Get().mEventCallback.SetRef ( state, 3 );
	}

	JNI_GET_ENV ( jvm, env );

	JNI_GET_JSTRING ( eventName, jeventName );
	JNI_GET_JSTRING ( jsonParams, jjsonParams );

	jclass javaNativeEvents = env->FindClass ( "com/whalefood/MoaiNativeEventsPlugin/MoaiNativeEvents" );
    if ( javaNativeEvents == NULL ) {

		ZLLog::Print ( "MOAINativeEventsAndroid: Unable to find java class %s", "com/whalefood/MoaiNativeEvents" );

    } else {

    	jmethodID jTriggerEvent = env->GetStaticMethodID ( javaNativeEvents, "triggerEvent", "(Ljava/lang/String;Ljava/lang/String;)V" );
    	if ( jTriggerEvent == NULL ) {

			ZLLog::Print ( "MOAINativeEventsAndroid: Unable to find static java method %s", "triggerEvent" );
    	} else {

			env->CallStaticVoidMethod ( javaNativeEvents, jTriggerEvent, jeventName, jjsonParams);
		}
	}

	return 0;
}

//================================================================//
// MOAINativeEventsAndroid
//================================================================//

//----------------------------------------------------------------//
MOAINativeEventsAndroid::MOAINativeEventsAndroid () {

	RTTI_SINGLE ( MOAINativeEventsAndroid )
}

//----------------------------------------------------------------//
MOAINativeEventsAndroid::~MOAINativeEventsAndroid () {
}

//----------------------------------------------------------------//
void MOAINativeEventsAndroid::RegisterLuaClass ( MOAILuaState& state ) {

	luaL_Reg regTable [] = {
		{ "triggerEvent",	_triggerEvent },
		{ NULL, NULL }
	};

	luaL_register ( state, 0, regTable );
}

//----------------------------------------------------------------//
void MOAINativeEventsAndroid::NotifyEventFinished (  cc8* rslt ) {

	if ( !mEventCallback.IsNil ()) {

		MOAIScopedLuaState state = mEventCallback.GetSelf ();

		lua_pushstring ( state, rslt );

		state.DebugCall ( 1, 0 );

		mEventCallback.Clear ();
	}
}

//================================================================//
// Miscellaneous JNI Functions
//================================================================//

//----------------------------------------------------------------//
extern "C" void Java_com_whalefood_MoaiNativeEventsPlugin_MoaiNativeEvents_NotifyEventFinished ( JNIEnv* env, jclass obj, jstring rslt ) {

    cc8* cstrRslts = env->GetStringUTFChars(rslt, JNI_FALSE);

	MOAINativeEventsAndroid::Get().NotifyEventFinished ( cstrRslts );

     env->ReleaseStringUTFChars(rslt, cstrRslts);

}

extern "C" void Java_com_whalefood_MoaiNativeEventsPlugin_Test ( JNIEnv* env, jclass obj) {

    ZLLog::Print ( "Test worked");
}
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include <mitkBaseData.h>
#include <mitkImageCast.h>
#include <mitkImageToItk.h>
#include <metaCommand.h>
#include "mitkCommandLineParser.h"
#include <usAny.h>
#include <itkImageFileWriter.h>
#include <itkImageFileReader.h>
#include <mitkIOUtil.h>
#include <boost/lexical_cast.hpp>
#include <itkShCoefficientImageExporter.h>
#include <itkFlipImageFilter.h>

#define _USE_MATH_DEFINES
#include <math.h>

template<int shOrder>
int StartShConversion(int argc, char* argv[])
{
    mitkCommandLineParser parser;

    parser.setTitle("Export SH Image");
    parser.setCategory("Preprocessing Tools");
    parser.setDescription(" ");
    parser.setContributor("MBI");

    parser.setArgumentPrefix("--", "-");
    parser.addArgument("input", "i", mitkCommandLineParser::InputFile, "Input:", "MITK SH image", us::Any(), false);
    parser.addArgument("output", "o", mitkCommandLineParser::InputFile, "Output", "MRtrix SH image", us::Any(), false);
    parser.addArgument("shOrder", "sh", mitkCommandLineParser::Int, "SH order:", "spherical harmonics order");

    map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
    if (parsedArgs.size()==0)
        return EXIT_FAILURE;

    string inFile = us::any_cast<string>(parsedArgs["input"]);
    string outFile = us::any_cast<string>(parsedArgs["output"]);

    try
    {

        typedef itk::Image< float, 4 > OutImageType;
        typedef itk::Image< itk::Vector< float, (shOrder*shOrder + shOrder + 2)/2 + shOrder >, 3 > InputImageType;

        typename InputImageType::Pointer itkInImage = InputImageType::New();
        typedef itk::ImageFileReader< InputImageType > ReaderType;
        typename ReaderType::Pointer reader = ReaderType::New();
        std::cout << "reading " << inFile;
        reader->SetFileName(inFile.c_str());
        reader->Update();
        itkInImage = reader->GetOutput();

        // extract directions from fiber bundle
        typename itk::ShCoefficientImageExporter<float, shOrder>::Pointer filter = itk::ShCoefficientImageExporter<float,shOrder>::New();
        filter->SetInputImage(itkInImage);
        filter->GenerateData();
        OutImageType::Pointer outImage = filter->GetOutputImage();

        typedef itk::ImageFileWriter< OutImageType > WriterType;
        WriterType::Pointer writer = WriterType::New();
        writer->SetFileName(outFile.c_str());
        writer->SetInput(outImage);
        writer->Update();
    }
    catch (itk::ExceptionObject e)
    {
        std::cout << e;
        return EXIT_FAILURE;
    }
    catch (std::exception e)
    {
        std::cout << e.what();
        return EXIT_FAILURE;
    }
    catch (...)
    {
        std::cout << "ERROR!?!";
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

int main(int argc, char* argv[])
{

    mitkCommandLineParser parser;
    parser.setArgumentPrefix("--", "-");
    parser.addArgument("input", "i", mitkCommandLineParser::InputFile, "Input image", "MITK SH image", us::Any(), false);
    parser.addArgument("output", "o", mitkCommandLineParser::OutputFile, "Output image", "MRtrix SH image", us::Any(), false);
    parser.addArgument("shOrder", "sh", mitkCommandLineParser::Int, "Spherical harmonics order", "spherical harmonics order");

    parser.setCategory("Preprocessing Tools");
    parser.setTitle("Export SH Image");
    parser.setDescription(" ");
    parser.setContributor("MBI");

    map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
    if (parsedArgs.size()==0)
        return EXIT_FAILURE;

    int shOrder = -1;
    if (parsedArgs.count("shOrder"))
        shOrder = us::any_cast<int>(parsedArgs["shOrder"]);

    switch (shOrder)
    {
    case 4:
        return StartShConversion<4>(argc, argv);
    case 6:
        return StartShConversion<6>(argc, argv);
    case 8:
        return StartShConversion<8>(argc, argv);
    case 10:
        return StartShConversion<10>(argc, argv);
    case 12:
        return StartShConversion<12>(argc, argv);
    }
    return EXIT_FAILURE;
}
<commit_msg>fixed sh image export<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include <mitkBaseData.h>
#include <mitkImageCast.h>
#include <mitkImageToItk.h>
#include <metaCommand.h>
#include "mitkCommandLineParser.h"
#include <usAny.h>
#include <itkImageFileWriter.h>
#include <itkImageFileReader.h>
#include <mitkIOUtil.h>
#include <boost/lexical_cast.hpp>
#include <itkShCoefficientImageExporter.h>
#include <itkFlipImageFilter.h>
#include <mitkIOUtil.h>
#include <mitkITKImageImport.h>

#define _USE_MATH_DEFINES
#include <math.h>

template<int shOrder>
int StartShConversion(int argc, char* argv[])
{
    mitkCommandLineParser parser;

    parser.setTitle("Export SH Image");
    parser.setCategory("Preprocessing Tools");
    parser.setDescription(" ");
    parser.setContributor("MBI");

    parser.setArgumentPrefix("--", "-");
    parser.addArgument("input", "i", mitkCommandLineParser::InputFile, "Input:", "MITK SH image", us::Any(), false);
    parser.addArgument("output", "o", mitkCommandLineParser::InputFile, "Output", "MRtrix SH image", us::Any(), false);
    parser.addArgument("shOrder", "sh", mitkCommandLineParser::Int, "SH order:", "spherical harmonics order");

    map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
    if (parsedArgs.size()==0)
        return EXIT_FAILURE;

    string inFile = us::any_cast<string>(parsedArgs["input"]);
    string outFile = us::any_cast<string>(parsedArgs["output"]);

    try
    {

        typedef itk::Image< float, 4 > OutImageType;
        typedef itk::Image< itk::Vector< float, (shOrder*shOrder + shOrder + 2)/2 + shOrder >, 3 > InputImageType;

        typename InputImageType::Pointer itkInImage = InputImageType::New();
        typedef itk::ImageFileReader< InputImageType > ReaderType;
        typename ReaderType::Pointer reader = ReaderType::New();
        std::cout << "reading " << inFile;
        reader->SetFileName(inFile.c_str());
        reader->Update();
        itkInImage = reader->GetOutput();

        // extract directions from fiber bundle
        typename itk::ShCoefficientImageExporter<float, shOrder>::Pointer filter = itk::ShCoefficientImageExporter<float,shOrder>::New();
        filter->SetInputImage(itkInImage);
        filter->GenerateData();
        OutImageType::Pointer outImage = filter->GetOutputImage();

        mitk::Image::Pointer image = mitk::GrabItkImageMemory(outImage.GetPointer());
        mitk::IOUtil::Save(image, outFile );

//        typedef itk::ImageFileWriter< OutImageType > WriterType;
//        WriterType::Pointer writer = WriterType::New();
//        writer->SetFileName(outFile.c_str());
//        writer->SetInput(outImage);
//        writer->Update();
    }
    catch (itk::ExceptionObject e)
    {
        std::cout << e;
        return EXIT_FAILURE;
    }
    catch (std::exception e)
    {
        std::cout << e.what();
        return EXIT_FAILURE;
    }
    catch (...)
    {
        std::cout << "ERROR!?!";
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

int main(int argc, char* argv[])
{

    mitkCommandLineParser parser;
    parser.setArgumentPrefix("--", "-");
    parser.addArgument("input", "i", mitkCommandLineParser::InputFile, "Input image", "MITK SH image", us::Any(), false);
    parser.addArgument("output", "o", mitkCommandLineParser::OutputFile, "Output image", "MRtrix SH image", us::Any(), false);
    parser.addArgument("shOrder", "sh", mitkCommandLineParser::Int, "Spherical harmonics order", "spherical harmonics order");

    parser.setCategory("Preprocessing Tools");
    parser.setTitle("Export SH Image");
    parser.setDescription(" ");
    parser.setContributor("MBI");

    map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
    if (parsedArgs.size()==0)
        return EXIT_FAILURE;

    int shOrder = -1;
    if (parsedArgs.count("shOrder"))
        shOrder = us::any_cast<int>(parsedArgs["shOrder"]);

    switch (shOrder)
    {
    case 4:
        return StartShConversion<4>(argc, argv);
    case 6:
        return StartShConversion<6>(argc, argv);
    case 8:
        return StartShConversion<8>(argc, argv);
    case 10:
        return StartShConversion<10>(argc, argv);
    case 12:
        return StartShConversion<12>(argc, argv);
    }
    return EXIT_FAILURE;
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#include "itkFileListVideoIO.h"

#include "itkImage.h"
#include "itkImportImageFilter.h"
#include "itkImageIOFactory.h"

namespace itk
{

///////////////////////////////////////////////////////////////////////////////
// Constructor, Destructor, and Print
//

//
// Constructor
//
FileListVideoIO::FileListVideoIO()
{
  this->ResetMembers();
}

//
// Destructor
//
FileListVideoIO::~FileListVideoIO()
{
  this->FinishReadingOrWriting();
}

//
// PrintSelf
//
void FileListVideoIO::PrintSelf(std::ostream & os, Indent indent) const
{
  Superclass::PrintSelf(os,indent);
  if (!this->m_ImageIO.IsNull())
    {
    os << indent << "Internal ImageIO:" << std::endl;
    this->m_ImageIO->Print(os, indent.GetNextIndent());
    }
}

//
// FinishReadingOrWriting
//
void FileListVideoIO::FinishReadingOrWriting()
{
  this->ResetMembers();

}

///////////////////////////////////////////////////////////////////////////////
// Member Accessors
//

//
// GetPositionInMSec
//
double FileListVideoIO::GetPositionInMSec()
{
  return this->m_PositionInMSec;
}

//
// GetRatio
//
double FileListVideoIO::GetRatio()
{
  return this->m_Ratio;
}

//
// GetFrameTotal
//
unsigned long FileListVideoIO::GetFrameTotal()
{
  return this->m_FrameTotal;
}

//
// GetFpS
//
double FileListVideoIO::GetFpS()
{
  return this->m_FpS;
}

//
// GetCurrentFrame
//
unsigned long FileListVideoIO::GetCurrentFrame()
{
  return this->m_CurrentFrame;
}

//
// GetIFrameInterval
//
unsigned int FileListVideoIO::GetIFrameInterval()
{
  return this->m_IFrameInterval;
}

//
// GetLastIFrame
//
unsigned long FileListVideoIO::GetLastIFrame()
{
  return this->m_LastIFrame;
}

//
// SetFileName -- Split list based on ';'
//
void FileListVideoIO::SetFileName(const char* fileList)
{
  this->m_FileNames = SplitFileNames(fileList);

  // Set the number of frames
  this->m_FrameTotal = this->m_FileNames.size();
}

//
// SplitFileNames ';'
//
std::vector<std::string> FileListVideoIO::SplitFileNames(const char* fileList)
{
  std::string str = fileList;

  std::vector<std::string> out;

  int pos = 0;
  int len = str.length();
  while (pos != -1 && len > 0)
    {
    // Get the substring
    str = str.substr(pos, len);

    // Update pos
    pos = str.find(',');

    // Add the filename to the list
    out.push_back(str.substr(0,pos));

    // Move past the delimiter
    if (pos != -1)
      {
      pos++;
      }
    len -= pos;
    }

  return out;
}

///////////////////////////////////////////////////////////////////////////////
// Read related methods
//

//
// SetReadFromFile
//
void FileListVideoIO::SetReadFromFile()
{
  if (!this->m_ReaderOpen && !this->m_WriterOpen)
    {
    this->m_ReadType = ReadFromFile;
    }
  else
    {
    itkExceptionMacro("Cannot change read type while reader is open");
    }
}

//
// SetReadFromCamera
//
void FileListVideoIO::SetReadFromCamera()
{
  itkExceptionMacro("Read From Camera is not supported by this VideoIO");
}

//
// CanReadFile
//
bool FileListVideoIO::CanReadFile(const char* filename)
{
  // Make sure file names have been specified
  std::vector<std::string> fileList = SplitFileNames(filename);
  if (fileList.size() == 0)
    {
    return false;
    }

  // Make sure all file names have the same extension
  for (unsigned int i = 1; i < fileList.size(); ++i)
    {
    int prevExtPos = fileList[i-1].rfind(".");
    int extPos = fileList[i].rfind(".");
    if (prevExtPos == -1 || extPos == -1)
      {
      return false;
      }
    std::string prevExt = fileList[i-1].substr(prevExtPos + 1, fileList[i-1].length()-prevExtPos-1);
    std::string ext = fileList[i].substr(extPos + 1, fileList[i].length()-extPos-1);

    if (strcmp(prevExt.c_str(), ext.c_str()))
      {
      return false;
      }
    }

  // Make sure we can instantiate an ImageIO to read the first file
  ImageIOBase::Pointer ioTemp = ImageIOFactory::CreateImageIO(
      fileList[0].c_str(), ImageIOFactory::ReadMode);
  if (ioTemp.IsNull())
    {
    return false;
    }

  return true;
}

//
// CanReadCamera
//
bool FileListVideoIO::CanReadCamera( unsigned long cameraID )
{
  return false;
}

//
// ReadImageInformation
//
void FileListVideoIO::ReadImageInformation()
{
  // Open from a file
  if (this->m_ReadType == ReadFromFile)
    {

    // Make sure file can be read
    std::string filename = this->m_FileNames[0];
    if (!this->CanReadFile(filename.c_str()))
      {
      itkExceptionMacro(<< "Cannot Read File: " << filename);
      }

    // Open the image file
    ImageIOBase::Pointer localIO = ImageIOFactory::CreateImageIO(
      this->m_FileNames[0].c_str(), ImageIOFactory::ReadMode);

    localIO->SetFileName(this->m_FileNames[0].c_str());
    localIO->ReadImageInformation();

    // No I-Frame issues to worry about
    this->m_IFrameInterval = 1;
    this->m_LastIFrame = this->m_FrameTotal-1;

    // Fill Dimensions and Origin
    this->m_Dimensions.clear();
    this->m_Origin.clear();
    this->SetNumberOfDimensions(localIO->GetNumberOfDimensions());
    for (unsigned int i = 0; i < localIO->GetNumberOfDimensions(); ++i)
      {
      this->m_Dimensions.push_back(localIO->GetDimensions(i));
      this->m_Origin.push_back(localIO->GetOrigin(i));
      }

    // Get other image info
    this->m_NumberOfComponents = localIO->GetNumberOfComponents();
    this->m_ComponentType = localIO->GetComponentType();
    this->m_PixelType = localIO->GetPixelType();

    // Make up an arbitrary FpS of 1
    this->m_FpS = 1;

    }

  // Open capture from a camera
  else if (this->m_ReadType == ReadFromCamera)
    {
    itkExceptionMacro("FileListVideoIO cannot read from a camera");
    }

  // Should never get here
  else
    {
    itkExceptionMacro("Invalid Read Type... How did we get here?");
    }
}

//
// Read
//
void FileListVideoIO::Read(void *buffer)
{
  // Make sure we've already called ReadImageInformation (dimensions are non-zero)
  if (this->m_Dimensions[0] == 0)
    {
    itkExceptionMacro(<< "Cannot read frame with zero dimension. May need to call ReadImageInformation");
    }

  // If video is not already open, open it and keep it open
  if (!this->m_ReaderOpen)
    {
    this->OpenReader();
    }

  // Read the desired frame
  this->m_ImageIO->SetFileName(this->m_FileNames[this->m_CurrentFrame]);
  this->m_ImageIO->Read(buffer);

  // Move on to the next frame
  if (this->m_CurrentFrame < this->m_FrameTotal - 1)
    {
    this->m_CurrentFrame++;
    }
}

//
// SetNextFrameToRead
//
bool FileListVideoIO::SetNextFrameToRead(unsigned long frameNumber)
{

  if (frameNumber >= this->m_FrameTotal)
    {
    return false;
    }

  this->m_CurrentFrame = frameNumber;
  return true;
}

//
// GetSpacing
//
double FileListVideoIO::GetSpacing(unsigned int i) const
{
  if (!m_ReaderOpen)
    {
    itkExceptionMacro("Can't get Spacing without ImageIO open for reading");
    }
  return m_ImageIO->GetSpacing(i);
}

//
// GetOrigin
//
double FileListVideoIO::GetOrigin(unsigned int i) const
{
  if (!m_ReaderOpen)
    {
    itkExceptionMacro("Can't get Origin without ImageIO open for reading");
    }
  return m_ImageIO->GetOrigin(i);
}

//
// GetDirection
//
std::vector< double > FileListVideoIO::GetDirection(unsigned int i) const
{
  if (!m_ReaderOpen)
    {
    itkExceptionMacro("Can't get Direction without ImageIO open for reading");
    }
  return m_ImageIO->GetDirection(i);
}

///////////////////////////////////////////////////////////////////////////////
// Write related methods
//

//
// CanWriteFile
//
bool FileListVideoIO::CanWriteFile(const char* filename)
{

  // Make sure file names have been specified
  std::vector<std::string> fileList = SplitFileNames(filename);
  if (fileList.size() == 0)
    {
    return false;
    }

  // Make sure all file names have the same extension
  for (unsigned int i = 1; i < fileList.size(); ++i)
    {
    int prevExtPos = fileList[i-1].rfind(".");
    int extPos = fileList[i].rfind(".");
    if (prevExtPos == -1 || extPos == -1)
      {
      return false;
      }
    std::string prevExt = fileList[i-1].substr(prevExtPos + 1, fileList[i-1].length()-prevExtPos-1);
    std::string ext = fileList[i].substr(extPos + 1, fileList[i].length()-extPos-1);

    if (strcmp(prevExt.c_str(), ext.c_str()))
      {
      return false;
      }
    }

  // Make sure we can instantiate an ImageIO to write the first file
  ImageIOBase::Pointer ioTemp = ImageIOFactory::CreateImageIO(
      fileList[0].c_str(), ImageIOFactory::WriteMode);
  if (ioTemp.IsNull())
    {
    return false;
    }

  return true;
}

//
// WriteImageInformation
//
void FileListVideoIO::WriteImageInformation()
{
  if (!this->m_WriterOpen)
    {
    this->OpenWriter();
    }
  this->m_ImageIO->SetFileName(this->m_FileNames[this->m_CurrentFrame]);
  this->m_ImageIO->WriteImageInformation();
}

//
// SetWriterParameters
//
void FileListVideoIO::SetWriterParameters(double fps, std::vector<SizeValueType> dim,
                                        const char* fourCC, unsigned int nChannels,
                                        IOComponentType componentType)
{
  this->m_Dimensions.clear();
  this->m_Origin.clear();
  this->m_NumberOfComponents = nChannels;
  for (unsigned int i = 0; i < dim.size(); ++i)
    {
    this->m_Dimensions.push_back(dim[i]);
    this->m_Origin.push_back(0);
    }

  // Set FpS even though we're not going to use it
  this->m_FpS = fps;

}

//
// Write
//
void FileListVideoIO::Write(const void *buffer)
{

  // Make sure parameters are specified
  if (this->m_Dimensions.size() == 0)
    {
    itkExceptionMacro("Can not write with empty parameters. You probably need to call SetWriterParameters");
    }

  // If the writer isn't open yet, open it
  if (!this->m_WriterOpen)
    {
    this->OpenWriter();
    }

  // Set the properties to the ImageIO
  this->m_ImageIO->SetNumberOfDimensions(this->m_Dimensions.size());
  for (unsigned int i = 0; i < this->m_Dimensions.size(); ++i)
    {
    this->m_ImageIO->SetDimensions(i, this->m_Dimensions[i]);
    this->m_ImageIO->SetOrigin(i, this->m_Origin[i]);
    }
  this->m_ImageIO->SetNumberOfComponents(this->m_NumberOfComponents);

  // Write with the ImageIO
  this->m_ImageIO->SetFileName(this->m_FileNames[this->m_CurrentFrame]);
  this->m_ImageIO->Write(buffer);

  // Move to the next frame
  if (this->m_CurrentFrame < this->m_FrameTotal-1)
    {
    this->m_CurrentFrame++;
    }

}

///////////////////////////////////////////////////////////////////////////////
// Protected methods
//

//
// OpenReader
//
void FileListVideoIO::OpenReader()
{
  if (this->m_ReaderOpen)
    {
    itkExceptionMacro("Can not open reader while video is already open for reading");
    }

  if (this->m_WriterOpen)
    {
    itkExceptionMacro("Can not open reader while video is already open for writing");
    }

  // Make sure FileNames have been specified
  if (this->m_FileNames.size() == 0)
    {
    itkExceptionMacro("Can not open reader without file names set");
    }

  // If neither reader nor writer is currently open, open the reader
  if (this->m_ReadType == ReadFromFile)
    {
    // Use the ImageIOFactory to instantiate a working ImageIO
    this->m_ImageIO = ImageIOFactory::CreateImageIO(
      this->m_FileNames[0].c_str(), ImageIOFactory::ReadMode);
    if (!this->m_ImageIO.IsNull())
      {
      this->m_ReaderOpen = true;
      }
    else
      {
      itkExceptionMacro("Video failed to open");
      }
    }
  else if (this->m_ReadType == ReadFromCamera)
    {
    itkExceptionMacro("FileListVideoIO doesn't support reading from camera");
    }
}

//
// OpenWriter
//
void FileListVideoIO::OpenWriter()
{
  if (this->m_WriterOpen)
    {
    itkExceptionMacro("Can not open writer while video is already open for writing");
    }

  if (this->m_ReaderOpen)
    {
    itkExceptionMacro("Can not open writer while video is already open for reading");
    }

  // Make sure FileNames have been specified
  if (this->m_FileNames.size() == 0)
    {
    itkExceptionMacro("Can not open reader without file names set");
    }

  // If neither reader nor writer is currently open, open the writer
  this->m_ImageIO = ImageIOFactory::CreateImageIO(
    this->m_FileNames[0].c_str(), ImageIOFactory::WriteMode);
  if (!this->m_ImageIO.IsNull())
    {
    this->m_WriterOpen = true;
    }
  else
    {
    itkExceptionMacro("File failed to open for writing");
    }
}

//
// ResetMembers
//
void FileListVideoIO::ResetMembers()
{
  this->m_ImageIO = NULL;
  this->m_FileNames.clear();
  this->m_WriterOpen = false;
  this->m_ReaderOpen = false;
  this->m_FpS = 0;
  this->m_Dimensions.clear();
  this->m_FrameTotal = 0;
  this->m_CurrentFrame = 0;
  this->m_NumberOfComponents = 0;
  this->m_IFrameInterval = 0;
  this->m_LastIFrame = 0;

  // Default to reading from a file
  this->m_ReadType = ReadFromFile;

  // Members from ImageIOBase
  this->m_PixelType = SCALAR;
  this->m_ComponentType = UCHAR;
  this->SetNumberOfDimensions(2);
  this->m_Spacing[0] = 1.0;
  this->m_Spacing[1] = 1.0;
  this->m_Origin[0] = 0.0;
  this->m_Origin[1] = 0.0;
}

} // end namespace itk
<commit_msg>ENH: Fix bad order issue with FileListVideoIO<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#include "itkFileListVideoIO.h"

#include "itkImage.h"
#include "itkImportImageFilter.h"
#include "itkImageIOFactory.h"

namespace itk
{

///////////////////////////////////////////////////////////////////////////////
// Constructor, Destructor, and Print
//

//
// Constructor
//
FileListVideoIO::FileListVideoIO()
{
  this->ResetMembers();
}

//
// Destructor
//
FileListVideoIO::~FileListVideoIO()
{
  this->FinishReadingOrWriting();
}

//
// PrintSelf
//
void FileListVideoIO::PrintSelf(std::ostream & os, Indent indent) const
{
  Superclass::PrintSelf(os,indent);
  if (!m_ImageIO.IsNull())
    {
    os << indent << "Internal ImageIO:" << std::endl;
    m_ImageIO->Print(os, indent.GetNextIndent());
    }
}

//
// FinishReadingOrWriting
//
void FileListVideoIO::FinishReadingOrWriting()
{
  this->ResetMembers();

}

///////////////////////////////////////////////////////////////////////////////
// Member Accessors
//

//
// GetPositionInMSec
//
double FileListVideoIO::GetPositionInMSec()
{
  return m_PositionInMSec;
}

//
// GetRatio
//
double FileListVideoIO::GetRatio()
{
  return m_Ratio;
}

//
// GetFrameTotal
//
unsigned long FileListVideoIO::GetFrameTotal()
{
  return m_FrameTotal;
}

//
// GetFpS
//
double FileListVideoIO::GetFpS()
{
  return m_FpS;
}

//
// GetCurrentFrame
//
unsigned long FileListVideoIO::GetCurrentFrame()
{
  return m_CurrentFrame;
}

//
// GetIFrameInterval
//
unsigned int FileListVideoIO::GetIFrameInterval()
{
  return m_IFrameInterval;
}

//
// GetLastIFrame
//
unsigned long FileListVideoIO::GetLastIFrame()
{
  return m_LastIFrame;
}

//
// SetFileName -- Split list based on ';'
//
void FileListVideoIO::SetFileName(const char* fileList)
{
  m_FileNames = SplitFileNames(fileList);

  // Set the number of frames
  m_FrameTotal = m_FileNames.size();
}

//
// SplitFileNames ';'
//
std::vector<std::string> FileListVideoIO::SplitFileNames(const char* fileList)
{
  std::string str = fileList;

  std::vector<std::string> out;

  int pos = 0;
  int len = str.length();
  while (pos != -1 && len > 0)
    {
    // Get the substring
    str = str.substr(pos, len);

    // Update pos
    pos = str.find(',');

    // Add the filename to the list
    out.push_back(str.substr(0,pos));

    // Move past the delimiter
    if (pos != -1)
      {
      pos++;
      }
    len -= pos;
    }

  return out;
}

///////////////////////////////////////////////////////////////////////////////
// Read related methods
//

//
// SetReadFromFile
//
void FileListVideoIO::SetReadFromFile()
{
  if (!m_ReaderOpen && !m_WriterOpen)
    {
    m_ReadType = ReadFromFile;
    }
  else
    {
    itkExceptionMacro("Cannot change read type while reader is open");
    }
}

//
// SetReadFromCamera
//
void FileListVideoIO::SetReadFromCamera()
{
  itkExceptionMacro("Read From Camera is not supported by this VideoIO");
}

//
// CanReadFile
//
bool FileListVideoIO::CanReadFile(const char* filename)
{
  // Make sure file names have been specified
  std::vector<std::string> fileList = SplitFileNames(filename);
  if (fileList.size() == 0)
    {
    return false;
    }

  // Make sure all file names have the same extension
  for (unsigned int i = 1; i < fileList.size(); ++i)
    {
    int prevExtPos = fileList[i-1].rfind(".");
    int extPos = fileList[i].rfind(".");
    if (prevExtPos == -1 || extPos == -1)
      {
      return false;
      }
    std::string prevExt = fileList[i-1].substr(prevExtPos + 1, fileList[i-1].length()-prevExtPos-1);
    std::string ext = fileList[i].substr(extPos + 1, fileList[i].length()-extPos-1);

    if (strcmp(prevExt.c_str(), ext.c_str()))
      {
      return false;
      }
    }

  // Make sure we can instantiate an ImageIO to read the first file
  ImageIOBase::Pointer ioTemp = ImageIOFactory::CreateImageIO(
      fileList[0].c_str(), ImageIOFactory::ReadMode);
  if (ioTemp.IsNull())
    {
    return false;
    }

  return true;
}

//
// CanReadCamera
//
bool FileListVideoIO::CanReadCamera( unsigned long cameraID )
{
  return false;
}

//
// ReadImageInformation
//
void FileListVideoIO::ReadImageInformation()
{
  // Open from a file
  if (m_ReadType == ReadFromFile)
    {

    // Make sure file can be read
    std::string filename = m_FileNames[0];
    if (!this->CanReadFile(filename.c_str()))
      {
      itkExceptionMacro(<< "Cannot Read File: " << filename);
      }

    // Open the internal IO (don't use local so that spacing, origin, direction
    // can be retrieved)
    if (!m_ReaderOpen)
      {
      this->OpenReader();
      }

    m_ImageIO->SetFileName(m_FileNames[0].c_str());
    m_ImageIO->ReadImageInformation();

    // No I-Frame issues to worry about
    m_IFrameInterval = 1;
    m_LastIFrame = m_FrameTotal-1;

    // Fill Dimensions and Origin
    m_Dimensions.clear();
    m_Origin.clear();
    this->SetNumberOfDimensions(m_ImageIO->GetNumberOfDimensions());
    for (unsigned int i = 0; i < m_ImageIO->GetNumberOfDimensions(); ++i)
      {
      m_Dimensions.push_back(m_ImageIO->GetDimensions(i));
      m_Origin.push_back(m_ImageIO->GetOrigin(i));
      }

    // Get other image info
    m_NumberOfComponents = m_ImageIO->GetNumberOfComponents();
    m_ComponentType = m_ImageIO->GetComponentType();
    m_PixelType = m_ImageIO->GetPixelType();

    // Make up an arbitrary FpS of 1
    m_FpS = 1;

    }

  // Open capture from a camera
  else if (m_ReadType == ReadFromCamera)
    {
    itkExceptionMacro("FileListVideoIO cannot read from a camera");
    }

  // Should never get here
  else
    {
    itkExceptionMacro("Invalid Read Type... How did we get here?");
    }
}

//
// Read
//
void FileListVideoIO::Read(void *buffer)
{
  // Make sure we've already called ReadImageInformation (dimensions are non-zero)
  if (m_Dimensions[0] == 0)
    {
    itkExceptionMacro(<< "Cannot read frame with zero dimension. May need to call ReadImageInformation");
    }

  // If video is not already open, open it and keep it open
  if (!m_ReaderOpen)
    {
    this->OpenReader();
    }

  // Read the desired frame
  m_ImageIO->SetFileName(m_FileNames[m_CurrentFrame]);
  m_ImageIO->Read(buffer);

  // Move on to the next frame
  if (m_CurrentFrame < m_FrameTotal - 1)
    {
    m_CurrentFrame++;
    }
}

//
// SetNextFrameToRead
//
bool FileListVideoIO::SetNextFrameToRead(unsigned long frameNumber)
{

  if (frameNumber >= m_FrameTotal)
    {
    return false;
    }

  m_CurrentFrame = frameNumber;
  return true;
}

//
// GetSpacing
//
double FileListVideoIO::GetSpacing(unsigned int i) const
{
  if (!m_ReaderOpen)
    {
    itkExceptionMacro("Can't get Spacing without ImageIO open for reading");
    }
  return m_ImageIO->GetSpacing(i);
}

//
// GetOrigin
//
double FileListVideoIO::GetOrigin(unsigned int i) const
{
  if (!m_ReaderOpen)
    {
    itkExceptionMacro("Can't get Origin without ImageIO open for reading");
    }
  return m_ImageIO->GetOrigin(i);
}

//
// GetDirection
//
std::vector< double > FileListVideoIO::GetDirection(unsigned int i) const
{
  if (!m_ReaderOpen)
    {
    itkExceptionMacro("Can't get Direction without ImageIO open for reading");
    }
  return m_ImageIO->GetDirection(i);
}

///////////////////////////////////////////////////////////////////////////////
// Write related methods
//

//
// CanWriteFile
//
bool FileListVideoIO::CanWriteFile(const char* filename)
{

  // Make sure file names have been specified
  std::vector<std::string> fileList = SplitFileNames(filename);
  if (fileList.size() == 0)
    {
    return false;
    }

  // Make sure all file names have the same extension
  for (unsigned int i = 1; i < fileList.size(); ++i)
    {
    int prevExtPos = fileList[i-1].rfind(".");
    int extPos = fileList[i].rfind(".");
    if (prevExtPos == -1 || extPos == -1)
      {
      return false;
      }
    std::string prevExt = fileList[i-1].substr(prevExtPos + 1, fileList[i-1].length()-prevExtPos-1);
    std::string ext = fileList[i].substr(extPos + 1, fileList[i].length()-extPos-1);

    if (strcmp(prevExt.c_str(), ext.c_str()))
      {
      return false;
      }
    }

  // Make sure we can instantiate an ImageIO to write the first file
  ImageIOBase::Pointer ioTemp = ImageIOFactory::CreateImageIO(
      fileList[0].c_str(), ImageIOFactory::WriteMode);
  if (ioTemp.IsNull())
    {
    return false;
    }

  return true;
}

//
// WriteImageInformation
//
void FileListVideoIO::WriteImageInformation()
{
  if (!m_WriterOpen)
    {
    this->OpenWriter();
    }
  m_ImageIO->SetFileName(m_FileNames[m_CurrentFrame]);
  m_ImageIO->WriteImageInformation();
}

//
// SetWriterParameters
//
void FileListVideoIO::SetWriterParameters(double fps, std::vector<SizeValueType> dim,
                                        const char* fourCC, unsigned int nChannels,
                                        IOComponentType componentType)
{
  m_Dimensions.clear();
  m_Origin.clear();
  m_NumberOfComponents = nChannels;
  for (unsigned int i = 0; i < dim.size(); ++i)
    {
    m_Dimensions.push_back(dim[i]);
    m_Origin.push_back(0);
    }

  // Set FpS even though we're not going to use it
  m_FpS = fps;

}

//
// Write
//
void FileListVideoIO::Write(const void *buffer)
{

  // Make sure parameters are specified
  if (m_Dimensions.size() == 0)
    {
    itkExceptionMacro("Can not write with empty parameters. You probably need to call SetWriterParameters");
    }

  // If the writer isn't open yet, open it
  if (!m_WriterOpen)
    {
    this->OpenWriter();
    }

  // Set the properties to the ImageIO
  m_ImageIO->SetNumberOfDimensions(m_Dimensions.size());
  for (unsigned int i = 0; i < m_Dimensions.size(); ++i)
    {
    m_ImageIO->SetDimensions(i, m_Dimensions[i]);
    m_ImageIO->SetOrigin(i, m_Origin[i]);
    }
  m_ImageIO->SetNumberOfComponents(m_NumberOfComponents);

  // Write with the ImageIO
  m_ImageIO->SetFileName(m_FileNames[m_CurrentFrame]);
  m_ImageIO->Write(buffer);

  // Move to the next frame
  if (m_CurrentFrame < m_FrameTotal-1)
    {
    m_CurrentFrame++;
    }

}

///////////////////////////////////////////////////////////////////////////////
// Protected methods
//

//
// OpenReader
//
void FileListVideoIO::OpenReader()
{
  if (m_ReaderOpen)
    {
    itkExceptionMacro("Can not open reader while video is already open for reading");
    }

  if (m_WriterOpen)
    {
    itkExceptionMacro("Can not open reader while video is already open for writing");
    }

  // Make sure FileNames have been specified
  if (m_FileNames.size() == 0)
    {
    itkExceptionMacro("Can not open reader without file names set");
    }

  // If neither reader nor writer is currently open, open the reader
  if (m_ReadType == ReadFromFile)
    {
    // Use the ImageIOFactory to instantiate a working ImageIO
    m_ImageIO = ImageIOFactory::CreateImageIO(
      m_FileNames[0].c_str(), ImageIOFactory::ReadMode);
    if (!m_ImageIO.IsNull())
      {
      m_ReaderOpen = true;
      }
    else
      {
      itkExceptionMacro("Video failed to open");
      }
    }
  else if (m_ReadType == ReadFromCamera)
    {
    itkExceptionMacro("FileListVideoIO doesn't support reading from camera");
    }
}

//
// OpenWriter
//
void FileListVideoIO::OpenWriter()
{
  if (m_WriterOpen)
    {
    itkExceptionMacro("Can not open writer while video is already open for writing");
    }

  if (m_ReaderOpen)
    {
    itkExceptionMacro("Can not open writer while video is already open for reading");
    }

  // Make sure FileNames have been specified
  if (m_FileNames.size() == 0)
    {
    itkExceptionMacro("Can not open reader without file names set");
    }

  // If neither reader nor writer is currently open, open the writer
  m_ImageIO = ImageIOFactory::CreateImageIO(
    m_FileNames[0].c_str(), ImageIOFactory::WriteMode);
  if (!m_ImageIO.IsNull())
    {
    m_WriterOpen = true;
    }
  else
    {
    itkExceptionMacro("File failed to open for writing");
    }
}

//
// ResetMembers
//
void FileListVideoIO::ResetMembers()
{
  m_ImageIO = NULL;
  m_FileNames.clear();
  m_WriterOpen = false;
  m_ReaderOpen = false;
  m_FpS = 0;
  m_Dimensions.clear();
  m_FrameTotal = 0;
  m_CurrentFrame = 0;
  m_NumberOfComponents = 0;
  m_IFrameInterval = 0;
  m_LastIFrame = 0;

  // Default to reading from a file
  m_ReadType = ReadFromFile;

  // Members from ImageIOBase
  m_PixelType = SCALAR;
  m_ComponentType = UCHAR;
  this->SetNumberOfDimensions(2);
  m_Spacing[0] = 1.0;
  m_Spacing[1] = 1.0;
  m_Origin[0] = 0.0;
  m_Origin[1] = 0.0;
}

} // end namespace itk
<|endoftext|>


<commit_before>// -------------------------------------------------------------------------
//    @FileName			:    NFCLoginLogicModule.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2013-01-02
//    @Module           :    NFCLoginLogicModule
//    @Desc             :
// -------------------------------------------------------------------------

#include "NFLoginLogicPlugin.h"
#include "NFCLoginLogicModule.h"

bool NFCLoginLogicModule::Init()
{
	m_pAccountRedisModule = pPluginManager->FindModule<NFIAccountRedisModule>();
	m_pNetModule = pPluginManager->FindModule<NFINetModule>();
	m_pLogModule = pPluginManager->FindModule<NFILogModule>();

    return true;
}

bool NFCLoginLogicModule::Shut()
{
    return true;
}

void NFCLoginLogicModule::OnLoginProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)
{
    NFGUID nPlayerID;
	NFMsg::ReqAccountLogin xMsg;
	if (!m_pNetModule->ReceivePB(nSockIndex, nMsgID, msg, nLen, xMsg, nPlayerID))
	{
		return;
	}

	NetObject* pNetObject = m_pNetModule->GetNet()->GetNetObject(nSockIndex);
	if (pNetObject)
	{
		if (pNetObject->GetConnectKeyState() == 0)
		{
			if (m_pAccountRedisModule->ExistAccount(xMsg.account()))
			{
				m_pAccountRedisModule->AddAccount(xMsg.account(), xMsg.password());
			}

			int nState = m_pAccountRedisModule->VerifyAccount(xMsg.account(), xMsg.password());
			if (0 != nState)
			{
				std::ostringstream strLog;
				strLog << "Check password failed, Account = " << xMsg.account() << " Password = " << xMsg.password();
				m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, NFGUID(0, nSockIndex), strLog, __FUNCTION__, __LINE__);

				NFMsg::AckEventResult xMsg;
				xMsg.set_event_code(NFMsg::EGEC_ACCOUNTPWD_INVALID);

				m_pNetModule->SendMsgPB(NFMsg::EGameMsgID::EGMI_ACK_LOGIN, xMsg, nSockIndex);
				return;
			}

			pNetObject->SetConnectKeyState(1);
			pNetObject->SetAccount(xMsg.account());

			NFMsg::AckEventResult xData;
			xData.set_event_code(NFMsg::EGEC_ACCOUNT_SUCCESS);

			m_pNetModule->SendMsgPB(NFMsg::EGameMsgID::EGMI_ACK_LOGIN, xData, nSockIndex);

			m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "Login successed :", xMsg.account().c_str());
		}
	}
}

bool NFCLoginLogicModule::ReadyExecute()
{
	m_pNetModule->RemoveReceiveCallBack(NFMsg::EGMI_REQ_LOGIN);
	m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_LOGIN, this, &NFCLoginLogicModule::OnLoginProcess);

    return true;
}

bool NFCLoginLogicModule::Execute()
{

    return true;
}

bool NFCLoginLogicModule::AfterInit()
{
    return true;
}
<commit_msg>add "!" to fixed the problem that judge the return value when query a key<commit_after>// -------------------------------------------------------------------------
//    @FileName			:    NFCLoginLogicModule.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2013-01-02
//    @Module           :    NFCLoginLogicModule
//    @Desc             :
// -------------------------------------------------------------------------

#include "NFLoginLogicPlugin.h"
#include "NFCLoginLogicModule.h"

bool NFCLoginLogicModule::Init()
{
	m_pAccountRedisModule = pPluginManager->FindModule<NFIAccountRedisModule>();
	m_pNetModule = pPluginManager->FindModule<NFINetModule>();
	m_pLogModule = pPluginManager->FindModule<NFILogModule>();

    return true;
}

bool NFCLoginLogicModule::Shut()
{
    return true;
}

void NFCLoginLogicModule::OnLoginProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)
{
    NFGUID nPlayerID;
	NFMsg::ReqAccountLogin xMsg;
	if (!m_pNetModule->ReceivePB(nSockIndex, nMsgID, msg, nLen, xMsg, nPlayerID))
	{
		return;
	}

	NetObject* pNetObject = m_pNetModule->GetNet()->GetNetObject(nSockIndex);
	if (pNetObject)
	{
		if (pNetObject->GetConnectKeyState() == 0)
		{
			if (!m_pAccountRedisModule->ExistAccount(xMsg.account()))
			{
				m_pAccountRedisModule->AddAccount(xMsg.account(), xMsg.password());
			}

			int nState = m_pAccountRedisModule->VerifyAccount(xMsg.account(), xMsg.password());
			if (0 != nState)
			{
				std::ostringstream strLog;
				strLog << "Check password failed, Account = " << xMsg.account() << " Password = " << xMsg.password();
				m_pLogModule->LogNormal(NFILogModule::NLL_ERROR_NORMAL, NFGUID(0, nSockIndex), strLog, __FUNCTION__, __LINE__);

				NFMsg::AckEventResult xMsg;
				xMsg.set_event_code(NFMsg::EGEC_ACCOUNTPWD_INVALID);

				m_pNetModule->SendMsgPB(NFMsg::EGameMsgID::EGMI_ACK_LOGIN, xMsg, nSockIndex);
				return;
			}

			pNetObject->SetConnectKeyState(1);
			pNetObject->SetAccount(xMsg.account());

			NFMsg::AckEventResult xData;
			xData.set_event_code(NFMsg::EGEC_ACCOUNT_SUCCESS);

			m_pNetModule->SendMsgPB(NFMsg::EGameMsgID::EGMI_ACK_LOGIN, xData, nSockIndex);

			m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "Login successed :", xMsg.account().c_str());
		}
	}
}

bool NFCLoginLogicModule::ReadyExecute()
{
	m_pNetModule->RemoveReceiveCallBack(NFMsg::EGMI_REQ_LOGIN);
	m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_LOGIN, this, &NFCLoginLogicModule::OnLoginProcess);

    return true;
}

bool NFCLoginLogicModule::Execute()
{

    return true;
}

bool NFCLoginLogicModule::AfterInit()
{
    return true;
}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <mitkGL.h>
#include "mitkSurfaceMapper2D.h"
#include "mitkBaseRenderer.h"
#include "mitkPlaneGeometry.h"
#include "mitkSurface.h"
#include "mitkColorProperty.h"
#include "mitkProperties.h"
#include "mitkVtkScalarModeProperty.h"
#include "mitkAbstractTransformGeometry.h"
#include "mitkLookupTableProperty.h"

#include <vtkPolyData.h>
#include <vtkPolyDataSource.h>
#include <vtkPlane.h>
#include <vtkCutter.h>
#include <vtkPoints.h>
#include <vtkCellArray.h>
#include <vtkLookupTable.h>
#include <vtkPointData.h>
#include <vtkCellData.h>
#include <vtkDataArray.h>
#include <vtkPolyData.h>
#include <vtkLinearTransform.h>
#include <vtkAbstractMapper.h>

//##ModelId=3EF180540006
mitk::SurfaceMapper2D::SurfaceMapper2D()
{
  m_Plane  = vtkPlane::New();
  m_Cutter = vtkCutter::New();

  m_Cutter->SetCutFunction(m_Plane);
  m_Cutter->GenerateValues(1,0,1);

  m_LUT = vtkLookupTable::New();
  m_LUT->SetTableRange(0,255);
  m_LUT->SetNumberOfColors(255);
  m_LUT->SetRampToLinear();
  m_LUT->Build();
}

//##ModelId=3EF180540019
mitk::SurfaceMapper2D::~SurfaceMapper2D()
{
}

//##ModelId=3EF18053036B
const mitk::Surface *mitk::SurfaceMapper2D::GetInput(void)
{
  if(m_Surface.IsNotNull())
    return m_Surface;

  return static_cast<const mitk::Surface * > ( GetData() );
}

void mitk::SurfaceMapper2D::SetDataTreeNode( mitk::DataTreeNode::Pointer node )
{
  Superclass::SetDataTreeNode( node );

  bool useCellData;
  if (dynamic_cast<mitk::BoolProperty *>(node->GetProperty("deprecated useCellDataForColouring").GetPointer()) == NULL)
    useCellData = false;
  else
    useCellData = dynamic_cast<mitk::BoolProperty *>(node->GetProperty("deprecated useCellDataForColouring").GetPointer())->GetValue();

  if (!useCellData)
  {
    // search min/max point scalars over all time steps
#if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) ))
    double dataRange[2] = {0,0};
    double range[2];
#else
    float dataRange[2] = {0,0};
    float range[2];
#endif

    mitk::Surface::Pointer input  = const_cast< mitk::Surface* >(dynamic_cast<const mitk::Surface*>( this->GetDataTreeNode()->GetData() ));
    if(input.IsNull()) return;
    const TimeSlicedGeometry::Pointer inputTimeGeometry = input->GetTimeSlicedGeometry();
    if(( inputTimeGeometry.IsNull() ) || ( inputTimeGeometry->GetTimeSteps() == 0 ) ) return;
    for (unsigned int timestep=0; timestep<inputTimeGeometry->GetTimeSteps(); timestep++)
    {
      vtkPolyData * vtkpolydata = input->GetVtkPolyData( timestep );
      if((vtkpolydata==NULL) || (vtkpolydata->GetNumberOfPoints() < 1 )) continue;
      vtkDataArray *vpointscalars = vtkpolydata->GetPointData()->GetScalars();
      if (vpointscalars) {
        vpointscalars->GetRange( range, 0 );
        if (dataRange[0]==0 && dataRange[1]==0) {
          dataRange[0] = range[0];
          dataRange[1] = range[1];
        }
        else {
          if (range[0] < dataRange[0]) dataRange[0] = range[0];
          if (range[1] > dataRange[1]) dataRange[1] = range[1];
        }
      }
    }
    if (dataRange[1] - dataRange[0] > 0) {
      m_LUT->SetTableRange( dataRange );
      m_LUT->Build();
    }
  }
}

//##ModelId=3EF18053039D
void mitk::SurfaceMapper2D::Paint(mitk::BaseRenderer * renderer)
{
  if(IsVisible(renderer)==false) return;

  mitk::Surface::Pointer input  = const_cast<mitk::Surface*>(this->GetInput());

  if(input.IsNull())
    return;

  //
  // get the TimeSlicedGeometry of the input object
  //
  const TimeSlicedGeometry* inputTimeGeometry = input->GetTimeSlicedGeometry();
  if(( inputTimeGeometry == NULL ) || ( inputTimeGeometry->GetTimeSteps() == 0 ) )
    return;

  if (dynamic_cast<mitk::IntProperty *>(this->GetDataTreeNode()->GetProperty("lineWidth").GetPointer()) == NULL)
    m_LineWidth = 1;
  else
    m_LineWidth = dynamic_cast<mitk::IntProperty *>(this->GetDataTreeNode()->GetProperty("lineWidth").GetPointer())->GetValue();

  //
  // get the world time
  //
  Geometry2D::ConstPointer worldGeometry = renderer->GetCurrentWorldGeometry2D();
  assert( worldGeometry.IsNotNull() );
  ScalarType time = worldGeometry->GetTimeBounds()[ 0 ];

  //
  // convert the world time to time steps of the input object
  //
  int timestep=0;
  if( time > -ScalarTypeNumericTraits::max() )
    timestep = inputTimeGeometry->MSToTimeStep( time );
  if( inputTimeGeometry->IsValidTime( timestep ) == false )
    return;

  vtkPolyData * vtkpolydata = input->GetVtkPolyData( timestep );
  if((vtkpolydata==NULL) || (vtkpolydata->GetNumberOfPoints() < 1 ))
    return;

  PlaneGeometry::ConstPointer worldPlaneGeometry = dynamic_cast<const PlaneGeometry*>(worldGeometry.GetPointer());

  if(vtkpolydata!=NULL)
  {
    Point3D point;
    Vector3D normal;

    // Check if Lookup-Table is already given, else use standard one.
    double *scalarLimits = m_LUT->GetTableRange();
    double scalarsMin = scalarLimits[0], scalarsMax = scalarLimits[1];

    vtkLookupTable *lut = vtkLookupTable::New();

    mitk::LookupTableProperty::Pointer lookupTableProp;
    this->GetDataTreeNode()->GetProperty(lookupTableProp, "LookupTable", renderer);
    if (lookupTableProp.IsNotNull() )
    {
      lut = lookupTableProp->GetLookupTable()->GetVtkLookupTable();

      if (dynamic_cast<mitk::FloatProperty *>(this->GetDataTreeNode()->GetProperty("ScalarsRangeMinimum").GetPointer()) != NULL)
        scalarsMin = dynamic_cast<mitk::FloatProperty*>(this->GetDataTreeNode()->GetProperty("ScalarsRangeMinimum").GetPointer())->GetValue();
      if (dynamic_cast<mitk::FloatProperty *>(this->GetDataTreeNode()->GetProperty("ScalarsRangeMaximum").GetPointer()) != NULL)
        scalarsMax = dynamic_cast<mitk::FloatProperty*>(this->GetDataTreeNode()->GetProperty("ScalarsRangeMaximum").GetPointer())->GetValue();

      lut->SetTableRange(scalarsMin, scalarsMax);
    }
    else
    {
      lut = m_LUT;
    }

    vtkLinearTransform * vtktransform = GetDataTreeNode()->GetVtkTransform();
    if(worldPlaneGeometry.IsNotNull())
    {
      // set up vtkPlane according to worldGeometry
      point=worldPlaneGeometry->GetOrigin();
      normal=worldPlaneGeometry->GetNormal(); normal.Normalize();
      m_Plane->SetTransform((vtkAbstractTransform*)NULL);
    }
    else
    {
      AbstractTransformGeometry::ConstPointer worldAbstractGeometry = dynamic_cast<const AbstractTransformGeometry*>(renderer->GetCurrentWorldGeometry2D());
      if(worldAbstractGeometry.IsNotNull())
      {
        AbstractTransformGeometry::ConstPointer surfaceAbstractGeometry = dynamic_cast<const AbstractTransformGeometry*>(input->GetTimeSlicedGeometry()->GetGeometry3D(0));
        if(surfaceAbstractGeometry.IsNotNull()) //@todo substitude by operator== after implementation, see bug id 28
        {
          PaintCells(renderer, vtkpolydata, worldGeometry, renderer->GetDisplayGeometry(), vtktransform, lut);
          return;
        }
        else
        {
          //@FIXME: does not work correctly. Does m_Plane->SetTransform really transforms a "plane plane" into a "curved plane"?
          return;
          // set up vtkPlane according to worldGeometry
          point=const_cast<mitk::BoundingBox*>(worldAbstractGeometry->GetParametricBoundingBox())->GetMinimum();
          FillVector3D(normal, 0, 0, 1);
          m_Plane->SetTransform(worldAbstractGeometry->GetVtkAbstractTransform()->GetInverse());
        }
      }
      else
        return;
    }

#if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) ))
    double vp[3], vnormal[3];
#else
    float vp[3], vnormal[3];
#endif

    vnl2vtk(point.Get_vnl_vector(), vp);
    vnl2vtk(normal.Get_vnl_vector(), vnormal);

    //normally, we would need to transform the surface and cut the transformed surface with the cutter.
    //This might be quite slow. Thus, the idea is, to perform an inverse transform of the plane instead.
    //@todo It probably does not work for scaling operations yet:scaling operations have to be
    //dealed with after the cut is performed by scaling the contour.
    vtkLinearTransform * inversetransform = vtktransform->GetLinearInverse();
    inversetransform->TransformPoint(vp, vp);
    inversetransform->TransformNormalAtPoint(vp, vnormal, vnormal);

    m_Plane->SetOrigin(vp);
    m_Plane->SetNormal(vnormal);

    // set data into cutter
    m_Cutter->SetInput(vtkpolydata);
    //    m_Cutter->GenerateCutScalarsOff();
    //    m_Cutter->SetSortByToSortByCell();

    // calculate the cut
    m_Cutter->Update();

    //apply color and opacity read from the PropertyList
    ApplyProperties(renderer);

    // travers the cut contour
    PaintCells(renderer, m_Cutter->GetOutput(), worldGeometry, renderer->GetDisplayGeometry(), vtktransform, lut);
  }
}

void mitk::SurfaceMapper2D::PaintCells(mitk::BaseRenderer* renderer, vtkPolyData* contour, const mitk::Geometry2D* worldGeometry, const mitk::DisplayGeometry* displayGeometry, vtkLinearTransform * vtktransform, vtkLookupTable *lut)
{
  // deprecated settings
  bool usePointData = false;

  bool useCellData = false;
  this->GetDataTreeNode()->GetBoolProperty("deprecated useCellDataForColouring", useCellData);

  bool scalarVisibility = false;
  this->GetDataTreeNode()->GetBoolProperty("scalar visibility", scalarVisibility);

  if(scalarVisibility)
  {
    mitk::VtkScalarModeProperty* scalarMode;
    if(this->GetDataTreeNode()->GetProperty(scalarMode, "scalar mode", renderer))
    {
      if( (scalarMode->GetVtkScalarMode() == VTK_SCALAR_MODE_USE_POINT_DATA) ||
        (scalarMode->GetVtkScalarMode() == VTK_SCALAR_MODE_DEFAULT) )
      {
        usePointData = true;
      }
      if(scalarMode->GetVtkScalarMode() == VTK_SCALAR_MODE_USE_CELL_DATA)
      {
        useCellData = true;
      }
    }
    else
    {
      usePointData = true;
    }
  }

  vtkPoints    *vpoints = contour->GetPoints();
  vtkDataArray *vpointscalars = contour->GetPointData()->GetScalars();

  vtkCellArray *vlines  = contour->GetLines();
  vtkDataArray* vcellscalars = contour->GetCellData()->GetScalars();

  Point3D p; Point2D p2d, last;
  int i, j;
  int numberOfLines = vlines->GetNumberOfCells();

  glLineWidth( m_LineWidth );
  glBegin (GL_LINES);

  vlines->InitTraversal();
  for(i=0;i<numberOfLines;++i)
  {
    int *cell, cellSize;
#if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) ))
    double vp[3];
#else
    float vp[3];
#endif

    vlines->GetNextCell(cellSize, cell);

    vpoints->GetPoint(cell[0], vp);
    //take transformation via vtktransform into account
    vtktransform->TransformPoint(vp, vp);
    vtk2itk(vp, p);

    //convert 3D point (in mm) to 2D point on slice (also in mm)
    worldGeometry->Map(p, p2d);

    //convert point (until now mm and in worldcoordinates) to display coordinates (units )
    displayGeometry->WorldToDisplay(p2d, p2d);
    last=p2d;

    for(j=1; j<cellSize; ++j)
    {
      vpoints->GetPoint(cell[j], vp);
      //take transformation via vtktransform into account
      vtktransform->TransformPoint(vp, vp);
      vtk2itk(vp, p);

      //convert 3D point (in mm) to 2D point on slice (also in mm)
      worldGeometry->Map(p, p2d);

      //convert point (until now mm and in worldcoordinates) to display coordinates (units )
      displayGeometry->WorldToDisplay(p2d, p2d);

      vtkFloatingPointType color[3];
      if (useCellData && vcellscalars != NULL )
      {
        // color each cell according to cell data
        lut->GetColor( vcellscalars->GetComponent(i,0),color);
        glColor3f(color[0],color[1],color[2]);
        glVertex2f(last[0], last[1]);
        glVertex2f(p2d[0], p2d[1]);
      }
      else if (usePointData && vpointscalars != NULL )
      {
        lut->GetColor( vpointscalars->GetComponent(cell[j-1],0),color);
        glColor3f(color[0],color[1],color[2]);
        glVertex2f(last[0], last[1]);
        lut->GetColor( vpointscalars->GetComponent(cell[j],0),color);
        glColor3f(color[0],color[1],color[2]);
        glVertex2f(p2d[0], p2d[1]);
      }
      else {
        glVertex2f(last[0], last[1]);
        glVertex2f(p2d[0], p2d[1]);
      }
      last=p2d;
    }
  }

  glEnd ();
  glLineWidth(1.0);
}
<commit_msg>ADD: Explicit build call (maybe unnecessary ? )<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <mitkGL.h>
#include "mitkSurfaceMapper2D.h"
#include "mitkBaseRenderer.h"
#include "mitkPlaneGeometry.h"
#include "mitkSurface.h"
#include "mitkColorProperty.h"
#include "mitkProperties.h"
#include "mitkVtkScalarModeProperty.h"
#include "mitkAbstractTransformGeometry.h"
#include "mitkLookupTableProperty.h"

#include <vtkPolyData.h>
#include <vtkPolyDataSource.h>
#include <vtkPlane.h>
#include <vtkCutter.h>
#include <vtkPoints.h>
#include <vtkCellArray.h>
#include <vtkLookupTable.h>
#include <vtkPointData.h>
#include <vtkCellData.h>
#include <vtkDataArray.h>
#include <vtkPolyData.h>
#include <vtkLinearTransform.h>
#include <vtkAbstractMapper.h>

//##ModelId=3EF180540006
mitk::SurfaceMapper2D::SurfaceMapper2D()
{
  m_Plane  = vtkPlane::New();
  m_Cutter = vtkCutter::New();

  m_Cutter->SetCutFunction(m_Plane);
  m_Cutter->GenerateValues(1,0,1);

  m_LUT = vtkLookupTable::New();
  m_LUT->SetTableRange(0,255);
  m_LUT->SetNumberOfColors(255);
  m_LUT->SetRampToLinear();
  m_LUT->Build();
}

//##ModelId=3EF180540019
mitk::SurfaceMapper2D::~SurfaceMapper2D()
{
}

//##ModelId=3EF18053036B
const mitk::Surface *mitk::SurfaceMapper2D::GetInput(void)
{
  if(m_Surface.IsNotNull())
    return m_Surface;

  return static_cast<const mitk::Surface * > ( GetData() );
}

void mitk::SurfaceMapper2D::SetDataTreeNode( mitk::DataTreeNode::Pointer node )
{
  Superclass::SetDataTreeNode( node );

  bool useCellData;
  if (dynamic_cast<mitk::BoolProperty *>(node->GetProperty("deprecated useCellDataForColouring").GetPointer()) == NULL)
    useCellData = false;
  else
    useCellData = dynamic_cast<mitk::BoolProperty *>(node->GetProperty("deprecated useCellDataForColouring").GetPointer())->GetValue();

  if (!useCellData)
  {
    // search min/max point scalars over all time steps
#if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) ))
    double dataRange[2] = {0,0};
    double range[2];
#else
    float dataRange[2] = {0,0};
    float range[2];
#endif

    mitk::Surface::Pointer input  = const_cast< mitk::Surface* >(dynamic_cast<const mitk::Surface*>( this->GetDataTreeNode()->GetData() ));
    if(input.IsNull()) return;
    const TimeSlicedGeometry::Pointer inputTimeGeometry = input->GetTimeSlicedGeometry();
    if(( inputTimeGeometry.IsNull() ) || ( inputTimeGeometry->GetTimeSteps() == 0 ) ) return;
    for (unsigned int timestep=0; timestep<inputTimeGeometry->GetTimeSteps(); timestep++)
    {
      vtkPolyData * vtkpolydata = input->GetVtkPolyData( timestep );
      if((vtkpolydata==NULL) || (vtkpolydata->GetNumberOfPoints() < 1 )) continue;
      vtkDataArray *vpointscalars = vtkpolydata->GetPointData()->GetScalars();
      if (vpointscalars) {
        vpointscalars->GetRange( range, 0 );
        if (dataRange[0]==0 && dataRange[1]==0) {
          dataRange[0] = range[0];
          dataRange[1] = range[1];
        }
        else {
          if (range[0] < dataRange[0]) dataRange[0] = range[0];
          if (range[1] > dataRange[1]) dataRange[1] = range[1];
        }
      }
    }
    if (dataRange[1] - dataRange[0] > 0) {
      m_LUT->SetTableRange( dataRange );
      m_LUT->Build();
    }
  }
}

//##ModelId=3EF18053039D
void mitk::SurfaceMapper2D::Paint(mitk::BaseRenderer * renderer)
{
  if(IsVisible(renderer)==false) return;

  mitk::Surface::Pointer input  = const_cast<mitk::Surface*>(this->GetInput());

  if(input.IsNull())
    return;

  //
  // get the TimeSlicedGeometry of the input object
  //
  const TimeSlicedGeometry* inputTimeGeometry = input->GetTimeSlicedGeometry();
  if(( inputTimeGeometry == NULL ) || ( inputTimeGeometry->GetTimeSteps() == 0 ) )
    return;

  if (dynamic_cast<mitk::IntProperty *>(this->GetDataTreeNode()->GetProperty("lineWidth").GetPointer()) == NULL)
    m_LineWidth = 1;
  else
    m_LineWidth = dynamic_cast<mitk::IntProperty *>(this->GetDataTreeNode()->GetProperty("lineWidth").GetPointer())->GetValue();

  //
  // get the world time
  //
  Geometry2D::ConstPointer worldGeometry = renderer->GetCurrentWorldGeometry2D();
  assert( worldGeometry.IsNotNull() );
  ScalarType time = worldGeometry->GetTimeBounds()[ 0 ];

  //
  // convert the world time to time steps of the input object
  //
  int timestep=0;
  if( time > -ScalarTypeNumericTraits::max() )
    timestep = inputTimeGeometry->MSToTimeStep( time );
  if( inputTimeGeometry->IsValidTime( timestep ) == false )
    return;

  vtkPolyData * vtkpolydata = input->GetVtkPolyData( timestep );
  if((vtkpolydata==NULL) || (vtkpolydata->GetNumberOfPoints() < 1 ))
    return;

  PlaneGeometry::ConstPointer worldPlaneGeometry = dynamic_cast<const PlaneGeometry*>(worldGeometry.GetPointer());

  if(vtkpolydata!=NULL)
  {
    Point3D point;
    Vector3D normal;

    // Check if Lookup-Table is already given, else use standard one.
    double *scalarLimits = m_LUT->GetTableRange();
    double scalarsMin = scalarLimits[0], scalarsMax = scalarLimits[1];

    vtkLookupTable *lut = vtkLookupTable::New();

    mitk::LookupTableProperty::Pointer lookupTableProp;
    this->GetDataTreeNode()->GetProperty(lookupTableProp, "LookupTable", renderer);
    if (lookupTableProp.IsNotNull() )
    {
      lut = lookupTableProp->GetLookupTable()->GetVtkLookupTable();

      if (dynamic_cast<mitk::FloatProperty *>(this->GetDataTreeNode()->GetProperty("ScalarsRangeMinimum").GetPointer()) != NULL)
        scalarsMin = dynamic_cast<mitk::FloatProperty*>(this->GetDataTreeNode()->GetProperty("ScalarsRangeMinimum").GetPointer())->GetValue();
      if (dynamic_cast<mitk::FloatProperty *>(this->GetDataTreeNode()->GetProperty("ScalarsRangeMaximum").GetPointer()) != NULL)
        scalarsMax = dynamic_cast<mitk::FloatProperty*>(this->GetDataTreeNode()->GetProperty("ScalarsRangeMaximum").GetPointer())->GetValue();

      lut->SetTableRange(scalarsMin, scalarsMax);
      lut->Build();
    }
    else
    {
      lut = m_LUT;
    }

    vtkLinearTransform * vtktransform = GetDataTreeNode()->GetVtkTransform();
    if(worldPlaneGeometry.IsNotNull())
    {
      // set up vtkPlane according to worldGeometry
      point=worldPlaneGeometry->GetOrigin();
      normal=worldPlaneGeometry->GetNormal(); normal.Normalize();
      m_Plane->SetTransform((vtkAbstractTransform*)NULL);
    }
    else
    {
      AbstractTransformGeometry::ConstPointer worldAbstractGeometry = dynamic_cast<const AbstractTransformGeometry*>(renderer->GetCurrentWorldGeometry2D());
      if(worldAbstractGeometry.IsNotNull())
      {
        AbstractTransformGeometry::ConstPointer surfaceAbstractGeometry = dynamic_cast<const AbstractTransformGeometry*>(input->GetTimeSlicedGeometry()->GetGeometry3D(0));
        if(surfaceAbstractGeometry.IsNotNull()) //@todo substitude by operator== after implementation, see bug id 28
        {
          PaintCells(renderer, vtkpolydata, worldGeometry, renderer->GetDisplayGeometry(), vtktransform, lut);
          return;
        }
        else
        {
          //@FIXME: does not work correctly. Does m_Plane->SetTransform really transforms a "plane plane" into a "curved plane"?
          return;
          // set up vtkPlane according to worldGeometry
          point=const_cast<mitk::BoundingBox*>(worldAbstractGeometry->GetParametricBoundingBox())->GetMinimum();
          FillVector3D(normal, 0, 0, 1);
          m_Plane->SetTransform(worldAbstractGeometry->GetVtkAbstractTransform()->GetInverse());
        }
      }
      else
        return;
    }

#if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) ))
    double vp[3], vnormal[3];
#else
    float vp[3], vnormal[3];
#endif

    vnl2vtk(point.Get_vnl_vector(), vp);
    vnl2vtk(normal.Get_vnl_vector(), vnormal);

    //normally, we would need to transform the surface and cut the transformed surface with the cutter.
    //This might be quite slow. Thus, the idea is, to perform an inverse transform of the plane instead.
    //@todo It probably does not work for scaling operations yet:scaling operations have to be
    //dealed with after the cut is performed by scaling the contour.
    vtkLinearTransform * inversetransform = vtktransform->GetLinearInverse();
    inversetransform->TransformPoint(vp, vp);
    inversetransform->TransformNormalAtPoint(vp, vnormal, vnormal);

    m_Plane->SetOrigin(vp);
    m_Plane->SetNormal(vnormal);

    // set data into cutter
    m_Cutter->SetInput(vtkpolydata);
    //    m_Cutter->GenerateCutScalarsOff();
    //    m_Cutter->SetSortByToSortByCell();

    // calculate the cut
    m_Cutter->Update();

    //apply color and opacity read from the PropertyList
    ApplyProperties(renderer);

    // travers the cut contour
    PaintCells(renderer, m_Cutter->GetOutput(), worldGeometry, renderer->GetDisplayGeometry(), vtktransform, lut);
  }
}

void mitk::SurfaceMapper2D::PaintCells(mitk::BaseRenderer* renderer, vtkPolyData* contour, const mitk::Geometry2D* worldGeometry, const mitk::DisplayGeometry* displayGeometry, vtkLinearTransform * vtktransform, vtkLookupTable *lut)
{
  // deprecated settings
  bool usePointData = false;

  bool useCellData = false;
  this->GetDataTreeNode()->GetBoolProperty("deprecated useCellDataForColouring", useCellData);

  bool scalarVisibility = false;
  this->GetDataTreeNode()->GetBoolProperty("scalar visibility", scalarVisibility);

  if(scalarVisibility)
  {
    mitk::VtkScalarModeProperty* scalarMode;
    if(this->GetDataTreeNode()->GetProperty(scalarMode, "scalar mode", renderer))
    {
      if( (scalarMode->GetVtkScalarMode() == VTK_SCALAR_MODE_USE_POINT_DATA) ||
        (scalarMode->GetVtkScalarMode() == VTK_SCALAR_MODE_DEFAULT) )
      {
        usePointData = true;
      }
      if(scalarMode->GetVtkScalarMode() == VTK_SCALAR_MODE_USE_CELL_DATA)
      {
        useCellData = true;
      }
    }
    else
    {
      usePointData = true;
    }
  }

  vtkPoints    *vpoints = contour->GetPoints();
  vtkDataArray *vpointscalars = contour->GetPointData()->GetScalars();

  vtkCellArray *vlines  = contour->GetLines();
  vtkDataArray* vcellscalars = contour->GetCellData()->GetScalars();

  Point3D p; Point2D p2d, last;
  int i, j;
  int numberOfLines = vlines->GetNumberOfCells();

  glLineWidth( m_LineWidth );
  glBegin (GL_LINES);

  vlines->InitTraversal();
  for(i=0;i<numberOfLines;++i)
  {
    int *cell, cellSize;
#if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) ))
    double vp[3];
#else
    float vp[3];
#endif

    vlines->GetNextCell(cellSize, cell);

    vpoints->GetPoint(cell[0], vp);
    //take transformation via vtktransform into account
    vtktransform->TransformPoint(vp, vp);
    vtk2itk(vp, p);

    //convert 3D point (in mm) to 2D point on slice (also in mm)
    worldGeometry->Map(p, p2d);

    //convert point (until now mm and in worldcoordinates) to display coordinates (units )
    displayGeometry->WorldToDisplay(p2d, p2d);
    last=p2d;

    for(j=1; j<cellSize; ++j)
    {
      vpoints->GetPoint(cell[j], vp);
      //take transformation via vtktransform into account
      vtktransform->TransformPoint(vp, vp);
      vtk2itk(vp, p);

      //convert 3D point (in mm) to 2D point on slice (also in mm)
      worldGeometry->Map(p, p2d);

      //convert point (until now mm and in worldcoordinates) to display coordinates (units )
      displayGeometry->WorldToDisplay(p2d, p2d);

      vtkFloatingPointType color[3];
      if (useCellData && vcellscalars != NULL )
      {
        // color each cell according to cell data
        lut->GetColor( vcellscalars->GetComponent(i,0),color);
        glColor3f(color[0],color[1],color[2]);
        glVertex2f(last[0], last[1]);
        glVertex2f(p2d[0], p2d[1]);
      }
      else if (usePointData && vpointscalars != NULL )
      {
        lut->GetColor( vpointscalars->GetComponent(cell[j-1],0),color);
        glColor3f(color[0],color[1],color[2]);
        glVertex2f(last[0], last[1]);
        lut->GetColor( vpointscalars->GetComponent(cell[j],0),color);
        glColor3f(color[0],color[1],color[2]);
        glVertex2f(p2d[0], p2d[1]);
      }
      else {
        glVertex2f(last[0], last[1]);
        glVertex2f(p2d[0], p2d[1]);
      }
      last=p2d;
    }
  }

  glEnd ();
  glLineWidth(1.0);
}
<|endoftext|>