<commit_before>#ifndef VEXCL_TYPES_HPP
#define VEXCL_TYPES_HPP

/*
The MIT License

Copyright (c) 2012-2015 Denis Demidov <dennis.demidov@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
 * \file   vexcl/types.hpp
 * \author Pascal Germroth <pascal@ensieve.org>
 * \brief  Support for using native C++ and OpenCL types in expressions.
 */

#include <string>
#include <type_traits>
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <iomanip>

#include <boost/io/ios_state.hpp>

// This should be available for all backends
#include <CL/cl_platform.h>

/// \cond INTERNAL
typedef unsigned int  uint;
typedef unsigned char uchar;

namespace vex {

    /// Get the corresponding scalar type for a CL vector (or scalar) type.
    /** \code cl_scalar_of<cl_float4>::type == cl_float \endcode */
    template <class T>
    struct cl_scalar_of {};

    /// Get the corresponding vector type for a CL scalar type.
    /** \code cl_vector_of<cl_float, 4>::type == cl_float4 \endcode */
    template <class T, int dim>
    struct cl_vector_of {};

    /// Get the number of values in a CL vector (or scalar) type.
    /** \code cl_vector_length<cl_float4>::value == 4 \endcode */
    template <class T>
    struct cl_vector_length {};

} // namespace vex

#define VEXCL_BIN_OP(name, len, op)                                            \
  inline cl_##name##len &operator op## =(cl_##name##len & a,                   \
                                         const cl_##name##len & b) {           \
    for (size_t i = 0; i < len; i++)                                           \
      a.s[i] op## = b.s[i];                                                    \
    return a;                                                                  \
  }                                                                            \
  inline cl_##name##len operator op(const cl_##name##len & a,                  \
                                    const cl_##name##len & b) {                \
    cl_##name##len res = a;                                                    \
    return res op## = b;                                                       \
  }

// `scalar OP vector` acts like `(vector_t)(scalar) OP vector` in OpenCl:
// all components are set to the scalar value.
#define VEXCL_BIN_SCALAR_OP(name, len, op)                                     \
  inline cl_##name##len &operator op## =(cl_##name##len & a,                   \
                                         const cl_##name & b) {                \
    for (size_t i = 0; i < len; i++)                                           \
      a.s[i] op## = b;                                                         \
    return a;                                                                  \
  }                                                                            \
  inline cl_##name##len operator op(const cl_##name##len & a,                  \
                                    const cl_##name & b) {                     \
    cl_##name##len res = a;                                                    \
    return res op## = b;                                                       \
  }                                                                            \
  inline cl_##name##len operator op(const cl_##name & a,                       \
                                    const cl_##name##len & b) {                \
    cl_##name##len res = b;                                                    \
    return res op## = a;                                                       \
  }

#define VEXCL_VEC_TYPE(name, len)                                              \
  VEXCL_BIN_OP(name, len, +)                                                   \
  VEXCL_BIN_OP(name, len, -)                                                   \
  VEXCL_BIN_OP(name, len, *)                                                   \
  VEXCL_BIN_OP(name, len, /)                                                   \
  VEXCL_BIN_SCALAR_OP(name, len, +)                                            \
  VEXCL_BIN_SCALAR_OP(name, len, -)                                            \
  VEXCL_BIN_SCALAR_OP(name, len, *)                                            \
  VEXCL_BIN_SCALAR_OP(name, len, /)                                            \
  inline cl_##name##len operator-(const cl_##name##len & a) {                  \
    cl_##name##len res;                                                        \
    for (size_t i = 0; i < len; i++)                                           \
      res.s[i] = -a.s[i];                                                      \
    return res;                                                                \
  }                                                                            \
  inline std::ostream &operator<<(std::ostream & os,                           \
                                  const cl_##name##len & value) {              \
    boost::io::ios_all_saver stream_state(os);                                 \
    os << "(";                                                                 \
    for (std::size_t i = 0; i < len; i++) {                                    \
      if (i != 0) os << ',';                                                   \
      os << std::setw(13) << std::scientific << value.s[i];                    \
    }                                                                          \
    return os << ')';                                                          \
  }                                                                            \
  namespace vex {                                                              \
  template <> struct cl_scalar_of<cl_##name##len> {                            \
    typedef cl_##name type;                                                    \
  };                                                                           \
  template <> struct cl_vector_of<cl_##name, len> {                            \
    typedef cl_##name##len type;                                               \
  };                                                                           \
  template <>                                                                  \
  struct cl_vector_length<cl_##name##len>                                      \
      : std::integral_constant<unsigned, len> { };                             \
  }

#define VEXCL_TYPES(name)                                                      \
  VEXCL_VEC_TYPE(name, 2)                                                      \
  VEXCL_VEC_TYPE(name, 4)                                                      \
  VEXCL_VEC_TYPE(name, 8)                                                      \
  VEXCL_VEC_TYPE(name, 16)                                                     \
  namespace vex {                                                              \
  template <> struct cl_scalar_of<cl_##name> {                                 \
    typedef cl_##name type;                                                    \
  };                                                                           \
  template <> struct cl_vector_of<cl_##name, 1> {                              \
    typedef cl_##name type;                                                    \
  };                                                                           \
  template <>                                                                  \
  struct cl_vector_length<cl_##name> : std::integral_constant<unsigned, 1> {}; \
  }

#ifdef _MSC_VER
#  pragma warning(push)
#  pragma warning(disable : 4146)
#endif
VEXCL_TYPES(float)
VEXCL_TYPES(double)
VEXCL_TYPES(char)
VEXCL_TYPES(uchar)
VEXCL_TYPES(short)
VEXCL_TYPES(ushort)
VEXCL_TYPES(int)
VEXCL_TYPES(uint)
VEXCL_TYPES(long)
VEXCL_TYPES(ulong)
#ifdef _MSC_VER
#  pragma warning(pop)
#endif

#undef VEXCL_BIN_OP
#undef VEXCL_BIN_SCALAR_OP
#undef VEXCL_VEC_TYPE
#undef VEXCL_TYPES

namespace vex {

/// Convert each element of the vector to another type.
template<class To, class From>
inline To cl_convert(const From &val) {
    const size_t n = cl_vector_length<To>::value;
    static_assert(n == cl_vector_length<From>::value, "Vectors must be same length.");
    To out;
    for(size_t i = 0 ; i != n ; i++)
        out.s[i] = val.s[i];
    return out;
}

/// Declares a type as CL native, allows using it as a literal.
template <class T> struct is_cl_native : std::false_type {};

/// Convert typename to string.
template <class T, class Enable = void>
struct type_name_impl;

template <class T>
inline std::string type_name() {
    return type_name_impl<T>::get();
}

template<typename T>
struct type_name_impl<T&>
{
    static std::string get() {
        return type_name_impl<T>::get() + " &";
    }
};

#define VEXCL_STRINGIFY(name)                                                  \
  template<> struct type_name_impl<cl_##name> {                                \
    static std::string get() { return #name; }                                 \
  };

#define VEXCL_NATIVE(name)                                                     \
  template<> struct is_cl_native<cl_##name> : std::true_type { };

// enable use of OpenCL vector types as literals
#define VEXCL_VEC_TYPE(name, len)                                              \
  template <> struct type_name_impl<cl_##name##len> {                          \
    static std::string get() { return #name #len; }                            \
  };                                                                           \
  template <> struct is_cl_native<cl_##name##len> : std::true_type { };

#define VEXCL_TYPES(name)                                                      \
  VEXCL_STRINGIFY(name)                                                        \
  VEXCL_NATIVE(name)                                                           \
  VEXCL_VEC_TYPE(name, 2)                                                      \
  VEXCL_VEC_TYPE(name, 4)                                                      \
  VEXCL_VEC_TYPE(name, 8)                                                      \
  VEXCL_VEC_TYPE(name, 16)

VEXCL_TYPES(float)
VEXCL_TYPES(double)
VEXCL_TYPES(char)
VEXCL_TYPES(uchar)
VEXCL_TYPES(short)
VEXCL_TYPES(ushort)
VEXCL_TYPES(int)
VEXCL_TYPES(uint)
VEXCL_TYPES(long)
VEXCL_TYPES(ulong)

#undef VEXCL_TYPES
#undef VEXCL_VEC_TYPE
#undef VEXCL_STRINGIFY

// One can not pass these to the kernel, but the overloads are useful
template <> struct type_name_impl<bool> {
    static std::string get() { return "bool"; }
};
template <> struct type_name_impl<void> {
    static std::string get() { return "void"; }
};

// char and cl_char are different types. Hence, special handling is required:
template <> struct type_name_impl<char> {
    static std::string get() { return "char"; }
};
template <> struct is_cl_native<char> : std::true_type {};
template <> struct cl_vector_length<char> : std::integral_constant<unsigned, 1> {};
template <> struct cl_scalar_of<char> { typedef char type; };

#if defined(__APPLE__)
template <> struct type_name_impl<size_t>
    : public type_name_impl<
        boost::mpl::if_c<
            sizeof(std::size_t) == sizeof(uint),
            cl_uint, cl_ulong
        >::type
    >
{};

template <> struct type_name_impl<ptrdiff_t>
    : public type_name_impl<
        boost::mpl::if_c<
            sizeof(std::size_t) == sizeof(uint),
            cl_int, cl_long
        >::type
    >
{};

template <> struct is_cl_native<size_t>    : std::true_type {};
template <> struct is_cl_native<ptrdiff_t> : std::true_type {};

template <> struct cl_vector_length<size_t>    : std::integral_constant<unsigned, 1> {};
template <> struct cl_vector_length<ptrdiff_t> : std::integral_constant<unsigned, 1> {};

template <> struct cl_scalar_of<size_t>       { typedef size_t    type; };
template <> struct cl_vector_of<size_t, 1>    { typedef size_t    type; };
template <> struct cl_scalar_of<ptrdiff_t>    { typedef ptrdiff_t type; };
template <> struct cl_vector_of<ptrdiff_t, 1> { typedef ptrdiff_t type; };
#endif

template <class T, class Enable = void>
struct is_cl_scalar : std::false_type {};

template <class T>
struct is_cl_scalar<T,
    typename std::enable_if<is_cl_native<T>::value && (cl_vector_length<T>::value == 1)>::type
    > : std::true_type
{};

template <class T, class Enable = void>
struct is_cl_vector : std::false_type {};

template <class T>
struct is_cl_vector<T,
    typename std::enable_if<is_cl_native<T>::value && (cl_vector_length<T>::value > 1)>::type
    > : std::true_type
{};

}

/// \endcond

#endif
<commit_msg>directive when including cl_platform<commit_after>#ifndef VEXCL_TYPES_HPP
#define VEXCL_TYPES_HPP

/*
The MIT License

Copyright (c) 2012-2015 Denis Demidov <dennis.demidov@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
 * \file   vexcl/types.hpp
 * \author Pascal Germroth <pascal@ensieve.org>
 * \brief  Support for using native C++ and OpenCL types in expressions.
 */

#include <string>
#include <type_traits>
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <iomanip>

#include <boost/io/ios_state.hpp>

// This should be available for all backends
#if defined(__APPLE__) || defined(__MACOSX)
#include <OpenCL/cl_platform.h>
#else
#include <CL/cl_platform.h>
#endif

/// \cond INTERNAL
typedef unsigned int  uint;
typedef unsigned char uchar;

namespace vex {

    /// Get the corresponding scalar type for a CL vector (or scalar) type.
    /** \code cl_scalar_of<cl_float4>::type == cl_float \endcode */
    template <class T>
    struct cl_scalar_of {};

    /// Get the corresponding vector type for a CL scalar type.
    /** \code cl_vector_of<cl_float, 4>::type == cl_float4 \endcode */
    template <class T, int dim>
    struct cl_vector_of {};

    /// Get the number of values in a CL vector (or scalar) type.
    /** \code cl_vector_length<cl_float4>::value == 4 \endcode */
    template <class T>
    struct cl_vector_length {};

} // namespace vex

#define VEXCL_BIN_OP(name, len, op)                                            \
  inline cl_##name##len &operator op## =(cl_##name##len & a,                   \
                                         const cl_##name##len & b) {           \
    for (size_t i = 0; i < len; i++)                                           \
      a.s[i] op## = b.s[i];                                                    \
    return a;                                                                  \
  }                                                                            \
  inline cl_##name##len operator op(const cl_##name##len & a,                  \
                                    const cl_##name##len & b) {                \
    cl_##name##len res = a;                                                    \
    return res op## = b;                                                       \
  }

// `scalar OP vector` acts like `(vector_t)(scalar) OP vector` in OpenCl:
// all components are set to the scalar value.
#define VEXCL_BIN_SCALAR_OP(name, len, op)                                     \
  inline cl_##name##len &operator op## =(cl_##name##len & a,                   \
                                         const cl_##name & b) {                \
    for (size_t i = 0; i < len; i++)                                           \
      a.s[i] op## = b;                                                         \
    return a;                                                                  \
  }                                                                            \
  inline cl_##name##len operator op(const cl_##name##len & a,                  \
                                    const cl_##name & b) {                     \
    cl_##name##len res = a;                                                    \
    return res op## = b;                                                       \
  }                                                                            \
  inline cl_##name##len operator op(const cl_##name & a,                       \
                                    const cl_##name##len & b) {                \
    cl_##name##len res = b;                                                    \
    return res op## = a;                                                       \
  }

#define VEXCL_VEC_TYPE(name, len)                                              \
  VEXCL_BIN_OP(name, len, +)                                                   \
  VEXCL_BIN_OP(name, len, -)                                                   \
  VEXCL_BIN_OP(name, len, *)                                                   \
  VEXCL_BIN_OP(name, len, /)                                                   \
  VEXCL_BIN_SCALAR_OP(name, len, +)                                            \
  VEXCL_BIN_SCALAR_OP(name, len, -)                                            \
  VEXCL_BIN_SCALAR_OP(name, len, *)                                            \
  VEXCL_BIN_SCALAR_OP(name, len, /)                                            \
  inline cl_##name##len operator-(const cl_##name##len & a) {                  \
    cl_##name##len res;                                                        \
    for (size_t i = 0; i < len; i++)                                           \
      res.s[i] = -a.s[i];                                                      \
    return res;                                                                \
  }                                                                            \
  inline std::ostream &operator<<(std::ostream & os,                           \
                                  const cl_##name##len & value) {              \
    boost::io::ios_all_saver stream_state(os);                                 \
    os << "(";                                                                 \
    for (std::size_t i = 0; i < len; i++) {                                    \
      if (i != 0) os << ',';                                                   \
      os << std::setw(13) << std::scientific << value.s[i];                    \
    }                                                                          \
    return os << ')';                                                          \
  }                                                                            \
  namespace vex {                                                              \
  template <> struct cl_scalar_of<cl_##name##len> {                            \
    typedef cl_##name type;                                                    \
  };                                                                           \
  template <> struct cl_vector_of<cl_##name, len> {                            \
    typedef cl_##name##len type;                                               \
  };                                                                           \
  template <>                                                                  \
  struct cl_vector_length<cl_##name##len>                                      \
      : std::integral_constant<unsigned, len> { };                             \
  }

#define VEXCL_TYPES(name)                                                      \
  VEXCL_VEC_TYPE(name, 2)                                                      \
  VEXCL_VEC_TYPE(name, 4)                                                      \
  VEXCL_VEC_TYPE(name, 8)                                                      \
  VEXCL_VEC_TYPE(name, 16)                                                     \
  namespace vex {                                                              \
  template <> struct cl_scalar_of<cl_##name> {                                 \
    typedef cl_##name type;                                                    \
  };                                                                           \
  template <> struct cl_vector_of<cl_##name, 1> {                              \
    typedef cl_##name type;                                                    \
  };                                                                           \
  template <>                                                                  \
  struct cl_vector_length<cl_##name> : std::integral_constant<unsigned, 1> {}; \
  }

#ifdef _MSC_VER
#  pragma warning(push)
#  pragma warning(disable : 4146)
#endif
VEXCL_TYPES(float)
VEXCL_TYPES(double)
VEXCL_TYPES(char)
VEXCL_TYPES(uchar)
VEXCL_TYPES(short)
VEXCL_TYPES(ushort)
VEXCL_TYPES(int)
VEXCL_TYPES(uint)
VEXCL_TYPES(long)
VEXCL_TYPES(ulong)
#ifdef _MSC_VER
#  pragma warning(pop)
#endif

#undef VEXCL_BIN_OP
#undef VEXCL_BIN_SCALAR_OP
#undef VEXCL_VEC_TYPE
#undef VEXCL_TYPES

namespace vex {

/// Convert each element of the vector to another type.
template<class To, class From>
inline To cl_convert(const From &val) {
    const size_t n = cl_vector_length<To>::value;
    static_assert(n == cl_vector_length<From>::value, "Vectors must be same length.");
    To out;
    for(size_t i = 0 ; i != n ; i++)
        out.s[i] = val.s[i];
    return out;
}

/// Declares a type as CL native, allows using it as a literal.
template <class T> struct is_cl_native : std::false_type {};

/// Convert typename to string.
template <class T, class Enable = void>
struct type_name_impl;

template <class T>
inline std::string type_name() {
    return type_name_impl<T>::get();
}

template<typename T>
struct type_name_impl<T&>
{
    static std::string get() {
        return type_name_impl<T>::get() + " &";
    }
};

#define VEXCL_STRINGIFY(name)                                                  \
  template<> struct type_name_impl<cl_##name> {                                \
    static std::string get() { return #name; }                                 \
  };

#define VEXCL_NATIVE(name)                                                     \
  template<> struct is_cl_native<cl_##name> : std::true_type { };

// enable use of OpenCL vector types as literals
#define VEXCL_VEC_TYPE(name, len)                                              \
  template <> struct type_name_impl<cl_##name##len> {                          \
    static std::string get() { return #name #len; }                            \
  };                                                                           \
  template <> struct is_cl_native<cl_##name##len> : std::true_type { };

#define VEXCL_TYPES(name)                                                      \
  VEXCL_STRINGIFY(name)                                                        \
  VEXCL_NATIVE(name)                                                           \
  VEXCL_VEC_TYPE(name, 2)                                                      \
  VEXCL_VEC_TYPE(name, 4)                                                      \
  VEXCL_VEC_TYPE(name, 8)                                                      \
  VEXCL_VEC_TYPE(name, 16)

VEXCL_TYPES(float)
VEXCL_TYPES(double)
VEXCL_TYPES(char)
VEXCL_TYPES(uchar)
VEXCL_TYPES(short)
VEXCL_TYPES(ushort)
VEXCL_TYPES(int)
VEXCL_TYPES(uint)
VEXCL_TYPES(long)
VEXCL_TYPES(ulong)

#undef VEXCL_TYPES
#undef VEXCL_VEC_TYPE
#undef VEXCL_STRINGIFY

// One can not pass these to the kernel, but the overloads are useful
template <> struct type_name_impl<bool> {
    static std::string get() { return "bool"; }
};
template <> struct type_name_impl<void> {
    static std::string get() { return "void"; }
};

// char and cl_char are different types. Hence, special handling is required:
template <> struct type_name_impl<char> {
    static std::string get() { return "char"; }
};
template <> struct is_cl_native<char> : std::true_type {};
template <> struct cl_vector_length<char> : std::integral_constant<unsigned, 1> {};
template <> struct cl_scalar_of<char> { typedef char type; };

#if defined(__APPLE__)
template <> struct type_name_impl<size_t>
    : public type_name_impl<
        boost::mpl::if_c<
            sizeof(std::size_t) == sizeof(uint),
            cl_uint, cl_ulong
        >::type
    >
{};

template <> struct type_name_impl<ptrdiff_t>
    : public type_name_impl<
        boost::mpl::if_c<
            sizeof(std::size_t) == sizeof(uint),
            cl_int, cl_long
        >::type
    >
{};

template <> struct is_cl_native<size_t>    : std::true_type {};
template <> struct is_cl_native<ptrdiff_t> : std::true_type {};

template <> struct cl_vector_length<size_t>    : std::integral_constant<unsigned, 1> {};
template <> struct cl_vector_length<ptrdiff_t> : std::integral_constant<unsigned, 1> {};

template <> struct cl_scalar_of<size_t>       { typedef size_t    type; };
template <> struct cl_vector_of<size_t, 1>    { typedef size_t    type; };
template <> struct cl_scalar_of<ptrdiff_t>    { typedef ptrdiff_t type; };
template <> struct cl_vector_of<ptrdiff_t, 1> { typedef ptrdiff_t type; };
#endif

template <class T, class Enable = void>
struct is_cl_scalar : std::false_type {};

template <class T>
struct is_cl_scalar<T,
    typename std::enable_if<is_cl_native<T>::value && (cl_vector_length<T>::value == 1)>::type
    > : std::true_type
{};

template <class T, class Enable = void>
struct is_cl_vector : std::false_type {};

template <class T>
struct is_cl_vector<T,
    typename std::enable_if<is_cl_native<T>::value && (cl_vector_length<T>::value > 1)>::type
    > : std::true_type
{};

}

/// \endcond

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: layerupdate.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 03:31:06 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef CONFIGMGR_BACKEND_LAYERUPDATE_HXX
#define CONFIGMGR_BACKEND_LAYERUPDATE_HXX

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif

#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef INCLUDED_VECTOR
#include <vector>
#define INCLUDED_VECTOR
#endif

namespace com { namespace sun { namespace star { namespace configuration { namespace backend {
    class XLayerHandler;
} } } } }

namespace configmgr
{
// -----------------------------------------------------------------------------
    namespace backend
    {
// -----------------------------------------------------------------------------
        namespace uno        = ::com::sun::star::uno;
        namespace backenduno = ::com::sun::star::configuration::backend;

        using rtl::OUString;
// -----------------------------------------------------------------------------
        class NodeUpdate;
        typedef rtl::Reference<NodeUpdate> NodeUpdateRef;

        class LayerUpdate
        {
        public:
            typedef uno::Reference< backenduno::XLayerHandler > LayerWriter;

            LayerUpdate();
            LayerUpdate(LayerUpdate const & _aOther);
            ~LayerUpdate();
            LayerUpdate & operator =(LayerUpdate const & _aOther);
        public:
            typedef std::vector<OUString> ContextPath;

            bool isEmpty() const { return ! m_xContextNode.is(); }

            NodeUpdateRef       getContextNode() const;
            ContextPath const & getContextPath() const;

            void setContextNode(NodeUpdateRef const & _xContextNode);

        private:
            void makeContextPath(OUString const & _aContextPath);

        private:
            NodeUpdateRef   m_xContextNode;
            ContextPath     m_aContextPath;
        };
// -----------------------------------------------------------------------------

    } // namespace backend
// -----------------------------------------------------------------------------

} // namespace configmgr
#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.6.130); FILE MERGED 2008/04/01 15:06:37 thb 1.6.130.2: #i85898# Stripping all external header guards 2008/03/31 12:22:40 rt 1.6.130.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: layerupdate.hxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef CONFIGMGR_BACKEND_LAYERUPDATE_HXX
#define CONFIGMGR_BACKEND_LAYERUPDATE_HXX

#include <com/sun/star/uno/Reference.hxx>
#include <rtl/ref.hxx>
#include <rtl/ustring.hxx>

#ifndef INCLUDED_VECTOR
#include <vector>
#define INCLUDED_VECTOR
#endif

namespace com { namespace sun { namespace star { namespace configuration { namespace backend {
    class XLayerHandler;
} } } } }

namespace configmgr
{
// -----------------------------------------------------------------------------
    namespace backend
    {
// -----------------------------------------------------------------------------
        namespace uno        = ::com::sun::star::uno;
        namespace backenduno = ::com::sun::star::configuration::backend;

        using rtl::OUString;
// -----------------------------------------------------------------------------
        class NodeUpdate;
        typedef rtl::Reference<NodeUpdate> NodeUpdateRef;

        class LayerUpdate
        {
        public:
            typedef uno::Reference< backenduno::XLayerHandler > LayerWriter;

            LayerUpdate();
            LayerUpdate(LayerUpdate const & _aOther);
            ~LayerUpdate();
            LayerUpdate & operator =(LayerUpdate const & _aOther);
        public:
            typedef std::vector<OUString> ContextPath;

            bool isEmpty() const { return ! m_xContextNode.is(); }

            NodeUpdateRef       getContextNode() const;
            ContextPath const & getContextPath() const;

            void setContextNode(NodeUpdateRef const & _xContextNode);

        private:
            void makeContextPath(OUString const & _aContextPath);

        private:
            NodeUpdateRef   m_xContextNode;
            ContextPath     m_aContextPath;
        };
// -----------------------------------------------------------------------------

    } // namespace backend
// -----------------------------------------------------------------------------

} // namespace configmgr
#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: setnodeimpl.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: jb $ $Date: 2002-02-11 13:47:56 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef CONFIGMGR_SETNODEBEHAVIOR_HXX_
#define CONFIGMGR_SETNODEBEHAVIOR_HXX_

#ifndef CONFIGMGR_CONFIGNODEBEHAVIOR_HXX_
#include "nodeimpl.hxx"
#endif

#ifndef CONFIGMGR_CONFIGNODEIMPL_HXX_
#include "treeimpl.hxx"
#endif
#ifndef CONFIGMGR_CONFIGTEMPLATE_HXX_
#include "template.hxx"
#endif

#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif

#ifndef INCUDED_MAP
#include <map>
#define INCUDED_MAP
#endif
#ifndef INCLUDED_MEMORY
#include <memory>
#define INCLUDED_MEMORY
#endif

namespace configmgr
{
//-----------------------------------------------------------------------------
    class SubtreeChange;
    class AddNode;
    class RemoveNode;
//-----------------------------------------------------------------------------

    namespace configuration
    {
//-----------------------------------------------------------------------------
        class SetElementChangeImpl;

//-----------------------------------------------------------------------------
        typedef rtl::Reference<ElementTreeImpl>     ElementTreeHolder; // also in configset.hxx
        typedef std::vector< ElementTreeHolder >    ElementList; // also in treeimpl.hxx
//-----------------------------------------------------------------------------

        struct SetEntry
        {
            SetEntry(data::Accessor const& _aAccessor,ElementTreeImpl* _pTree);

            bool isValid()  const { return m_pTree != 0; }

            data::Accessor      accessor() const { return m_aAccessor; }
            ElementTreeImpl* tree() const { return m_pTree; };

            view::ViewTreeAccess    getTreeView() const;
        private:
            data::Accessor   m_aAccessor;
            ElementTreeImpl* m_pTree;
        };
    //-------------------------------------------------------------------------

        struct SetNodeVisitor
        {
            enum Result { DONE, CONTINUE };
            virtual Result visit(SetEntry const& anEntry) = 0;
        };

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

    // basic implementations of set node contents
    //-----------------------------------------------------------------------------

        struct ElementTreeData
        {
            typedef rtl::Reference<ElementTreeImpl> ElementTreeHolder;

            // construction
            ElementTreeData() : tree(), inDefault(false) {}

            ElementTreeData(ElementTreeHolder const& _tree, bool _bDefault)
             : tree(_tree), inDefault(_bDefault) {}

            // ORef compatibility
            sal_Bool isValid() const { return this->tree.is(); }
            ElementTreeImpl* get() const { return this->tree.get(); }
            ElementTreeHolder const& operator->() const { return this->tree; }
            ElementTreeImpl& operator*() const { return *get(); }

            // data
            ElementTreeHolder   tree;
            bool                inDefault;
        };
    //-----------------------------------------------------------------------------

        class ElementSet
        {
        public:
            typedef ElementTreeData Element;
            typedef std::map<Name, Element> Data;

        // the following must be implemented by derived classes
            bool isEmpty() const { return m_aData.empty(); }

            bool hasElement(Name const& aName) const;
            Element* getElement(Name const& aName);
            Element const* getElement(Name const& aName) const;
            Element findElement(Name const& aName);

            void insertElement(Name const& aName, Element const& aNewEntry);
            Element replaceElement(Name const& aName, Element const& aNewEntry);
            Element removeElement(Name const& aName);

            void clearElements() {  m_aData.clear(); }

            void swap(ElementSet& aOther) { m_aData.swap(aOther.m_aData); }

        // STL style iteration
            class ConstIterator
            {
                typedef Data::const_iterator It;
            public:
                ConstIterator(It const& it) : m_base(it) {}

                Element const& operator* () const { return  m_base->second; }
                Element const* operator->() const { return &m_base->second; }

                ConstIterator& operator++()     { ++m_base; return *this; }
                ConstIterator  operator++(int)  { return ConstIterator(m_base++); }

                ConstIterator& operator--()     { --m_base; return *this; }
                ConstIterator  operator--(int)  { return ConstIterator(m_base--); }

                friend bool operator ==(ConstIterator const& lhs, ConstIterator const& rhs)
                { return lhs.m_base == rhs.m_base; }
                friend bool operator !=(ConstIterator const& lhs, ConstIterator const& rhs)
                { return lhs.m_base != rhs.m_base; }
            private:
                It m_base;
            };
            ConstIterator begin() const { return ConstIterator(m_aData.begin()); }
            ConstIterator end()   const { return ConstIterator(m_aData.end()); }

            class Iterator
            {
                typedef Data::iterator It;
            public:
                Iterator(It const& it) : m_base(it) {}

                Element& operator* () const { return  m_base->second; }
                Element* operator->() const { return &m_base->second; }

                Iterator& operator++()      { ++m_base; return *this; }
                Iterator  operator++(int)   { return Iterator(m_base++); }

                Iterator& operator--()      { --m_base; return *this; }
                Iterator  operator--(int)   { return Iterator(m_base--); }

                friend bool operator ==(Iterator const& lhs, Iterator const& rhs)
                { return lhs.m_base == rhs.m_base; }
                friend bool operator !=(Iterator const& lhs, Iterator const& rhs)
                { return lhs.m_base != rhs.m_base; }

                operator ConstIterator() const { return ConstIterator(m_base); }
            private:
                It m_base;
            };
            Iterator begin()    { return Iterator(m_aData.begin()); }
            Iterator end()      { return Iterator(m_aData.end()); }

            typedef Data::const_iterator PairIterator;
            PairIterator beginNative()  const { return m_aData.begin(); }
            PairIterator endNative()    const { return m_aData.end(); }
        private:
            Data m_aData;
        };
    //-------------------------------------------------------------------------

    // Basic implementation of a set node
    //-------------------------------------------------------------------------

        class SetNodeImpl : public NodeImpl
        {
            friend class view::ViewStrategy;
            ElementSet          m_aDataSet;
            TemplateHolder      m_aTemplate;
            TemplateProvider    m_aTemplateProvider;
            TreeImpl*           m_pParentTree;
            NodeOffset          m_nContextPos;

            typedef NodeOffset InitHelper;
            InitHelper      m_aInit;

        public:
            typedef ElementSet::Element Element;

            SetNodeImpl(data::SetNodeAddress const& _aNodeRef, Template* pTemplate);

            typedef data::SetNodeAccess DataAccess;
            DataAccess getDataAccess(data::Accessor const& _aAccessor) const;

            /// Get the template that describes elements of this set
            TemplateHolder getElementTemplate() const { return m_aTemplate; }

            /// Get a template provider that can create new elements for this set
            TemplateProvider getTemplateProvider() const { return m_aTemplateProvider; }

            void convertChanges(NodeChangesInformation& rLocalChanges, data::Accessor const& _accessor, SubtreeChange const& rExternalChange, TreeDepth nDepth);

            void    insertElement(Name const& aName, Element const& aNewElement);
            Element replaceElement(Name const& aName, Element const& aNewElement);
            Element removeElement(Name const& aName);

            void rebuildFrom(SetNodeImpl& rOldData,data::SetNodeAccess const& _aNewNode,data::SetNodeAccess const& _aOldNode);

        protected:
            ~SetNodeImpl();

        protected:
        // new overrideables
            virtual bool                    doIsEmpty() const;
            virtual ElementTreeImpl*        doFindElement(Name const& aName) ;
            virtual SetNodeVisitor::Result  doDispatchToElements(data::Accessor const& _aAccessor, SetNodeVisitor& aVisitor);
            virtual void doDifferenceToDefaultState(data::Accessor const& _aAccessor, SubtreeChange& _rChangeToDefault, ISubtree& _rDefaultTree);

            virtual SetElementChangeImpl* doAdjustToAddedElement(data::Accessor const& _aAccessor, Name const& aName, AddNode const& aAddNodeChange, Element const & aNewElement);
            virtual SetElementChangeImpl* doAdjustToRemovedElement(data::Accessor const& _aAccessor, Name const& aName, RemoveNode const& aRemoveNodeChange);
            virtual SetElementChangeImpl* doAdjustChangedElement(data::Accessor const& _aAccessor, NodeChangesInformation& rLocalChanges, Name const& aName, Change const& aChange);

            virtual void doTransferElements(ElementSet& rReplacement);

        protected:
        // helpers
            TreeImpl*   getParentTree() const;
            NodeOffset  getContextOffset() const;

            Element makeElement(data::Accessor const& _aAccessor, SetEntry const & _anEntry);
            static Element entryToElement(SetEntry const& _anEntry);
            view::ViewTreeAccess getElementView();

            /// Initialize the set data: Set context information, and build the view (actually loading the elements may be deferred)
            friend class TreeImplBuilder;
            void initElements(TemplateProvider const& aTemplateProvider, TreeImpl& rParentTree, NodeOffset nPos, TreeDepth nDepth);

        protected:
            /// does this set contain any elements (loads elements if needed)
            bool implHasLoadedElements() const;
            bool implLoadElements(data::Accessor const& _aAccessor);
            void implEnsureElementsLoaded(data::Accessor const& _aAccessor);
            void implInitElements(data::SetNodeAccess const& _aNode, TreeDepth nDepth);
            void implInitElement(Element const& aNewElement);

            void implRebuildElements(data::SetNodeAccess const& _aNewNode,data::SetNodeAccess const& _aOldNode);
        protected:
            SetElementChangeImpl* implCreateInsert    (data::Accessor const& _aAccessor, Name const& aName, Element const& aNewElement) const;
            SetElementChangeImpl* implCreateReplace   (data::Accessor const& _aAccessor, Name const& aName, Element const& aNewElement, Element const& aOldElement) const;
            SetElementChangeImpl* implCreateRemove    (data::Accessor const& _aAccessor, Name const& aName, Element const& aOldElement) const;

            SetElementChangeImpl* implAdjustToAddedElement(data::Accessor const& _aAccessor, Name const& aName, Element const& aNewElement, bool _bReplacing);
            SetElementChangeImpl* implAdjustToRemovedElement(data::Accessor const& _aAccessor, Name const& aName);

            Element makeAdditionalElement(data::Accessor const& _aAccessor, rtl::Reference<view::ViewStrategy> const& _xStrategy, AddNode const& aAddNodeChange, TreeDepth nDepth);

            Element implValidateElement(data::Accessor const& _aAccessor, Element const& aNewElement);

            void implDifferenceToDefaultState(data::Accessor const& _aAccessor, SubtreeChange& _rChangeToDefault, ISubtree& _rDefaultTree) const;
        protected:
            Element* getStoredElement(Name const& aName)
            { return m_aDataSet.getElement(aName); }
            Element const* getStoredElement(Name const& aName) const
            { return m_aDataSet.getElement(aName); }

            typedef ElementSet::PairIterator NativeIterator;
            NativeIterator beginElementSet() const
            { return m_aDataSet.beginNative(); }
            NativeIterator endElementSet() const
            { return m_aDataSet.endNative(); }

            void attach(Element const& aNewElement, Name const& aName);
            void detach(Element const& aNewElement);
        };

//-----------------------------------------------------------------------------
        // domain-specific 'dynamic_cast' replacement
        SetNodeImpl&    AsSetNode  (NodeImpl& rNode);

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

#endif // CONFIGMGR_SETNODEBEHAVIOR_HXX_
<commit_msg>INTEGRATION: CWS cfg01 (1.8.22); FILE MERGED 2003/03/13 15:22:09 jb 1.8.22.1: #108154# Use NodeAccessRef to avoid copying Accessor objects<commit_after>/*************************************************************************
 *
 *  $RCSfile: setnodeimpl.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-01 13:41:52 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef CONFIGMGR_SETNODEBEHAVIOR_HXX_
#define CONFIGMGR_SETNODEBEHAVIOR_HXX_

#ifndef CONFIGMGR_CONFIGNODEBEHAVIOR_HXX_
#include "nodeimpl.hxx"
#endif

#ifndef CONFIGMGR_CONFIGNODEIMPL_HXX_
#include "treeimpl.hxx"
#endif
#ifndef CONFIGMGR_CONFIGTEMPLATE_HXX_
#include "template.hxx"
#endif

#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif

#ifndef INCUDED_MAP
#include <map>
#define INCUDED_MAP
#endif
#ifndef INCLUDED_MEMORY
#include <memory>
#define INCLUDED_MEMORY
#endif

namespace configmgr
{
//-----------------------------------------------------------------------------
    class SubtreeChange;
    class AddNode;
    class RemoveNode;
//-----------------------------------------------------------------------------

    namespace configuration
    {
//-----------------------------------------------------------------------------
        class SetElementChangeImpl;

//-----------------------------------------------------------------------------
        typedef rtl::Reference<ElementTreeImpl>     ElementTreeHolder; // also in configset.hxx
        typedef std::vector< ElementTreeHolder >    ElementList; // also in treeimpl.hxx
//-----------------------------------------------------------------------------

        struct SetEntry
        {
            SetEntry(data::Accessor const& _aAccessor,ElementTreeImpl* _pTree);

            bool isValid()  const { return m_pTree != 0; }

            data::Accessor const& accessor() const { return m_aAccessor; }
            ElementTreeImpl* tree() const { return m_pTree; };

            view::ViewTreeAccess    getTreeView() const;
        private:
            data::Accessor   m_aAccessor;
            ElementTreeImpl* m_pTree;
        };
    //-------------------------------------------------------------------------

        struct SetNodeVisitor
        {
            enum Result { DONE, CONTINUE };
            virtual Result visit(SetEntry const& anEntry) = 0;
        };

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

    // basic implementations of set node contents
    //-----------------------------------------------------------------------------

        struct ElementTreeData
        {
            typedef rtl::Reference<ElementTreeImpl> ElementTreeHolder;

            // construction
            ElementTreeData() : tree(), inDefault(false) {}

            ElementTreeData(ElementTreeHolder const& _tree, bool _bDefault)
             : tree(_tree), inDefault(_bDefault) {}

            // ORef compatibility
            sal_Bool isValid() const { return this->tree.is(); }
            ElementTreeImpl* get() const { return this->tree.get(); }
            ElementTreeHolder const& operator->() const { return this->tree; }
            ElementTreeImpl& operator*() const { return *get(); }

            // data
            ElementTreeHolder   tree;
            bool                inDefault;
        };
    //-----------------------------------------------------------------------------

        class ElementSet
        {
        public:
            typedef ElementTreeData Element;
            typedef std::map<Name, Element> Data;

        // the following must be implemented by derived classes
            bool isEmpty() const { return m_aData.empty(); }

            bool hasElement(Name const& aName) const;
            Element* getElement(Name const& aName);
            Element const* getElement(Name const& aName) const;
            Element findElement(Name const& aName);

            void insertElement(Name const& aName, Element const& aNewEntry);
            Element replaceElement(Name const& aName, Element const& aNewEntry);
            Element removeElement(Name const& aName);

            void clearElements() {  m_aData.clear(); }

            void swap(ElementSet& aOther) { m_aData.swap(aOther.m_aData); }

        // STL style iteration
            class ConstIterator
            {
                typedef Data::const_iterator It;
            public:
                ConstIterator(It const& it) : m_base(it) {}

                Element const& operator* () const { return  m_base->second; }
                Element const* operator->() const { return &m_base->second; }

                ConstIterator& operator++()     { ++m_base; return *this; }
                ConstIterator  operator++(int)  { return ConstIterator(m_base++); }

                ConstIterator& operator--()     { --m_base; return *this; }
                ConstIterator  operator--(int)  { return ConstIterator(m_base--); }

                friend bool operator ==(ConstIterator const& lhs, ConstIterator const& rhs)
                { return lhs.m_base == rhs.m_base; }
                friend bool operator !=(ConstIterator const& lhs, ConstIterator const& rhs)
                { return lhs.m_base != rhs.m_base; }
            private:
                It m_base;
            };
            ConstIterator begin() const { return ConstIterator(m_aData.begin()); }
            ConstIterator end()   const { return ConstIterator(m_aData.end()); }

            class Iterator
            {
                typedef Data::iterator It;
            public:
                Iterator(It const& it) : m_base(it) {}

                Element& operator* () const { return  m_base->second; }
                Element* operator->() const { return &m_base->second; }

                Iterator& operator++()      { ++m_base; return *this; }
                Iterator  operator++(int)   { return Iterator(m_base++); }

                Iterator& operator--()      { --m_base; return *this; }
                Iterator  operator--(int)   { return Iterator(m_base--); }

                friend bool operator ==(Iterator const& lhs, Iterator const& rhs)
                { return lhs.m_base == rhs.m_base; }
                friend bool operator !=(Iterator const& lhs, Iterator const& rhs)
                { return lhs.m_base != rhs.m_base; }

                operator ConstIterator() const { return ConstIterator(m_base); }
            private:
                It m_base;
            };
            Iterator begin()    { return Iterator(m_aData.begin()); }
            Iterator end()      { return Iterator(m_aData.end()); }

            typedef Data::const_iterator PairIterator;
            PairIterator beginNative()  const { return m_aData.begin(); }
            PairIterator endNative()    const { return m_aData.end(); }
        private:
            Data m_aData;
        };
    //-------------------------------------------------------------------------

    // Basic implementation of a set node
    //-------------------------------------------------------------------------

        class SetNodeImpl : public NodeImpl
        {
            friend class view::ViewStrategy;
            ElementSet          m_aDataSet;
            TemplateHolder      m_aTemplate;
            TemplateProvider    m_aTemplateProvider;
            TreeImpl*           m_pParentTree;
            NodeOffset          m_nContextPos;

            typedef NodeOffset InitHelper;
            InitHelper      m_aInit;

        public:
            typedef ElementSet::Element Element;

            SetNodeImpl(data::SetNodeAddress const& _aNodeRef, Template* pTemplate);

            typedef data::SetNodeAccess DataAccess;
            DataAccess getDataAccess(data::Accessor const& _aAccessor) const;

            /// Get the template that describes elements of this set
            TemplateHolder getElementTemplate() const { return m_aTemplate; }

            /// Get a template provider that can create new elements for this set
            TemplateProvider getTemplateProvider() const { return m_aTemplateProvider; }

            void convertChanges(NodeChangesInformation& rLocalChanges, data::Accessor const& _accessor, SubtreeChange const& rExternalChange, TreeDepth nDepth);

            void    insertElement(Name const& aName, Element const& aNewElement);
            Element replaceElement(Name const& aName, Element const& aNewElement);
            Element removeElement(Name const& aName);

            void rebuildFrom(SetNodeImpl& rOldData,data::SetNodeAccess const& _aNewNode,data::SetNodeAccess const& _aOldNode);

        protected:
            ~SetNodeImpl();

        protected:
        // new overrideables
            virtual bool                    doIsEmpty() const;
            virtual ElementTreeImpl*        doFindElement(Name const& aName) ;
            virtual SetNodeVisitor::Result  doDispatchToElements(data::Accessor const& _aAccessor, SetNodeVisitor& aVisitor);
            virtual void doDifferenceToDefaultState(data::Accessor const& _aAccessor, SubtreeChange& _rChangeToDefault, ISubtree& _rDefaultTree);

            virtual SetElementChangeImpl* doAdjustToAddedElement(data::Accessor const& _aAccessor, Name const& aName, AddNode const& aAddNodeChange, Element const & aNewElement);
            virtual SetElementChangeImpl* doAdjustToRemovedElement(data::Accessor const& _aAccessor, Name const& aName, RemoveNode const& aRemoveNodeChange);
            virtual SetElementChangeImpl* doAdjustChangedElement(data::Accessor const& _aAccessor, NodeChangesInformation& rLocalChanges, Name const& aName, Change const& aChange);

            virtual void doTransferElements(ElementSet& rReplacement);

        protected:
        // helpers
            TreeImpl*   getParentTree() const;
            NodeOffset  getContextOffset() const;

            Element makeElement(data::Accessor const& _aAccessor, SetEntry const & _anEntry);
            static Element entryToElement(SetEntry const& _anEntry);
            view::ViewTreeAccess getElementView();

            /// Initialize the set data: Set context information, and build the view (actually loading the elements may be deferred)
            friend class TreeImplBuilder;
            void initElements(TemplateProvider const& aTemplateProvider, TreeImpl& rParentTree, NodeOffset nPos, TreeDepth nDepth);

        protected:
            /// does this set contain any elements (loads elements if needed)
            bool implHasLoadedElements() const;
            bool implLoadElements(data::Accessor const& _aAccessor);
            void implEnsureElementsLoaded(data::Accessor const& _aAccessor);
            void implInitElements(data::SetNodeAccess const& _aNode, TreeDepth nDepth);
            void implInitElement(Element const& aNewElement);

            void implRebuildElements(data::SetNodeAccess const& _aNewNode,data::SetNodeAccess const& _aOldNode);
        protected:
            SetElementChangeImpl* implCreateInsert    (data::Accessor const& _aAccessor, Name const& aName, Element const& aNewElement) const;
            SetElementChangeImpl* implCreateReplace   (data::Accessor const& _aAccessor, Name const& aName, Element const& aNewElement, Element const& aOldElement) const;
            SetElementChangeImpl* implCreateRemove    (data::Accessor const& _aAccessor, Name const& aName, Element const& aOldElement) const;

            SetElementChangeImpl* implAdjustToAddedElement(data::Accessor const& _aAccessor, Name const& aName, Element const& aNewElement, bool _bReplacing);
            SetElementChangeImpl* implAdjustToRemovedElement(data::Accessor const& _aAccessor, Name const& aName);

            Element makeAdditionalElement(data::Accessor const& _aAccessor, rtl::Reference<view::ViewStrategy> const& _xStrategy, AddNode const& aAddNodeChange, TreeDepth nDepth);

            Element implValidateElement(data::Accessor const& _aAccessor, Element const& aNewElement);

            void implDifferenceToDefaultState(data::Accessor const& _aAccessor, SubtreeChange& _rChangeToDefault, ISubtree& _rDefaultTree) const;
        protected:
            Element* getStoredElement(Name const& aName)
            { return m_aDataSet.getElement(aName); }
            Element const* getStoredElement(Name const& aName) const
            { return m_aDataSet.getElement(aName); }

            typedef ElementSet::PairIterator NativeIterator;
            NativeIterator beginElementSet() const
            { return m_aDataSet.beginNative(); }
            NativeIterator endElementSet() const
            { return m_aDataSet.endNative(); }

            void attach(Element const& aNewElement, Name const& aName);
            void detach(Element const& aNewElement);
        };

//-----------------------------------------------------------------------------
        // domain-specific 'dynamic_cast' replacement
        SetNodeImpl&    AsSetNode  (NodeImpl& rNode);

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

#endif // CONFIGMGR_SETNODEBEHAVIOR_HXX_
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AColumns.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-07-10 14:33:41 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_ADO_COLUMNS_HXX_
#define _CONNECTIVITY_ADO_COLUMNS_HXX_

#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_
#include "connectivity/sdbcx/VCollection.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _CONNECTIVITY_SDBCX_IREFRESHABLE_HXX_
#include "connectivity/sdbcx/IRefreshable.hxx"
#endif
#ifndef _CONNECTIVITY_ADO_AWRAPADOX_HXX_
#include "ado/Awrapadox.hxx"
#endif

namespace connectivity
{
    namespace ado
    {
        class OConnection;
        class OColumns : public sdbcx::OCollection
        {
        protected:
            WpADOColumns    m_aCollection;
            OConnection*    m_pConnection;

            virtual sdbcx::ObjectType createObject(const ::rtl::OUString& _rName);
            virtual void impl_refresh() throw(::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > createDescriptor();
            virtual sdbcx::ObjectType appendObject( const ::rtl::OUString& _rForName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor );
            virtual void dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName);
        public:
            OColumns(   ::cppu::OWeakObject& _rParent,
                        ::osl::Mutex& _rMutex,
                        const TStringVector &_rVector,
                        const WpADOColumns& _rCollection,
                        sal_Bool _bCase,
                        OConnection* _pConnection) : sdbcx::OCollection(_rParent,_bCase,_rMutex,_rVector)
                        ,m_aCollection(_rCollection)
                        ,m_pConnection(_pConnection)
            {
            }

        };
    }
}
#endif // _CONNECTIVITY_ADO_COLUMNS_HXX_

<commit_msg>INTEGRATION: CWS changefileheader (1.8.262); FILE MERGED 2008/04/01 10:53:19 thb 1.8.262.2: #i85898# Stripping all external header guards 2008/03/28 15:24:11 rt 1.8.262.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: AColumns.hxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_ADO_COLUMNS_HXX_
#define _CONNECTIVITY_ADO_COLUMNS_HXX_

#include "connectivity/sdbcx/VCollection.hxx"
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#include "connectivity/sdbcx/IRefreshable.hxx"
#include "ado/Awrapadox.hxx"

namespace connectivity
{
    namespace ado
    {
        class OConnection;
        class OColumns : public sdbcx::OCollection
        {
        protected:
            WpADOColumns    m_aCollection;
            OConnection*    m_pConnection;

            virtual sdbcx::ObjectType createObject(const ::rtl::OUString& _rName);
            virtual void impl_refresh() throw(::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > createDescriptor();
            virtual sdbcx::ObjectType appendObject( const ::rtl::OUString& _rForName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor );
            virtual void dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName);
        public:
            OColumns(   ::cppu::OWeakObject& _rParent,
                        ::osl::Mutex& _rMutex,
                        const TStringVector &_rVector,
                        const WpADOColumns& _rCollection,
                        sal_Bool _bCase,
                        OConnection* _pConnection) : sdbcx::OCollection(_rParent,_bCase,_rMutex,_rVector)
                        ,m_aCollection(_rCollection)
                        ,m_pConnection(_pConnection)
            {
            }

        };
    }
}
#endif // _CONNECTIVITY_ADO_COLUMNS_HXX_

<|endoftext|>


<commit_before><commit_msg>Crude text style rendering in the omnibox 2 popup. I copied most of the DrawString/DrawStringFragment stuff from the old code. I am pretty sure the RTL stuff doesn't actually work, I just copied enough in to get things to compile/work.<commit_after><|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007-2009, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "IECoreGL/PointsPrimitive.h"
#include "IECoreGL/DiskPrimitive.h"
#include "IECoreGL/QuadPrimitive.h"
#include "IECoreGL/SpherePrimitive.h"
#include "IECoreGL/TypedStateComponent.h"
#include "IECoreGL/Camera.h"
#include "IECoreGL/State.h"
#include "IECoreGL/GL.h"

#include "IECore/MessageHandler.h"

#include "OpenEXR/ImathFun.h"
#include "OpenEXR/ImathMatrixAlgo.h"

#include <algorithm>

using namespace IECoreGL;
using namespace IECore;
using namespace Imath;
using namespace std;

IE_CORE_DEFINERUNTIMETYPED( PointsPrimitive );

float PointsPrimitive::g_defaultWidth = 1;
float PointsPrimitive::g_defaultHeight = 1;
float PointsPrimitive::g_defaultRotation = 1;

PointsPrimitive::PointsPrimitive( Type type,
	IECore::ConstV3fVectorDataPtr p,
	IECore::ConstColor3fVectorDataPtr colors,
	IECore::ConstFloatVectorDataPtr alphas,
	IECore::ConstFloatVectorDataPtr widths,
	IECore::ConstFloatVectorDataPtr heights,
	IECore::ConstFloatVectorDataPtr rotations )
	:	m_points( p->copy() ), m_type( type )
{
	m_colors = colors ? colors->copy() : 0;
	m_alphas = alphas ? alphas->copy() : 0;
	m_widths = widths ? widths->copy() : 0;
	m_heights = heights ? heights->copy() : 0;
	m_rotations = rotations ? rotations->copy() : 0;

	unsigned int wStep = 0;
	const float *w = dataAndStride( m_widths, &g_defaultWidth, wStep );
	unsigned int hStep = 0;
	const float *h = dataAndStride( m_heights, &g_defaultHeight, hStep );
	if( !m_heights )
	{
		h = 0;
	}
	const vector<V3f> &pd = m_points->readable();
	for( unsigned int i=0; i<pd.size(); i++ )
	{
		float r = *w; w += wStep;
		if( h )
		{
			r = max( r, *h ); h += hStep;
		}
		m_bound.extendBy( Box3f( pd[i] - V3f( r ), pd[i] + V3f( r ) ) );
	}
}

PointsPrimitive::~PointsPrimitive()
{
}

void PointsPrimitive::render( ConstStatePtr state, IECore::TypeId style ) const
{
	if( depthSortRequested( state ) )
	{
		depthSort();
		m_renderSorted = true;
	}
	else
	{
		m_renderSorted = false;
	}

	Type type = m_type;
	switch( state->get<PointsPrimitiveUseGLPoints>()->value() )
	{
		case ForPointsOnly :
			break;
		case ForPointsAndDisks :
			if( type==Disk )
			{
				type = Point;
			}
			break;
		case ForAll :
			type = Point;
			break;
	}

	switch( type )
	{
		case Point :
			renderPoints( state, style );
			break;
		case Disk :
			renderDisks( state, style );
			break;
		case Quad :
			renderQuads( state, style );
			break;
		case Sphere :
			renderSpheres( state, style );
	}
}

Imath::Box3f PointsPrimitive::bound() const
{
	return m_bound;
}

size_t PointsPrimitive::vertexAttributeSize() const
{
	return m_points->readable().size();
}

const Imath::Color3f *PointsPrimitive::setOrReturnColor() const
{
	if( m_colors )
	{
		if( m_colors->readable().size()==1 )
		{
			// constant - set the color once
			const Color3f &cc = m_colors->readable()[0];
			glColor3f( cc[0], cc[1], cc[2] );
		}
		else
		{
			return &m_colors->readable()[0];
		}
	}
	return 0;
}

template<typename T>
const T *PointsPrimitive::dataAndStride( typename IECore::TypedData<std::vector<T> >::ConstPtr data, T *defaultValue, unsigned int &stride )
{
	stride = 0;
	if( !data )
	{
		stride = 0;
		return defaultValue;
	}
	if( data->readable().size()>1 )
	{
		stride = 1;
	}
	return &data->readable()[0];
}

void PointsPrimitive::renderPoints( ConstStatePtr state, IECore::TypeId style ) const
{
	const std::vector<V3f> &p = m_points->readable();

	glPointSize( state->get<PointsPrimitiveGLPointWidth>()->value() );

	const Color3f *c = setOrReturnColor();
	if( style==PrimitiveSolid::staticTypeId() )
	{
		setVertexAttributes( state );
	}

	glEnableClientState( GL_VERTEX_ARRAY );
	glVertexPointer( 3, GL_FLOAT, 0, &p[0] );
	if( c )
	{
		glEnableClientState( GL_COLOR_ARRAY );
		glColorPointer( 3, GL_FLOAT, 0, c );
	}

	glDrawArrays( GL_POINTS, 0, p.size() );

	glDisableClientState( GL_COLOR_ARRAY );
	glDisableClientState( GL_VERTEX_ARRAY );
}

void PointsPrimitive::renderDisks( ConstStatePtr state, IECore::TypeId style ) const
{
	DiskPrimitivePtr disk = new DiskPrimitive();

	V3f cameraCentre = Camera::positionInObjectSpace();
	V3f cameraUp = Camera::upInObjectSpace();

	const std::vector<V3f> &p = m_points->readable();

	const Color3f *c = setOrReturnColor();

	unsigned int wStep = 0;
	const float *w = dataAndStride( m_widths, &g_defaultWidth, wStep );
	if( !wStep )
	{
		disk->setRadius( *w / 2.0f );
		w = 0;
	}

	for( unsigned int j=0; j<p.size(); j++ )
	{
		unsigned int i = m_renderSorted ? m_depthOrder[j] : j;

		if( style==PrimitiveSolid::staticTypeId() )
		{
			setVertexAttributesAsUniforms( i );
			if( c )
			{
				glColor3f( c[i][0], c[i][1], c[i][2] );
			}
		}

		M44f aim = alignZAxisWithTargetDir( cameraCentre - p[i], cameraUp );
		glPushMatrix();
			glTranslatef( p[i][0], p[i][1], p[i][2] );
			glMultMatrixf( aim.getValue() );
			if( w )
			{
				disk->setRadius( w[i] / 2.0f );
			}
			disk->render( state, style );
		glPopMatrix();
	}

}

void PointsPrimitive::renderQuads( ConstStatePtr state, IECore::TypeId style ) const
{
	QuadPrimitivePtr quad = new QuadPrimitive();
	V3f cameraCentre = Camera::positionInObjectSpace();
	V3f cameraUp = Camera::upInObjectSpace();

	const std::vector<V3f> &p = m_points->readable();

	const Color3f *c = setOrReturnColor();

	unsigned int wStep = 0;
	const float *w = dataAndStride( m_widths, &g_defaultWidth, wStep );
	if( !wStep )
	{
		quad->setWidth( *w );
		w = 0;
	}

	unsigned int hStep = 0;
	const float *h = dataAndStride( m_heights, &g_defaultHeight, hStep );
	if( !hStep )
	{
		quad->setHeight( *h );
		h = 0;
	}

	unsigned int rStep = 0;
	const float *r = dataAndStride( m_rotations, &g_defaultRotation, rStep );

	for( unsigned int j=0; j<p.size(); j++ )
	{
		unsigned int i = m_renderSorted ? m_depthOrder[j] : j;

		if( style==PrimitiveSolid::staticTypeId() )
		{
			setVertexAttributesAsUniforms( i );
			if( c )
			{
				glColor3f( c[i][0], c[i][1], c[i][2] );
			}
		}

		M44f aim = alignZAxisWithTargetDir( cameraCentre - p[i], cameraUp );

		glPushMatrix();
			glTranslatef( p[i][0], p[i][1], p[i][2] );
			glMultMatrixf( aim.getValue() );
			glRotatef( -r[i*rStep], 0, 0, 1 );
			if( w )
			{
				quad->setWidth( w[i] );
			}
			if( h )
			{
				quad->setHeight( h[i] );
			}
			quad->render( state, style );
		glPopMatrix();
	}

}

void PointsPrimitive::renderSpheres( ConstStatePtr state, IECore::TypeId style ) const
{
	SpherePrimitivePtr sphere = new SpherePrimitive();
	const std::vector<V3f> &p = m_points->readable();

	const Color3f *c = setOrReturnColor();

	unsigned int wStep = 0;
	const float *w = dataAndStride( m_widths, &g_defaultWidth, wStep );
	if( !wStep )
	{
		sphere->setRadius( *w / 2.0f );
		w = 0;
	}

	for( unsigned int j=0; j<p.size(); j++ )
	{
		unsigned int i = m_renderSorted ? m_depthOrder[j] : j;

		if( style==PrimitiveSolid::staticTypeId() )
		{
			setVertexAttributesAsUniforms( i );
			if( c )
			{
				glColor3f( c[i][0], c[i][1], c[i][2] );
			}
		}

		glPushMatrix();
			glTranslatef( p[i][0], p[i][1], p[i][2] );
			if( w )
			{
				sphere->setRadius( w[i] / 2.0f );
			}
			sphere->render( state, style );
		glPopMatrix();
	}

}

struct SortFn
{
	SortFn( const vector<float> &d ) : depths( d ) {};
	bool operator()( int f, int s ) { return depths[f] > depths[s]; };
	const vector<float> &depths;
};

/// \todo Stick a radix sort in IECore and use that.
void PointsPrimitive::depthSort() const
{
	V3f cameraDirection = Camera::viewDirectionInObjectSpace();
	cameraDirection.normalize();

	const vector<V3f> &points = m_points->readable();
	if( !m_depthOrder.size() )
	{
		// never sorted before. initialize space.
		m_depthOrder.resize( points.size() );
		for( unsigned int i=0; i<m_depthOrder.size(); i++ )
		{
			m_depthOrder[i] = i;
		}
		m_depths.resize( points.size() );
	}
	else
	{
		// sorted before. see if the camera direction has changed enough
		// to warrant resorting.
		if( cameraDirection.dot( m_depthCameraDirection ) > 0.95 )
		{
			return;
		}
	}

	m_depthCameraDirection = cameraDirection;

	// calculate all distances
	for( unsigned int i=0; i<m_depths.size(); i++ )
	{
		m_depths[i] = points[i].dot( m_depthCameraDirection );
	}

	// sort based on those distances
	SortFn sorter( m_depths );
	sort( m_depthOrder.begin(), m_depthOrder.end(), sorter );
}
<commit_msg>Changed todo<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007-2009, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "IECoreGL/PointsPrimitive.h"
#include "IECoreGL/DiskPrimitive.h"
#include "IECoreGL/QuadPrimitive.h"
#include "IECoreGL/SpherePrimitive.h"
#include "IECoreGL/TypedStateComponent.h"
#include "IECoreGL/Camera.h"
#include "IECoreGL/State.h"
#include "IECoreGL/GL.h"

#include "IECore/MessageHandler.h"

#include "OpenEXR/ImathFun.h"
#include "OpenEXR/ImathMatrixAlgo.h"

#include <algorithm>

using namespace IECoreGL;
using namespace IECore;
using namespace Imath;
using namespace std;

IE_CORE_DEFINERUNTIMETYPED( PointsPrimitive );

float PointsPrimitive::g_defaultWidth = 1;
float PointsPrimitive::g_defaultHeight = 1;
float PointsPrimitive::g_defaultRotation = 1;

PointsPrimitive::PointsPrimitive( Type type,
	IECore::ConstV3fVectorDataPtr p,
	IECore::ConstColor3fVectorDataPtr colors,
	IECore::ConstFloatVectorDataPtr alphas,
	IECore::ConstFloatVectorDataPtr widths,
	IECore::ConstFloatVectorDataPtr heights,
	IECore::ConstFloatVectorDataPtr rotations )
	:	m_points( p->copy() ), m_type( type )
{
	m_colors = colors ? colors->copy() : 0;
	m_alphas = alphas ? alphas->copy() : 0;
	m_widths = widths ? widths->copy() : 0;
	m_heights = heights ? heights->copy() : 0;
	m_rotations = rotations ? rotations->copy() : 0;

	unsigned int wStep = 0;
	const float *w = dataAndStride( m_widths, &g_defaultWidth, wStep );
	unsigned int hStep = 0;
	const float *h = dataAndStride( m_heights, &g_defaultHeight, hStep );
	if( !m_heights )
	{
		h = 0;
	}
	const vector<V3f> &pd = m_points->readable();
	for( unsigned int i=0; i<pd.size(); i++ )
	{
		float r = *w; w += wStep;
		if( h )
		{
			r = max( r, *h ); h += hStep;
		}
		m_bound.extendBy( Box3f( pd[i] - V3f( r ), pd[i] + V3f( r ) ) );
	}
}

PointsPrimitive::~PointsPrimitive()
{
}

void PointsPrimitive::render( ConstStatePtr state, IECore::TypeId style ) const
{
	if( depthSortRequested( state ) )
	{
		depthSort();
		m_renderSorted = true;
	}
	else
	{
		m_renderSorted = false;
	}

	Type type = m_type;
	switch( state->get<PointsPrimitiveUseGLPoints>()->value() )
	{
		case ForPointsOnly :
			break;
		case ForPointsAndDisks :
			if( type==Disk )
			{
				type = Point;
			}
			break;
		case ForAll :
			type = Point;
			break;
	}

	switch( type )
	{
		case Point :
			renderPoints( state, style );
			break;
		case Disk :
			renderDisks( state, style );
			break;
		case Quad :
			renderQuads( state, style );
			break;
		case Sphere :
			renderSpheres( state, style );
	}
}

Imath::Box3f PointsPrimitive::bound() const
{
	return m_bound;
}

size_t PointsPrimitive::vertexAttributeSize() const
{
	return m_points->readable().size();
}

const Imath::Color3f *PointsPrimitive::setOrReturnColor() const
{
	if( m_colors )
	{
		if( m_colors->readable().size()==1 )
		{
			// constant - set the color once
			const Color3f &cc = m_colors->readable()[0];
			glColor3f( cc[0], cc[1], cc[2] );
		}
		else
		{
			return &m_colors->readable()[0];
		}
	}
	return 0;
}

template<typename T>
const T *PointsPrimitive::dataAndStride( typename IECore::TypedData<std::vector<T> >::ConstPtr data, T *defaultValue, unsigned int &stride )
{
	stride = 0;
	if( !data )
	{
		stride = 0;
		return defaultValue;
	}
	if( data->readable().size()>1 )
	{
		stride = 1;
	}
	return &data->readable()[0];
}

void PointsPrimitive::renderPoints( ConstStatePtr state, IECore::TypeId style ) const
{
	const std::vector<V3f> &p = m_points->readable();

	glPointSize( state->get<PointsPrimitiveGLPointWidth>()->value() );

	const Color3f *c = setOrReturnColor();
	if( style==PrimitiveSolid::staticTypeId() )
	{
		setVertexAttributes( state );
	}

	glEnableClientState( GL_VERTEX_ARRAY );
	glVertexPointer( 3, GL_FLOAT, 0, &p[0] );
	if( c )
	{
		glEnableClientState( GL_COLOR_ARRAY );
		glColorPointer( 3, GL_FLOAT, 0, c );
	}

	glDrawArrays( GL_POINTS, 0, p.size() );

	glDisableClientState( GL_COLOR_ARRAY );
	glDisableClientState( GL_VERTEX_ARRAY );
}

void PointsPrimitive::renderDisks( ConstStatePtr state, IECore::TypeId style ) const
{
	DiskPrimitivePtr disk = new DiskPrimitive();

	V3f cameraCentre = Camera::positionInObjectSpace();
	V3f cameraUp = Camera::upInObjectSpace();

	const std::vector<V3f> &p = m_points->readable();

	const Color3f *c = setOrReturnColor();

	unsigned int wStep = 0;
	const float *w = dataAndStride( m_widths, &g_defaultWidth, wStep );
	if( !wStep )
	{
		disk->setRadius( *w / 2.0f );
		w = 0;
	}

	for( unsigned int j=0; j<p.size(); j++ )
	{
		unsigned int i = m_renderSorted ? m_depthOrder[j] : j;

		if( style==PrimitiveSolid::staticTypeId() )
		{
			setVertexAttributesAsUniforms( i );
			if( c )
			{
				glColor3f( c[i][0], c[i][1], c[i][2] );
			}
		}

		M44f aim = alignZAxisWithTargetDir( cameraCentre - p[i], cameraUp );
		glPushMatrix();
			glTranslatef( p[i][0], p[i][1], p[i][2] );
			glMultMatrixf( aim.getValue() );
			if( w )
			{
				disk->setRadius( w[i] / 2.0f );
			}
			disk->render( state, style );
		glPopMatrix();
	}

}

void PointsPrimitive::renderQuads( ConstStatePtr state, IECore::TypeId style ) const
{
	QuadPrimitivePtr quad = new QuadPrimitive();
	V3f cameraCentre = Camera::positionInObjectSpace();
	V3f cameraUp = Camera::upInObjectSpace();

	const std::vector<V3f> &p = m_points->readable();

	const Color3f *c = setOrReturnColor();

	unsigned int wStep = 0;
	const float *w = dataAndStride( m_widths, &g_defaultWidth, wStep );
	if( !wStep )
	{
		quad->setWidth( *w );
		w = 0;
	}

	unsigned int hStep = 0;
	const float *h = dataAndStride( m_heights, &g_defaultHeight, hStep );
	if( !hStep )
	{
		quad->setHeight( *h );
		h = 0;
	}

	unsigned int rStep = 0;
	const float *r = dataAndStride( m_rotations, &g_defaultRotation, rStep );

	for( unsigned int j=0; j<p.size(); j++ )
	{
		unsigned int i = m_renderSorted ? m_depthOrder[j] : j;

		if( style==PrimitiveSolid::staticTypeId() )
		{
			setVertexAttributesAsUniforms( i );
			if( c )
			{
				glColor3f( c[i][0], c[i][1], c[i][2] );
			}
		}

		M44f aim = alignZAxisWithTargetDir( cameraCentre - p[i], cameraUp );

		glPushMatrix();
			glTranslatef( p[i][0], p[i][1], p[i][2] );
			glMultMatrixf( aim.getValue() );
			glRotatef( -r[i*rStep], 0, 0, 1 );
			if( w )
			{
				quad->setWidth( w[i] );
			}
			if( h )
			{
				quad->setHeight( h[i] );
			}
			quad->render( state, style );
		glPopMatrix();
	}

}

void PointsPrimitive::renderSpheres( ConstStatePtr state, IECore::TypeId style ) const
{
	SpherePrimitivePtr sphere = new SpherePrimitive();
	const std::vector<V3f> &p = m_points->readable();

	const Color3f *c = setOrReturnColor();

	unsigned int wStep = 0;
	const float *w = dataAndStride( m_widths, &g_defaultWidth, wStep );
	if( !wStep )
	{
		sphere->setRadius( *w / 2.0f );
		w = 0;
	}

	for( unsigned int j=0; j<p.size(); j++ )
	{
		unsigned int i = m_renderSorted ? m_depthOrder[j] : j;

		if( style==PrimitiveSolid::staticTypeId() )
		{
			setVertexAttributesAsUniforms( i );
			if( c )
			{
				glColor3f( c[i][0], c[i][1], c[i][2] );
			}
		}

		glPushMatrix();
			glTranslatef( p[i][0], p[i][1], p[i][2] );
			if( w )
			{
				sphere->setRadius( w[i] / 2.0f );
			}
			sphere->render( state, style );
		glPopMatrix();
	}

}

struct SortFn
{
	SortFn( const vector<float> &d ) : depths( d ) {};
	bool operator()( int f, int s ) { return depths[f] > depths[s]; };
	const vector<float> &depths;
};

/// \todo Use IECore::RadixSort (might still want to use std::sort for small numbers of points - profile to check this)
void PointsPrimitive::depthSort() const
{
	V3f cameraDirection = Camera::viewDirectionInObjectSpace();
	cameraDirection.normalize();

	const vector<V3f> &points = m_points->readable();
	if( !m_depthOrder.size() )
	{
		// never sorted before. initialize space.
		m_depthOrder.resize( points.size() );
		for( unsigned int i=0; i<m_depthOrder.size(); i++ )
		{
			m_depthOrder[i] = i;
		}
		m_depths.resize( points.size() );
	}
	else
	{
		// sorted before. see if the camera direction has changed enough
		// to warrant resorting.
		if( cameraDirection.dot( m_depthCameraDirection ) > 0.95 )
		{
			return;
		}
	}

	m_depthCameraDirection = cameraDirection;

	// calculate all distances
	for( unsigned int i=0; i<m_depths.size(); i++ )
	{
		m_depths[i] = points[i].dot( m_depthCameraDirection );
	}

	// sort based on those distances
	SortFn sorter( m_depths );
	sort( m_depthOrder.begin(), m_depthOrder.end(), sorter );
}
<|endoftext|>