Update the trunk to the OpenCV's CVS (2008-07-14)
[opencv] / cxcore / include / cxtypes.h
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
5 //  By downloading, copying, installing or using the software you agree to this license.
6 //  If you do not agree to this license, do not download, install,
7 //  copy or use the software.
8 //
9 //
10 //                        Intel License Agreement
11 //                For Open Source Computer Vision Library
12 //
13 // Copyright (C) 2000, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
15 //
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
18 //
19 //   * Redistribution's of source code must retain the above copyright notice,
20 //     this list of conditions and the following disclaimer.
21 //
22 //   * Redistribution's in binary form must reproduce the above copyright notice,
23 //     this list of conditions and the following disclaimer in the documentation
24 //     and/or other materials provided with the distribution.
25 //
26 //   * The name of Intel Corporation may not be used to endorse or promote products
27 //     derived from this software without specific prior written permission.
28 //
29 // This software is provided by the copyright holders and contributors "as is" and
30 // any express or implied warranties, including, but not limited to, the implied
31 // warranties of merchantability and fitness for a particular purpose are disclaimed.
32 // In no event shall the Intel Corporation or contributors be liable for any direct,
33 // indirect, incidental, special, exemplary, or consequential damages
34 // (including, but not limited to, procurement of substitute goods or services;
35 // loss of use, data, or profits; or business interruption) however caused
36 // and on any theory of liability, whether in contract, strict liability,
37 // or tort (including negligence or otherwise) arising in any way out of
38 // the use of this software, even if advised of the possibility of such damage.
39 //
40 //M*/
41
42 #ifndef _CXCORE_TYPES_H_
43 #define _CXCORE_TYPES_H_
44
45 #if !defined _CRT_SECURE_NO_DEPRECATE && _MSC_VER > 1300
46 #define _CRT_SECURE_NO_DEPRECATE /* to avoid multiple Visual Studio 2005 warnings */
47 #endif
48
49 #ifndef SKIP_INCLUDES
50   #include <assert.h>
51   #include <stdlib.h>
52   #include <string.h>
53   #include <float.h>
54
55   #if defined __ICL
56     #define CV_ICC   __ICL
57   #elif defined __ICC
58     #define CV_ICC   __ICC
59   #elif defined __ECL
60     #define CV_ICC   __ECL
61   #elif defined __ECC
62     #define CV_ICC   __ECC
63   #endif
64
65   #if defined WIN64 && defined EM64T && (defined _MSC_VER || defined CV_ICC) \
66       || defined __SSE2__ || defined _MM_SHUFFLE2
67     #include <emmintrin.h>
68     #define CV_SSE2 1
69   #else
70     #define CV_SSE2 0
71   #endif
72
73   #if defined __BORLANDC__
74     #include <fastmath.h>
75   #elif defined WIN64 && !defined EM64T && defined CV_ICC
76     #include <mathimf.h>
77   #else
78     #include <math.h>
79   #endif
80
81   #ifdef HAVE_IPL
82       #ifndef __IPL_H__
83           #if defined WIN32 || defined WIN64
84               #include <ipl.h>
85           #else
86               #include <ipl/ipl.h>
87           #endif
88       #endif
89   #elif defined __IPL_H__
90       #define HAVE_IPL
91   #endif
92 #endif // SKIP_INCLUDES
93
94 #if defined WIN32 || defined WIN64
95     #define CV_CDECL __cdecl
96     #define CV_STDCALL __stdcall
97 #else
98     #define CV_CDECL
99     #define CV_STDCALL
100 #endif
101
102 #ifndef CV_EXTERN_C
103     #ifdef __cplusplus
104         #define CV_EXTERN_C extern "C"
105         #define CV_DEFAULT(val) = val
106     #else
107         #define CV_EXTERN_C
108         #define CV_DEFAULT(val)
109     #endif
110 #endif
111
112 #ifndef CV_EXTERN_C_FUNCPTR
113     #ifdef __cplusplus
114         #define CV_EXTERN_C_FUNCPTR(x) extern "C" { typedef x; }
115     #else
116         #define CV_EXTERN_C_FUNCPTR(x) typedef x
117     #endif
118 #endif
119
120 #ifndef CV_INLINE
121 #if defined __cplusplus
122     #define CV_INLINE inline
123 #elif (defined WIN32 || defined WIN64) && !defined __GNUC__
124     #define CV_INLINE __inline
125 #else
126     #define CV_INLINE static
127 #endif
128 #endif /* CV_INLINE */
129
130 #if (defined WIN32 || defined WIN64) && defined CVAPI_EXPORTS
131     #define CV_EXPORTS __declspec(dllexport)
132 #else
133     #define CV_EXPORTS
134 #endif
135
136 #ifndef CVAPI
137     #define CVAPI(rettype) CV_EXTERN_C CV_EXPORTS rettype CV_CDECL
138 #endif
139
140 #if defined _MSC_VER || defined __BORLANDC__
141 typedef __int64 int64;
142 typedef unsigned __int64 uint64;
143 #else
144 typedef long long int64;
145 typedef unsigned long long uint64;
146 #endif
147
148 #ifndef HAVE_IPL
149 typedef unsigned char uchar;
150 typedef unsigned short ushort;
151 #endif
152
153 typedef signed char schar;
154
155 /* CvArr* is used to pass arbitrary
156  * array-like data structures
157  * into functions where the particular
158  * array type is recognized at runtime:
159  */
160 typedef void CvArr;
161
162 typedef union Cv32suf
163 {
164     int i;
165     unsigned u;
166     float f;
167 }
168 Cv32suf;
169
170 typedef union Cv64suf
171 {
172     int64 i;
173     uint64 u;
174     double f;
175 }
176 Cv64suf;
177
178 /****************************************************************************************\
179 *                             Common macros and inline functions                         *
180 \****************************************************************************************/
181
182 #define CV_PI   3.1415926535897932384626433832795
183 #define CV_LOG2 0.69314718055994530941723212145818
184
185 #define CV_SWAP(a,b,t) ((t) = (a), (a) = (b), (b) = (t))
186
187 #ifndef MIN
188 #define MIN(a,b)  ((a) > (b) ? (b) : (a))
189 #endif
190
191 #ifndef MAX
192 #define MAX(a,b)  ((a) < (b) ? (b) : (a))
193 #endif
194
195 /* min & max without jumps */
196 #define  CV_IMIN(a, b)  ((a) ^ (((a)^(b)) & (((a) < (b)) - 1)))
197
198 #define  CV_IMAX(a, b)  ((a) ^ (((a)^(b)) & (((a) > (b)) - 1)))
199
200 /* absolute value without jumps */
201 #ifndef __cplusplus
202 #define  CV_IABS(a)     (((a) ^ ((a) < 0 ? -1 : 0)) - ((a) < 0 ? -1 : 0))
203 #else
204 #define  CV_IABS(a)     abs(a)
205 #endif
206 #define  CV_CMP(a,b)    (((a) > (b)) - ((a) < (b)))
207 #define  CV_SIGN(a)     CV_CMP((a),0)
208
209 CV_INLINE  int  cvRound( double value )
210 {
211 #if CV_SSE2
212     __m128d t = _mm_load_sd( &value );
213     return _mm_cvtsd_si32(t);
214 #elif defined WIN32 && !defined WIN64 && defined _MSC_VER
215     int t;
216     __asm
217     {
218         fld value;
219         fistp t;
220     }
221     return t;
222 #elif (defined HAVE_LRINT) || (defined WIN64 && !defined EM64T && defined CV_ICC)
223     return (int)lrint(value);
224 #else
225     /*
226      the algorithm was taken from Agner Fog's optimization guide
227      at http://www.agner.org/assem
228      */
229     Cv64suf temp;
230     temp.f = value + 6755399441055744.0;
231     return (int)temp.u;
232 #endif
233 }
234
235
236 CV_INLINE  int  cvFloor( double value )
237 {
238 #if CV_SSE2
239     __m128d t = _mm_load_sd( &value );
240     int i = _mm_cvtsd_si32(t);
241     return i - _mm_movemask_pd(_mm_cmplt_sd(t,_mm_cvtsi32_sd(t,i)));
242 #else
243     int temp = cvRound(value);
244     Cv32suf diff;
245     diff.f = (float)(value - temp);
246     return temp - (diff.i < 0);
247 #endif
248 }
249
250
251 CV_INLINE  int  cvCeil( double value )
252 {
253 #if CV_SSE2
254     __m128d t = _mm_load_sd( &value );
255     int i = _mm_cvtsd_si32(t);
256     return i + _mm_movemask_pd(_mm_cmplt_sd(_mm_cvtsi32_sd(t,i),t));
257 #else
258     int temp = cvRound(value);
259     Cv32suf diff;
260     diff.f = (float)(temp - value);
261     return temp + (diff.i < 0);
262 #endif
263 }
264
265 #define cvInvSqrt(value) ((float)(1./sqrt(value)))
266 #define cvSqrt(value)  ((float)sqrt(value))
267
268 CV_INLINE int cvIsNaN( double value )
269 {
270 #if 1/*defined _MSC_VER || defined __BORLANDC__
271     return _isnan(value);
272 #elif defined __GNUC__
273     return isnan(value);
274 #else*/
275     Cv64suf ieee754;
276     ieee754.f = value;
277     return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) +
278            ((unsigned)ieee754.u != 0) > 0x7ff00000;
279 #endif
280 }
281
282
283 CV_INLINE int cvIsInf( double value )
284 {
285 #if 1/*defined _MSC_VER || defined __BORLANDC__
286     return !_finite(value);
287 #elif defined __GNUC__
288     return isinf(value);
289 #else*/
290     Cv64suf ieee754;
291     ieee754.f = value;
292     return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) == 0x7ff00000 &&
293            (unsigned)ieee754.u == 0;
294 #endif
295 }
296
297
298 /*************** Random number generation *******************/
299
300 typedef uint64 CvRNG;
301
302 CV_INLINE CvRNG cvRNG( int64 seed CV_DEFAULT(-1))
303 {
304     CvRNG rng = seed ? (uint64)seed : (uint64)(int64)-1;
305     return rng;
306 }
307
308 /* Return random 32-bit unsigned integer: */
309 CV_INLINE unsigned cvRandInt( CvRNG* rng )
310 {
311     uint64 temp = *rng;
312     temp = (uint64)(unsigned)temp*1554115554 + (temp >> 32);
313     *rng = temp;
314     return (unsigned)temp;
315 }
316
317 /* Returns random floating-point number between 0 and 1: */
318 CV_INLINE double cvRandReal( CvRNG* rng )
319 {
320     return cvRandInt(rng)*2.3283064365386962890625e-10 /* 2^-32 */;
321 }
322
323 /****************************************************************************************\
324 *                                  Image type (IplImage)                                 *
325 \****************************************************************************************/
326
327 #ifndef HAVE_IPL
328
329 /*
330  * The following definitions (until #endif)
331  * is an extract from IPL headers.
332  * Copyright (c) 1995 Intel Corporation.
333  */
334 #define IPL_DEPTH_SIGN 0x80000000
335
336 #define IPL_DEPTH_1U     1
337 #define IPL_DEPTH_8U     8
338 #define IPL_DEPTH_16U   16
339 #define IPL_DEPTH_32F   32
340
341 #define IPL_DEPTH_8S  (IPL_DEPTH_SIGN| 8)
342 #define IPL_DEPTH_16S (IPL_DEPTH_SIGN|16)
343 #define IPL_DEPTH_32S (IPL_DEPTH_SIGN|32)
344
345 #define IPL_DATA_ORDER_PIXEL  0
346 #define IPL_DATA_ORDER_PLANE  1
347
348 #define IPL_ORIGIN_TL 0
349 #define IPL_ORIGIN_BL 1
350
351 #define IPL_ALIGN_4BYTES   4
352 #define IPL_ALIGN_8BYTES   8
353 #define IPL_ALIGN_16BYTES 16
354 #define IPL_ALIGN_32BYTES 32
355
356 #define IPL_ALIGN_DWORD   IPL_ALIGN_4BYTES
357 #define IPL_ALIGN_QWORD   IPL_ALIGN_8BYTES
358
359 #define IPL_BORDER_CONSTANT   0
360 #define IPL_BORDER_REPLICATE  1
361 #define IPL_BORDER_REFLECT    2
362 #define IPL_BORDER_WRAP       3
363
364 typedef struct _IplImage
365 {
366     int  nSize;             /* sizeof(IplImage) */
367     int  ID;                /* version (=0)*/
368     int  nChannels;         /* Most of OpenCV functions support 1,2,3 or 4 channels */
369     int  alphaChannel;      /* Ignored by OpenCV */
370     int  depth;             /* Pixel depth in bits: IPL_DEPTH_8U, IPL_DEPTH_8S, IPL_DEPTH_16S,
371                                IPL_DEPTH_32S, IPL_DEPTH_32F and IPL_DEPTH_64F are supported.  */
372     char colorModel[4];     /* Ignored by OpenCV */
373     char channelSeq[4];     /* ditto */
374     int  dataOrder;         /* 0 - interleaved color channels, 1 - separate color channels.
375                                cvCreateImage can only create interleaved images */
376     int  origin;            /* 0 - top-left origin,
377                                1 - bottom-left origin (Windows bitmaps style).  */
378     int  align;             /* Alignment of image rows (4 or 8).
379                                OpenCV ignores it and uses widthStep instead.    */
380     int  width;             /* Image width in pixels.                           */
381     int  height;            /* Image height in pixels.                          */
382     struct _IplROI *roi;    /* Image ROI. If NULL, the whole image is selected. */
383     struct _IplImage *maskROI;      /* Must be NULL. */
384     void  *imageId;                 /* "           " */
385     struct _IplTileInfo *tileInfo;  /* "           " */
386     int  imageSize;         /* Image data size in bytes
387                                (==image->height*image->widthStep
388                                in case of interleaved data)*/
389     char *imageData;        /* Pointer to aligned image data.         */
390     int  widthStep;         /* Size of aligned image row in bytes.    */
391     int  BorderMode[4];     /* Ignored by OpenCV.                     */
392     int  BorderConst[4];    /* Ditto.                                 */
393     char *imageDataOrigin;  /* Pointer to very origin of image data
394                                (not necessarily aligned) -
395                                needed for correct deallocation */
396 }
397 IplImage;
398
399 typedef struct _IplTileInfo IplTileInfo;
400
401 typedef struct _IplROI
402 {
403     int  coi; /* 0 - no COI (all channels are selected), 1 - 0th channel is selected ...*/
404     int  xOffset;
405     int  yOffset;
406     int  width;
407     int  height;
408 }
409 IplROI;
410
411 typedef struct _IplConvKernel
412 {
413     int  nCols;
414     int  nRows;
415     int  anchorX;
416     int  anchorY;
417     int *values;
418     int  nShiftR;
419 }
420 IplConvKernel;
421
422 typedef struct _IplConvKernelFP
423 {
424     int  nCols;
425     int  nRows;
426     int  anchorX;
427     int  anchorY;
428     float *values;
429 }
430 IplConvKernelFP;
431
432 #define IPL_IMAGE_HEADER 1
433 #define IPL_IMAGE_DATA   2
434 #define IPL_IMAGE_ROI    4
435
436 #endif/*HAVE_IPL*/
437
438 /* extra border mode */
439 #define IPL_BORDER_REFLECT_101    4
440
441 #define IPL_IMAGE_MAGIC_VAL  ((int)sizeof(IplImage))
442 #define CV_TYPE_NAME_IMAGE "opencv-image"
443
444 #define CV_IS_IMAGE_HDR(img) \
445     ((img) != NULL && ((const IplImage*)(img))->nSize == sizeof(IplImage))
446
447 #define CV_IS_IMAGE(img) \
448     (CV_IS_IMAGE_HDR(img) && ((IplImage*)img)->imageData != NULL)
449
450 /* for storing double-precision
451    floating point data in IplImage's */
452 #define IPL_DEPTH_64F  64
453
454 /* get reference to pixel at (col,row),
455    for multi-channel images (col) should be multiplied by number of channels */
456 #define CV_IMAGE_ELEM( image, elemtype, row, col )       \
457     (((elemtype*)((image)->imageData + (image)->widthStep*(row)))[(col)])
458
459 /****************************************************************************************\
460 *                                  Matrix type (CvMat)                                   *
461 \****************************************************************************************/
462
463 #define CV_CN_MAX     64
464 #define CV_CN_SHIFT   3
465 #define CV_DEPTH_MAX  (1 << CV_CN_SHIFT)
466
467 #define CV_8U   0
468 #define CV_8S   1
469 #define CV_16U  2
470 #define CV_16S  3
471 #define CV_32S  4
472 #define CV_32F  5
473 #define CV_64F  6
474 #define CV_USRTYPE1 7
475
476 #define CV_MAKETYPE(depth,cn) ((depth) + (((cn)-1) << CV_CN_SHIFT))
477 #define CV_MAKE_TYPE CV_MAKETYPE
478
479 #define CV_8UC1 CV_MAKETYPE(CV_8U,1)
480 #define CV_8UC2 CV_MAKETYPE(CV_8U,2)
481 #define CV_8UC3 CV_MAKETYPE(CV_8U,3)
482 #define CV_8UC4 CV_MAKETYPE(CV_8U,4)
483 #define CV_8UC(n) CV_MAKETYPE(CV_8U,(n))
484
485 #define CV_8SC1 CV_MAKETYPE(CV_8S,1)
486 #define CV_8SC2 CV_MAKETYPE(CV_8S,2)
487 #define CV_8SC3 CV_MAKETYPE(CV_8S,3)
488 #define CV_8SC4 CV_MAKETYPE(CV_8S,4)
489 #define CV_8SC(n) CV_MAKETYPE(CV_8S,(n))
490
491 #define CV_16UC1 CV_MAKETYPE(CV_16U,1)
492 #define CV_16UC2 CV_MAKETYPE(CV_16U,2)
493 #define CV_16UC3 CV_MAKETYPE(CV_16U,3)
494 #define CV_16UC4 CV_MAKETYPE(CV_16U,4)
495 #define CV_16UC(n) CV_MAKETYPE(CV_16U,(n))
496
497 #define CV_16SC1 CV_MAKETYPE(CV_16S,1)
498 #define CV_16SC2 CV_MAKETYPE(CV_16S,2)
499 #define CV_16SC3 CV_MAKETYPE(CV_16S,3)
500 #define CV_16SC4 CV_MAKETYPE(CV_16S,4)
501 #define CV_16SC(n) CV_MAKETYPE(CV_16S,(n))
502
503 #define CV_32SC1 CV_MAKETYPE(CV_32S,1)
504 #define CV_32SC2 CV_MAKETYPE(CV_32S,2)
505 #define CV_32SC3 CV_MAKETYPE(CV_32S,3)
506 #define CV_32SC4 CV_MAKETYPE(CV_32S,4)
507 #define CV_32SC(n) CV_MAKETYPE(CV_32S,(n))
508
509 #define CV_32FC1 CV_MAKETYPE(CV_32F,1)
510 #define CV_32FC2 CV_MAKETYPE(CV_32F,2)
511 #define CV_32FC3 CV_MAKETYPE(CV_32F,3)
512 #define CV_32FC4 CV_MAKETYPE(CV_32F,4)
513 #define CV_32FC(n) CV_MAKETYPE(CV_32F,(n))
514
515 #define CV_64FC1 CV_MAKETYPE(CV_64F,1)
516 #define CV_64FC2 CV_MAKETYPE(CV_64F,2)
517 #define CV_64FC3 CV_MAKETYPE(CV_64F,3)
518 #define CV_64FC4 CV_MAKETYPE(CV_64F,4)
519 #define CV_64FC(n) CV_MAKETYPE(CV_64F,(n))
520
521 #define CV_AUTO_STEP  0x7fffffff
522 #define CV_WHOLE_ARR  cvSlice( 0, 0x3fffffff )
523
524 #define CV_MAT_CN_MASK          ((CV_CN_MAX - 1) << CV_CN_SHIFT)
525 #define CV_MAT_CN(flags)        ((((flags) & CV_MAT_CN_MASK) >> CV_CN_SHIFT) + 1)
526 #define CV_MAT_DEPTH_MASK       (CV_DEPTH_MAX - 1)
527 #define CV_MAT_DEPTH(flags)     ((flags) & CV_MAT_DEPTH_MASK)
528 #define CV_MAT_TYPE_MASK        (CV_DEPTH_MAX*CV_CN_MAX - 1)
529 #define CV_MAT_TYPE(flags)      ((flags) & CV_MAT_TYPE_MASK)
530 #define CV_MAT_CONT_FLAG_SHIFT  14
531 #define CV_MAT_CONT_FLAG        (1 << CV_MAT_CONT_FLAG_SHIFT)
532 #define CV_IS_MAT_CONT(flags)   ((flags) & CV_MAT_CONT_FLAG)
533 #define CV_IS_CONT_MAT          CV_IS_MAT_CONT
534 #define CV_MAT_TEMP_FLAG_SHIFT  15
535 #define CV_MAT_TEMP_FLAG        (1 << CV_MAT_TEMP_FLAG_SHIFT)
536 #define CV_IS_TEMP_MAT(flags)   ((flags) & CV_MAT_TEMP_FLAG)
537
538 #define CV_MAGIC_MASK       0xFFFF0000
539 #define CV_MAT_MAGIC_VAL    0x42420000
540 #define CV_TYPE_NAME_MAT    "opencv-matrix"
541
542 typedef struct CvMat
543 {
544     int type;
545     int step;
546
547     /* for internal use only */
548     int* refcount;
549     int hdr_refcount;
550
551     union
552     {
553         uchar* ptr;
554         short* s;
555         int* i;
556         float* fl;
557         double* db;
558     } data;
559
560 #ifdef __cplusplus
561     union
562     {
563         int rows;
564         int height;
565     };
566
567     union
568     {
569         int cols;
570         int width;
571     };
572 #else
573     int rows;
574     int cols;
575 #endif
576
577 }
578 CvMat;
579
580
581 #define CV_IS_MAT_HDR(mat) \
582     ((mat) != NULL && \
583     (((const CvMat*)(mat))->type & CV_MAGIC_MASK) == CV_MAT_MAGIC_VAL && \
584     ((const CvMat*)(mat))->cols > 0 && ((const CvMat*)(mat))->rows > 0)
585
586 #define CV_IS_MAT(mat) \
587     (CV_IS_MAT_HDR(mat) && ((const CvMat*)(mat))->data.ptr != NULL)
588
589 #define CV_IS_MASK_ARR(mat) \
590     (((mat)->type & (CV_MAT_TYPE_MASK & ~CV_8SC1)) == 0)
591
592 #define CV_ARE_TYPES_EQ(mat1, mat2) \
593     ((((mat1)->type ^ (mat2)->type) & CV_MAT_TYPE_MASK) == 0)
594
595 #define CV_ARE_CNS_EQ(mat1, mat2) \
596     ((((mat1)->type ^ (mat2)->type) & CV_MAT_CN_MASK) == 0)
597
598 #define CV_ARE_DEPTHS_EQ(mat1, mat2) \
599     ((((mat1)->type ^ (mat2)->type) & CV_MAT_DEPTH_MASK) == 0)
600
601 #define CV_ARE_SIZES_EQ(mat1, mat2) \
602     ((mat1)->rows == (mat2)->rows && (mat1)->cols == (mat2)->cols)
603
604 #define CV_IS_MAT_CONST(mat)  \
605     (((mat)->rows|(mat)->cols) == 1)
606
607 /* Size of each channel item,
608    0x124489 = 1000 0100 0100 0010 0010 0001 0001 ~ array of sizeof(arr_type_elem) */
609 #define CV_ELEM_SIZE1(type) \
610     ((((sizeof(size_t)<<28)|0x8442211) >> CV_MAT_DEPTH(type)*4) & 15)
611
612 /* 0x3a50 = 11 10 10 01 01 00 00 ~ array of log2(sizeof(arr_type_elem)) */
613 #define CV_ELEM_SIZE(type) \
614     (CV_MAT_CN(type) << ((((sizeof(size_t)/4+1)*16384|0x3a50) >> CV_MAT_DEPTH(type)*2) & 3))
615
616 /* Inline constructor. No data is allocated internally!!!
617  * (Use together with cvCreateData, or use cvCreateMat instead to
618  * get a matrix with allocated data):
619  */
620 CV_INLINE CvMat cvMat( int rows, int cols, int type, void* data CV_DEFAULT(NULL))
621 {
622     CvMat m;
623
624     assert( (unsigned)CV_MAT_DEPTH(type) <= CV_64F );
625     type = CV_MAT_TYPE(type);
626     m.type = CV_MAT_MAGIC_VAL | CV_MAT_CONT_FLAG | type;
627     m.cols = cols;
628     m.rows = rows;
629     m.step = rows > 1 ? m.cols*CV_ELEM_SIZE(type) : 0;
630     m.data.ptr = (uchar*)data;
631     m.refcount = NULL;
632     m.hdr_refcount = 0;
633
634     return m;
635 }
636
637
638 #define CV_MAT_ELEM_PTR_FAST( mat, row, col, pix_size )  \
639     (assert( (unsigned)(row) < (unsigned)(mat).rows &&   \
640              (unsigned)(col) < (unsigned)(mat).cols ),   \
641      (mat).data.ptr + (size_t)(mat).step*(row) + (pix_size)*(col))
642
643 #define CV_MAT_ELEM_PTR( mat, row, col )                 \
644     CV_MAT_ELEM_PTR_FAST( mat, row, col, CV_ELEM_SIZE((mat).type) )
645
646 #define CV_MAT_ELEM( mat, elemtype, row, col )           \
647     (*(elemtype*)CV_MAT_ELEM_PTR_FAST( mat, row, col, sizeof(elemtype)))
648
649
650 CV_INLINE  double  cvmGet( const CvMat* mat, int row, int col )
651 {
652     int type;
653
654     type = CV_MAT_TYPE(mat->type);
655     assert( (unsigned)row < (unsigned)mat->rows &&
656             (unsigned)col < (unsigned)mat->cols );
657
658     if( type == CV_32FC1 )
659         return ((float*)(mat->data.ptr + (size_t)mat->step*row))[col];
660     else
661     {
662         assert( type == CV_64FC1 );
663         return ((double*)(mat->data.ptr + (size_t)mat->step*row))[col];
664     }
665 }
666
667
668 CV_INLINE  void  cvmSet( CvMat* mat, int row, int col, double value )
669 {
670     int type;
671     type = CV_MAT_TYPE(mat->type);
672     assert( (unsigned)row < (unsigned)mat->rows &&
673             (unsigned)col < (unsigned)mat->cols );
674
675     if( type == CV_32FC1 )
676         ((float*)(mat->data.ptr + (size_t)mat->step*row))[col] = (float)value;
677     else
678     {
679         assert( type == CV_64FC1 );
680         ((double*)(mat->data.ptr + (size_t)mat->step*row))[col] = (double)value;
681     }
682 }
683
684
685 CV_INLINE int cvCvToIplDepth( int type )
686 {
687     int depth = CV_MAT_DEPTH(type);
688     return CV_ELEM_SIZE1(depth)*8 | (depth == CV_8S || depth == CV_16S ||
689            depth == CV_32S ? IPL_DEPTH_SIGN : 0);
690 }
691
692
693 /****************************************************************************************\
694 *                       Multi-dimensional dense array (CvMatND)                          *
695 \****************************************************************************************/
696
697 #define CV_MATND_MAGIC_VAL    0x42430000
698 #define CV_TYPE_NAME_MATND    "opencv-nd-matrix"
699
700 #define CV_MAX_DIM            32
701 #define CV_MAX_DIM_HEAP       (1 << 16)
702
703 typedef struct CvMatND
704 {
705     int type;
706     int dims;
707
708     int* refcount;
709     int hdr_refcount;
710
711     union
712     {
713         uchar* ptr;
714         float* fl;
715         double* db;
716         int* i;
717         short* s;
718     } data;
719
720     struct
721     {
722         int size;
723         int step;
724     }
725     dim[CV_MAX_DIM];
726 }
727 CvMatND;
728
729 #define CV_IS_MATND_HDR(mat) \
730     ((mat) != NULL && (((const CvMatND*)(mat))->type & CV_MAGIC_MASK) == CV_MATND_MAGIC_VAL)
731
732 #define CV_IS_MATND(mat) \
733     (CV_IS_MATND_HDR(mat) && ((const CvMatND*)(mat))->data.ptr != NULL)
734
735
736 /****************************************************************************************\
737 *                      Multi-dimensional sparse array (CvSparseMat)                      *
738 \****************************************************************************************/
739
740 #define CV_SPARSE_MAT_MAGIC_VAL    0x42440000
741 #define CV_TYPE_NAME_SPARSE_MAT    "opencv-sparse-matrix"
742
743 struct CvSet;
744
745 typedef struct CvSparseMat
746 {
747     int type;
748     int dims;
749     int* refcount;
750     int hdr_refcount;
751
752     struct CvSet* heap;
753     void** hashtable;
754     int hashsize;
755     int valoffset;
756     int idxoffset;
757     int size[CV_MAX_DIM];
758 }
759 CvSparseMat;
760
761 #define CV_IS_SPARSE_MAT_HDR(mat) \
762     ((mat) != NULL && \
763     (((const CvSparseMat*)(mat))->type & CV_MAGIC_MASK) == CV_SPARSE_MAT_MAGIC_VAL)
764
765 #define CV_IS_SPARSE_MAT(mat) \
766     CV_IS_SPARSE_MAT_HDR(mat)
767
768 /**************** iteration through a sparse array *****************/
769
770 typedef struct CvSparseNode
771 {
772     unsigned hashval;
773     struct CvSparseNode* next;
774 }
775 CvSparseNode;
776
777 typedef struct CvSparseMatIterator
778 {
779     CvSparseMat* mat;
780     CvSparseNode* node;
781     int curidx;
782 }
783 CvSparseMatIterator;
784
785 #define CV_NODE_VAL(mat,node)   ((void*)((uchar*)(node) + (mat)->valoffset))
786 #define CV_NODE_IDX(mat,node)   ((int*)((uchar*)(node) + (mat)->idxoffset))
787
788 /****************************************************************************************\
789 *                                         Histogram                                      *
790 \****************************************************************************************/
791
792 typedef int CvHistType;
793
794 #define CV_HIST_MAGIC_VAL     0x42450000
795 #define CV_HIST_UNIFORM_FLAG  (1 << 10)
796
797 /* indicates whether bin ranges are set already or not */
798 #define CV_HIST_RANGES_FLAG   (1 << 11)
799
800 #define CV_HIST_ARRAY         0
801 #define CV_HIST_SPARSE        1
802 #define CV_HIST_TREE          CV_HIST_SPARSE
803
804 /* should be used as a parameter only,
805    it turns to CV_HIST_UNIFORM_FLAG of hist->type */
806 #define CV_HIST_UNIFORM       1
807
808 typedef struct CvHistogram
809 {
810     int     type;
811     CvArr*  bins;
812     float   thresh[CV_MAX_DIM][2];  /* For uniform histograms.                      */
813     float** thresh2;                /* For non-uniform histograms.                  */
814     CvMatND mat;                    /* Embedded matrix header for array histograms. */
815 }
816 CvHistogram;
817
818 #define CV_IS_HIST( hist ) \
819     ((hist) != NULL  && \
820      (((CvHistogram*)(hist))->type & CV_MAGIC_MASK) == CV_HIST_MAGIC_VAL && \
821      (hist)->bins != NULL)
822
823 #define CV_IS_UNIFORM_HIST( hist ) \
824     (((hist)->type & CV_HIST_UNIFORM_FLAG) != 0)
825
826 #define CV_IS_SPARSE_HIST( hist ) \
827     CV_IS_SPARSE_MAT((hist)->bins)
828
829 #define CV_HIST_HAS_RANGES( hist ) \
830     (((hist)->type & CV_HIST_RANGES_FLAG) != 0)
831
832 /****************************************************************************************\
833 *                      Other supplementary data type definitions                         *
834 \****************************************************************************************/
835
836 /*************************************** CvRect *****************************************/
837
838 typedef struct CvRect
839 {
840     int x;
841     int y;
842     int width;
843     int height;
844 }
845 CvRect;
846
847 CV_INLINE  CvRect  cvRect( int x, int y, int width, int height )
848 {
849     CvRect r;
850
851     r.x = x;
852     r.y = y;
853     r.width = width;
854     r.height = height;
855
856     return r;
857 }
858
859
860 CV_INLINE  IplROI  cvRectToROI( CvRect rect, int coi )
861 {
862     IplROI roi;
863     roi.xOffset = rect.x;
864     roi.yOffset = rect.y;
865     roi.width = rect.width;
866     roi.height = rect.height;
867     roi.coi = coi;
868
869     return roi;
870 }
871
872
873 CV_INLINE  CvRect  cvROIToRect( IplROI roi )
874 {
875     return cvRect( roi.xOffset, roi.yOffset, roi.width, roi.height );
876 }
877
878 /*********************************** CvTermCriteria *************************************/
879
880 #define CV_TERMCRIT_ITER    1
881 #define CV_TERMCRIT_NUMBER  CV_TERMCRIT_ITER
882 #define CV_TERMCRIT_EPS     2
883
884 typedef struct CvTermCriteria
885 {
886     int    type;  /* may be combination of
887                      CV_TERMCRIT_ITER
888                      CV_TERMCRIT_EPS */
889     int    max_iter;
890     double epsilon;
891 }
892 CvTermCriteria;
893
894 CV_INLINE  CvTermCriteria  cvTermCriteria( int type, int max_iter, double epsilon )
895 {
896     CvTermCriteria t;
897
898     t.type = type;
899     t.max_iter = max_iter;
900     t.epsilon = (float)epsilon;
901
902     return t;
903 }
904
905
906 /******************************* CvPoint and variants ***********************************/
907
908 typedef struct CvPoint
909 {
910     int x;
911     int y;
912 }
913 CvPoint;
914
915
916 CV_INLINE  CvPoint  cvPoint( int x, int y )
917 {
918     CvPoint p;
919
920     p.x = x;
921     p.y = y;
922
923     return p;
924 }
925
926
927 typedef struct CvPoint2D32f
928 {
929     float x;
930     float y;
931 }
932 CvPoint2D32f;
933
934
935 CV_INLINE  CvPoint2D32f  cvPoint2D32f( double x, double y )
936 {
937     CvPoint2D32f p;
938
939     p.x = (float)x;
940     p.y = (float)y;
941
942     return p;
943 }
944
945
946 CV_INLINE  CvPoint2D32f  cvPointTo32f( CvPoint point )
947 {
948     return cvPoint2D32f( (float)point.x, (float)point.y );
949 }
950
951
952 CV_INLINE  CvPoint  cvPointFrom32f( CvPoint2D32f point )
953 {
954     CvPoint ipt;
955     ipt.x = cvRound(point.x);
956     ipt.y = cvRound(point.y);
957
958     return ipt;
959 }
960
961
962 typedef struct CvPoint3D32f
963 {
964     float x;
965     float y;
966     float z;
967 }
968 CvPoint3D32f;
969
970
971 CV_INLINE  CvPoint3D32f  cvPoint3D32f( double x, double y, double z )
972 {
973     CvPoint3D32f p;
974
975     p.x = (float)x;
976     p.y = (float)y;
977     p.z = (float)z;
978
979     return p;
980 }
981
982
983 typedef struct CvPoint2D64f
984 {
985     double x;
986     double y;
987 }
988 CvPoint2D64f;
989
990
991 CV_INLINE  CvPoint2D64f  cvPoint2D64f( double x, double y )
992 {
993     CvPoint2D64f p;
994
995     p.x = x;
996     p.y = y;
997
998     return p;
999 }
1000
1001
1002 typedef struct CvPoint3D64f
1003 {
1004     double x;
1005     double y;
1006     double z;
1007 }
1008 CvPoint3D64f;
1009
1010
1011 CV_INLINE  CvPoint3D64f  cvPoint3D64f( double x, double y, double z )
1012 {
1013     CvPoint3D64f p;
1014
1015     p.x = x;
1016     p.y = y;
1017     p.z = z;
1018
1019     return p;
1020 }
1021
1022
1023 /******************************** CvSize's & CvBox **************************************/
1024
1025 typedef struct
1026 {
1027     int width;
1028     int height;
1029 }
1030 CvSize;
1031
1032 CV_INLINE  CvSize  cvSize( int width, int height )
1033 {
1034     CvSize s;
1035
1036     s.width = width;
1037     s.height = height;
1038
1039     return s;
1040 }
1041
1042 typedef struct CvSize2D32f
1043 {
1044     float width;
1045     float height;
1046 }
1047 CvSize2D32f;
1048
1049
1050 CV_INLINE  CvSize2D32f  cvSize2D32f( double width, double height )
1051 {
1052     CvSize2D32f s;
1053
1054     s.width = (float)width;
1055     s.height = (float)height;
1056
1057     return s;
1058 }
1059
1060 typedef struct CvBox2D
1061 {
1062     CvPoint2D32f center;  /* Center of the box.                          */
1063     CvSize2D32f  size;    /* Box width and length.                       */
1064     float angle;          /* Angle between the horizontal axis           */
1065                           /* and the first side (i.e. length) in degrees */
1066 }
1067 CvBox2D;
1068
1069
1070 /* Line iterator state: */
1071 typedef struct CvLineIterator
1072 {
1073     /* Pointer to the current point: */
1074     uchar* ptr;
1075
1076     /* Bresenham algorithm state: */
1077     int  err;
1078     int  plus_delta;
1079     int  minus_delta;
1080     int  plus_step;
1081     int  minus_step;
1082 }
1083 CvLineIterator;
1084
1085
1086
1087 /************************************* CvSlice ******************************************/
1088
1089 typedef struct CvSlice
1090 {
1091     int  start_index, end_index;
1092 }
1093 CvSlice;
1094
1095 CV_INLINE  CvSlice  cvSlice( int start, int end )
1096 {
1097     CvSlice slice;
1098     slice.start_index = start;
1099     slice.end_index = end;
1100
1101     return slice;
1102 }
1103
1104 #define CV_WHOLE_SEQ_END_INDEX 0x3fffffff
1105 #define CV_WHOLE_SEQ  cvSlice(0, CV_WHOLE_SEQ_END_INDEX)
1106
1107
1108 /************************************* CvScalar *****************************************/
1109
1110 typedef struct CvScalar
1111 {
1112     double val[4];
1113 }
1114 CvScalar;
1115
1116 CV_INLINE  CvScalar  cvScalar( double val0, double val1 CV_DEFAULT(0),
1117                                double val2 CV_DEFAULT(0), double val3 CV_DEFAULT(0))
1118 {
1119     CvScalar scalar;
1120     scalar.val[0] = val0; scalar.val[1] = val1;
1121     scalar.val[2] = val2; scalar.val[3] = val3;
1122     return scalar;
1123 }
1124
1125
1126 CV_INLINE  CvScalar  cvRealScalar( double val0 )
1127 {
1128     CvScalar scalar;
1129     scalar.val[0] = val0;
1130     scalar.val[1] = scalar.val[2] = scalar.val[3] = 0;
1131     return scalar;
1132 }
1133
1134 CV_INLINE  CvScalar  cvScalarAll( double val0123 )
1135 {
1136     CvScalar scalar;
1137     scalar.val[0] = val0123;
1138     scalar.val[1] = val0123;
1139     scalar.val[2] = val0123;
1140     scalar.val[3] = val0123;
1141     return scalar;
1142 }
1143
1144 /****************************************************************************************\
1145 *                                   Dynamic Data structures                              *
1146 \****************************************************************************************/
1147
1148 /******************************** Memory storage ****************************************/
1149
1150 typedef struct CvMemBlock
1151 {
1152     struct CvMemBlock*  prev;
1153     struct CvMemBlock*  next;
1154 }
1155 CvMemBlock;
1156
1157 #define CV_STORAGE_MAGIC_VAL    0x42890000
1158
1159 typedef struct CvMemStorage
1160 {
1161     int signature;
1162     CvMemBlock* bottom;           /* First allocated block.                   */
1163     CvMemBlock* top;              /* Current memory block - top of the stack. */
1164     struct  CvMemStorage* parent; /* We get new blocks from parent as needed. */
1165     int block_size;               /* Block size.                              */
1166     int free_space;               /* Remaining free space in current block.   */
1167 }
1168 CvMemStorage;
1169
1170 #define CV_IS_STORAGE(storage)  \
1171     ((storage) != NULL &&       \
1172     (((CvMemStorage*)(storage))->signature & CV_MAGIC_MASK) == CV_STORAGE_MAGIC_VAL)
1173
1174
1175 typedef struct CvMemStoragePos
1176 {
1177     CvMemBlock* top;
1178     int free_space;
1179 }
1180 CvMemStoragePos;
1181
1182
1183 /*********************************** Sequence *******************************************/
1184
1185 typedef struct CvSeqBlock
1186 {
1187     struct CvSeqBlock*  prev; /* Previous sequence block.                   */
1188     struct CvSeqBlock*  next; /* Next sequence block.                       */
1189   int    start_index;         /* Index of the first element in the block +  */
1190                               /* sequence->first->start_index.              */
1191     int    count;             /* Number of elements in the block.           */
1192     schar* data;              /* Pointer to the first element of the block. */
1193 }
1194 CvSeqBlock;
1195
1196
1197 #define CV_TREE_NODE_FIELDS(node_type)                               \
1198     int       flags;             /* Miscellaneous flags.     */      \
1199     int       header_size;       /* Size of sequence header. */      \
1200     struct    node_type* h_prev; /* Previous sequence.       */      \
1201     struct    node_type* h_next; /* Next sequence.           */      \
1202     struct    node_type* v_prev; /* 2nd previous sequence.   */      \
1203     struct    node_type* v_next  /* 2nd next sequence.       */
1204
1205 /*
1206    Read/Write sequence.
1207    Elements can be dynamically inserted to or deleted from the sequence.
1208 */
1209 #define CV_SEQUENCE_FIELDS()                                              \
1210     CV_TREE_NODE_FIELDS(CvSeq);                                           \
1211     int       total;          /* Total number of elements.            */  \
1212     int       elem_size;      /* Size of sequence element in bytes.   */  \
1213     schar*    block_max;      /* Maximal bound of the last block.     */  \
1214     schar*    ptr;            /* Current write pointer.               */  \
1215     int       delta_elems;    /* Grow seq this many at a time.        */  \
1216     CvMemStorage* storage;    /* Where the seq is stored.             */  \
1217     CvSeqBlock* free_blocks;  /* Free blocks list.                    */  \
1218     CvSeqBlock* first;        /* Pointer to the first sequence block. */
1219
1220 typedef struct CvSeq
1221 {
1222     CV_SEQUENCE_FIELDS()
1223 }
1224 CvSeq;
1225
1226 #define CV_TYPE_NAME_SEQ             "opencv-sequence"
1227 #define CV_TYPE_NAME_SEQ_TREE        "opencv-sequence-tree"
1228
1229 /*************************************** Set ********************************************/
1230 /*
1231   Set.
1232   Order is not preserved. There can be gaps between sequence elements.
1233   After the element has been inserted it stays in the same place all the time.
1234   The MSB(most-significant or sign bit) of the first field (flags) is 0 iff the element exists.
1235 */
1236 #define CV_SET_ELEM_FIELDS(elem_type)   \
1237     int  flags;                         \
1238     struct elem_type* next_free;
1239
1240 typedef struct CvSetElem
1241 {
1242     CV_SET_ELEM_FIELDS(CvSetElem)
1243 }
1244 CvSetElem;
1245
1246 #define CV_SET_FIELDS()      \
1247     CV_SEQUENCE_FIELDS()     \
1248     CvSetElem* free_elems;   \
1249     int active_count;
1250
1251 typedef struct CvSet
1252 {
1253     CV_SET_FIELDS()
1254 }
1255 CvSet;
1256
1257
1258 #define CV_SET_ELEM_IDX_MASK   ((1 << 26) - 1)
1259 #define CV_SET_ELEM_FREE_FLAG  (1 << (sizeof(int)*8-1))
1260
1261 /* Checks whether the element pointed by ptr belongs to a set or not */
1262 #define CV_IS_SET_ELEM( ptr )  (((CvSetElem*)(ptr))->flags >= 0)
1263
1264 /************************************* Graph ********************************************/
1265
1266 /*
1267   We represent a graph as a set of vertices.
1268   Vertices contain their adjacency lists (more exactly, pointers to first incoming or
1269   outcoming edge (or 0 if isolated vertex)). Edges are stored in another set.
1270   There is a singly-linked list of incoming/outcoming edges for each vertex.
1271
1272   Each edge consists of
1273
1274      o   Two pointers to the starting and ending vertices
1275          (vtx[0] and vtx[1] respectively).
1276
1277          A graph may be oriented or not. In the latter case, edges between
1278          vertex i to vertex j are not distinguished during search operations.
1279
1280      o   Two pointers to next edges for the starting and ending vertices, where
1281          next[0] points to the next edge in the vtx[0] adjacency list and
1282          next[1] points to the next edge in the vtx[1] adjacency list.
1283 */
1284 #define CV_GRAPH_EDGE_FIELDS()      \
1285     int flags;                      \
1286     float weight;                   \
1287     struct CvGraphEdge* next[2];    \
1288     struct CvGraphVtx* vtx[2];
1289
1290
1291 #define CV_GRAPH_VERTEX_FIELDS()    \
1292     int flags;                      \
1293     struct CvGraphEdge* first;
1294
1295
1296 typedef struct CvGraphEdge
1297 {
1298     CV_GRAPH_EDGE_FIELDS()
1299 }
1300 CvGraphEdge;
1301
1302 typedef struct CvGraphVtx
1303 {
1304     CV_GRAPH_VERTEX_FIELDS()
1305 }
1306 CvGraphVtx;
1307
1308 typedef struct CvGraphVtx2D
1309 {
1310     CV_GRAPH_VERTEX_FIELDS()
1311     CvPoint2D32f* ptr;
1312 }
1313 CvGraphVtx2D;
1314
1315 /*
1316    Graph is "derived" from the set (this is set a of vertices)
1317    and includes another set (edges)
1318 */
1319 #define  CV_GRAPH_FIELDS()   \
1320     CV_SET_FIELDS()          \
1321     CvSet* edges;
1322
1323 typedef struct CvGraph
1324 {
1325     CV_GRAPH_FIELDS()
1326 }
1327 CvGraph;
1328
1329 #define CV_TYPE_NAME_GRAPH "opencv-graph"
1330
1331 /*********************************** Chain/Countour *************************************/
1332
1333 typedef struct CvChain
1334 {
1335     CV_SEQUENCE_FIELDS()
1336     CvPoint  origin;
1337 }
1338 CvChain;
1339
1340 #define CV_CONTOUR_FIELDS()  \
1341     CV_SEQUENCE_FIELDS()     \
1342     CvRect rect;             \
1343     int color;               \
1344     int reserved[3];
1345
1346 typedef struct CvContour
1347 {
1348     CV_CONTOUR_FIELDS()
1349 }
1350 CvContour;
1351
1352 typedef CvContour CvPoint2DSeq;
1353
1354 /****************************************************************************************\
1355 *                                    Sequence types                                      *
1356 \****************************************************************************************/
1357
1358 #define CV_SEQ_MAGIC_VAL             0x42990000
1359
1360 #define CV_IS_SEQ(seq) \
1361     ((seq) != NULL && (((CvSeq*)(seq))->flags & CV_MAGIC_MASK) == CV_SEQ_MAGIC_VAL)
1362
1363 #define CV_SET_MAGIC_VAL             0x42980000
1364 #define CV_IS_SET(set) \
1365     ((set) != NULL && (((CvSeq*)(set))->flags & CV_MAGIC_MASK) == CV_SET_MAGIC_VAL)
1366
1367 #define CV_SEQ_ELTYPE_BITS           9
1368 #define CV_SEQ_ELTYPE_MASK           ((1 << CV_SEQ_ELTYPE_BITS) - 1)
1369
1370 #define CV_SEQ_ELTYPE_POINT          CV_32SC2  /* (x,y) */
1371 #define CV_SEQ_ELTYPE_CODE           CV_8UC1   /* freeman code: 0..7 */
1372 #define CV_SEQ_ELTYPE_GENERIC        0
1373 #define CV_SEQ_ELTYPE_PTR            CV_USRTYPE1
1374 #define CV_SEQ_ELTYPE_PPOINT         CV_SEQ_ELTYPE_PTR  /* &(x,y) */
1375 #define CV_SEQ_ELTYPE_INDEX          CV_32SC1  /* #(x,y) */
1376 #define CV_SEQ_ELTYPE_GRAPH_EDGE     0  /* &next_o, &next_d, &vtx_o, &vtx_d */
1377 #define CV_SEQ_ELTYPE_GRAPH_VERTEX   0  /* first_edge, &(x,y) */
1378 #define CV_SEQ_ELTYPE_TRIAN_ATR      0  /* vertex of the binary tree   */
1379 #define CV_SEQ_ELTYPE_CONNECTED_COMP 0  /* connected component  */
1380 #define CV_SEQ_ELTYPE_POINT3D        CV_32FC3  /* (x,y,z)  */
1381
1382 #define CV_SEQ_KIND_BITS        3
1383 #define CV_SEQ_KIND_MASK        (((1 << CV_SEQ_KIND_BITS) - 1)<<CV_SEQ_ELTYPE_BITS)
1384
1385 /* types of sequences */
1386 #define CV_SEQ_KIND_GENERIC     (0 << CV_SEQ_ELTYPE_BITS)
1387 #define CV_SEQ_KIND_CURVE       (1 << CV_SEQ_ELTYPE_BITS)
1388 #define CV_SEQ_KIND_BIN_TREE    (2 << CV_SEQ_ELTYPE_BITS)
1389
1390 /* types of sparse sequences (sets) */
1391 #define CV_SEQ_KIND_GRAPH       (3 << CV_SEQ_ELTYPE_BITS)
1392 #define CV_SEQ_KIND_SUBDIV2D    (4 << CV_SEQ_ELTYPE_BITS)
1393
1394 #define CV_SEQ_FLAG_SHIFT       (CV_SEQ_KIND_BITS + CV_SEQ_ELTYPE_BITS)
1395
1396 /* flags for curves */
1397 #define CV_SEQ_FLAG_CLOSED     (1 << CV_SEQ_FLAG_SHIFT)
1398 #define CV_SEQ_FLAG_SIMPLE     (2 << CV_SEQ_FLAG_SHIFT)
1399 #define CV_SEQ_FLAG_CONVEX     (4 << CV_SEQ_FLAG_SHIFT)
1400 #define CV_SEQ_FLAG_HOLE       (8 << CV_SEQ_FLAG_SHIFT)
1401
1402 /* flags for graphs */
1403 #define CV_GRAPH_FLAG_ORIENTED (1 << CV_SEQ_FLAG_SHIFT)
1404
1405 #define CV_GRAPH               CV_SEQ_KIND_GRAPH
1406 #define CV_ORIENTED_GRAPH      (CV_SEQ_KIND_GRAPH|CV_GRAPH_FLAG_ORIENTED)
1407
1408 /* point sets */
1409 #define CV_SEQ_POINT_SET       (CV_SEQ_KIND_GENERIC| CV_SEQ_ELTYPE_POINT)
1410 #define CV_SEQ_POINT3D_SET     (CV_SEQ_KIND_GENERIC| CV_SEQ_ELTYPE_POINT3D)
1411 #define CV_SEQ_POLYLINE        (CV_SEQ_KIND_CURVE  | CV_SEQ_ELTYPE_POINT)
1412 #define CV_SEQ_POLYGON         (CV_SEQ_FLAG_CLOSED | CV_SEQ_POLYLINE )
1413 #define CV_SEQ_CONTOUR         CV_SEQ_POLYGON
1414 #define CV_SEQ_SIMPLE_POLYGON  (CV_SEQ_FLAG_SIMPLE | CV_SEQ_POLYGON  )
1415
1416 /* chain-coded curves */
1417 #define CV_SEQ_CHAIN           (CV_SEQ_KIND_CURVE  | CV_SEQ_ELTYPE_CODE)
1418 #define CV_SEQ_CHAIN_CONTOUR   (CV_SEQ_FLAG_CLOSED | CV_SEQ_CHAIN)
1419
1420 /* binary tree for the contour */
1421 #define CV_SEQ_POLYGON_TREE    (CV_SEQ_KIND_BIN_TREE  | CV_SEQ_ELTYPE_TRIAN_ATR)
1422
1423 /* sequence of the connected components */
1424 #define CV_SEQ_CONNECTED_COMP  (CV_SEQ_KIND_GENERIC  | CV_SEQ_ELTYPE_CONNECTED_COMP)
1425
1426 /* sequence of the integer numbers */
1427 #define CV_SEQ_INDEX           (CV_SEQ_KIND_GENERIC  | CV_SEQ_ELTYPE_INDEX)
1428
1429 #define CV_SEQ_ELTYPE( seq )   ((seq)->flags & CV_SEQ_ELTYPE_MASK)
1430 #define CV_SEQ_KIND( seq )     ((seq)->flags & CV_SEQ_KIND_MASK )
1431
1432 /* flag checking */
1433 #define CV_IS_SEQ_INDEX( seq )      ((CV_SEQ_ELTYPE(seq) == CV_SEQ_ELTYPE_INDEX) && \
1434                                      (CV_SEQ_KIND(seq) == CV_SEQ_KIND_GENERIC))
1435
1436 #define CV_IS_SEQ_CURVE( seq )      (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE)
1437 #define CV_IS_SEQ_CLOSED( seq )     (((seq)->flags & CV_SEQ_FLAG_CLOSED) != 0)
1438 #define CV_IS_SEQ_CONVEX( seq )     (((seq)->flags & CV_SEQ_FLAG_CONVEX) != 0)
1439 #define CV_IS_SEQ_HOLE( seq )       (((seq)->flags & CV_SEQ_FLAG_HOLE) != 0)
1440 #define CV_IS_SEQ_SIMPLE( seq )     ((((seq)->flags & CV_SEQ_FLAG_SIMPLE) != 0) || \
1441                                     CV_IS_SEQ_CONVEX(seq))
1442
1443 /* type checking macros */
1444 #define CV_IS_SEQ_POINT_SET( seq ) \
1445     ((CV_SEQ_ELTYPE(seq) == CV_32SC2 || CV_SEQ_ELTYPE(seq) == CV_32FC2))
1446
1447 #define CV_IS_SEQ_POINT_SUBSET( seq ) \
1448     (CV_IS_SEQ_INDEX( seq ) || CV_SEQ_ELTYPE(seq) == CV_SEQ_ELTYPE_PPOINT)
1449
1450 #define CV_IS_SEQ_POLYLINE( seq )   \
1451     (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE && CV_IS_SEQ_POINT_SET(seq))
1452
1453 #define CV_IS_SEQ_POLYGON( seq )   \
1454     (CV_IS_SEQ_POLYLINE(seq) && CV_IS_SEQ_CLOSED(seq))
1455
1456 #define CV_IS_SEQ_CHAIN( seq )   \
1457     (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE && (seq)->elem_size == 1)
1458
1459 #define CV_IS_SEQ_CONTOUR( seq )   \
1460     (CV_IS_SEQ_CLOSED(seq) && (CV_IS_SEQ_POLYLINE(seq) || CV_IS_SEQ_CHAIN(seq)))
1461
1462 #define CV_IS_SEQ_CHAIN_CONTOUR( seq ) \
1463     (CV_IS_SEQ_CHAIN( seq ) && CV_IS_SEQ_CLOSED( seq ))
1464
1465 #define CV_IS_SEQ_POLYGON_TREE( seq ) \
1466     (CV_SEQ_ELTYPE (seq) ==  CV_SEQ_ELTYPE_TRIAN_ATR &&    \
1467     CV_SEQ_KIND( seq ) ==  CV_SEQ_KIND_BIN_TREE )
1468
1469 #define CV_IS_GRAPH( seq )    \
1470     (CV_IS_SET(seq) && CV_SEQ_KIND((CvSet*)(seq)) == CV_SEQ_KIND_GRAPH)
1471
1472 #define CV_IS_GRAPH_ORIENTED( seq )   \
1473     (((seq)->flags & CV_GRAPH_FLAG_ORIENTED) != 0)
1474
1475 #define CV_IS_SUBDIV2D( seq )  \
1476     (CV_IS_SET(seq) && CV_SEQ_KIND((CvSet*)(seq)) == CV_SEQ_KIND_SUBDIV2D)
1477
1478 /****************************************************************************************/
1479 /*                            Sequence writer & reader                                  */
1480 /****************************************************************************************/
1481
1482 #define CV_SEQ_WRITER_FIELDS()                                     \
1483     int          header_size;                                      \
1484     CvSeq*       seq;        /* the sequence written */            \
1485     CvSeqBlock*  block;      /* current block */                   \
1486     schar*       ptr;        /* pointer to free space */           \
1487     schar*       block_min;  /* pointer to the beginning of block*/\
1488     schar*       block_max;  /* pointer to the end of block */
1489
1490 typedef struct CvSeqWriter
1491 {
1492     CV_SEQ_WRITER_FIELDS()
1493 }
1494 CvSeqWriter;
1495
1496
1497 #define CV_SEQ_READER_FIELDS()                                      \
1498     int          header_size;                                       \
1499     CvSeq*       seq;        /* sequence, beign read */             \
1500     CvSeqBlock*  block;      /* current block */                    \
1501     schar*       ptr;        /* pointer to element be read next */  \
1502     schar*       block_min;  /* pointer to the beginning of block */\
1503     schar*       block_max;  /* pointer to the end of block */      \
1504     int          delta_index;/* = seq->first->start_index   */      \
1505     schar*       prev_elem;  /* pointer to previous element */
1506
1507
1508 typedef struct CvSeqReader
1509 {
1510     CV_SEQ_READER_FIELDS()
1511 }
1512 CvSeqReader;
1513
1514 /****************************************************************************************/
1515 /*                                Operations on sequences                               */
1516 /****************************************************************************************/
1517
1518 #define  CV_SEQ_ELEM( seq, elem_type, index )                    \
1519 /* assert gives some guarantee that <seq> parameter is valid */  \
1520 (   assert(sizeof((seq)->first[0]) == sizeof(CvSeqBlock) &&      \
1521     (seq)->elem_size == sizeof(elem_type)),                      \
1522     (elem_type*)((seq)->first && (unsigned)index <               \
1523     (unsigned)((seq)->first->count) ?                            \
1524     (seq)->first->data + (index) * sizeof(elem_type) :           \
1525     cvGetSeqElem( (CvSeq*)(seq), (index) )))
1526 #define CV_GET_SEQ_ELEM( elem_type, seq, index ) CV_SEQ_ELEM( (seq), elem_type, (index) )
1527
1528 /* Add element to sequence: */
1529 #define CV_WRITE_SEQ_ELEM_VAR( elem_ptr, writer )     \
1530 {                                                     \
1531     if( (writer).ptr >= (writer).block_max )          \
1532     {                                                 \
1533         cvCreateSeqBlock( &writer);                   \
1534     }                                                 \
1535     memcpy((writer).ptr, elem_ptr, (writer).seq->elem_size);\
1536     (writer).ptr += (writer).seq->elem_size;          \
1537 }
1538
1539 #define CV_WRITE_SEQ_ELEM( elem, writer )             \
1540 {                                                     \
1541     assert( (writer).seq->elem_size == sizeof(elem)); \
1542     if( (writer).ptr >= (writer).block_max )          \
1543     {                                                 \
1544         cvCreateSeqBlock( &writer);                   \
1545     }                                                 \
1546     assert( (writer).ptr <= (writer).block_max - sizeof(elem));\
1547     memcpy((writer).ptr, &(elem), sizeof(elem));      \
1548     (writer).ptr += sizeof(elem);                     \
1549 }
1550
1551
1552 /* Move reader position forward: */
1553 #define CV_NEXT_SEQ_ELEM( elem_size, reader )                 \
1554 {                                                             \
1555     if( ((reader).ptr += (elem_size)) >= (reader).block_max ) \
1556     {                                                         \
1557         cvChangeSeqBlock( &(reader), 1 );                     \
1558     }                                                         \
1559 }
1560
1561
1562 /* Move reader position backward: */
1563 #define CV_PREV_SEQ_ELEM( elem_size, reader )                \
1564 {                                                            \
1565     if( ((reader).ptr -= (elem_size)) < (reader).block_min ) \
1566     {                                                        \
1567         cvChangeSeqBlock( &(reader), -1 );                   \
1568     }                                                        \
1569 }
1570
1571 /* Read element and move read position forward: */
1572 #define CV_READ_SEQ_ELEM( elem, reader )                       \
1573 {                                                              \
1574     assert( (reader).seq->elem_size == sizeof(elem));          \
1575     memcpy( &(elem), (reader).ptr, sizeof((elem)));            \
1576     CV_NEXT_SEQ_ELEM( sizeof(elem), reader )                   \
1577 }
1578
1579 /* Read element and move read position backward: */
1580 #define CV_REV_READ_SEQ_ELEM( elem, reader )                     \
1581 {                                                                \
1582     assert( (reader).seq->elem_size == sizeof(elem));            \
1583     memcpy(&(elem), (reader).ptr, sizeof((elem)));               \
1584     CV_PREV_SEQ_ELEM( sizeof(elem), reader )                     \
1585 }
1586
1587
1588 #define CV_READ_CHAIN_POINT( _pt, reader )                              \
1589 {                                                                       \
1590     (_pt) = (reader).pt;                                                \
1591     if( (reader).ptr )                                                  \
1592     {                                                                   \
1593         CV_READ_SEQ_ELEM( (reader).code, (reader));                     \
1594         assert( ((reader).code & ~7) == 0 );                            \
1595         (reader).pt.x += (reader).deltas[(int)(reader).code][0];        \
1596         (reader).pt.y += (reader).deltas[(int)(reader).code][1];        \
1597     }                                                                   \
1598 }
1599
1600 #define CV_CURRENT_POINT( reader )  (*((CvPoint*)((reader).ptr)))
1601 #define CV_PREV_POINT( reader )     (*((CvPoint*)((reader).prev_elem)))
1602
1603 #define CV_READ_EDGE( pt1, pt2, reader )               \
1604 {                                                      \
1605     assert( sizeof(pt1) == sizeof(CvPoint) &&          \
1606             sizeof(pt2) == sizeof(CvPoint) &&          \
1607             reader.seq->elem_size == sizeof(CvPoint)); \
1608     (pt1) = CV_PREV_POINT( reader );                   \
1609     (pt2) = CV_CURRENT_POINT( reader );                \
1610     (reader).prev_elem = (reader).ptr;                 \
1611     CV_NEXT_SEQ_ELEM( sizeof(CvPoint), (reader));      \
1612 }
1613
1614 /************ Graph macros ************/
1615
1616 /* Return next graph edge for given vertex: */
1617 #define  CV_NEXT_GRAPH_EDGE( edge, vertex )                              \
1618      (assert((edge)->vtx[0] == (vertex) || (edge)->vtx[1] == (vertex)),  \
1619       (edge)->next[(edge)->vtx[1] == (vertex)])
1620
1621
1622
1623 /****************************************************************************************\
1624 *             Data structures for persistence (a.k.a serialization) functionality        *
1625 \****************************************************************************************/
1626
1627 /* "black box" file storage */
1628 typedef struct CvFileStorage CvFileStorage;
1629
1630 /* Storage flags: */
1631 #define CV_STORAGE_READ          0
1632 #define CV_STORAGE_WRITE         1
1633 #define CV_STORAGE_WRITE_TEXT    CV_STORAGE_WRITE
1634 #define CV_STORAGE_WRITE_BINARY  CV_STORAGE_WRITE
1635 #define CV_STORAGE_APPEND        2
1636
1637 /* List of attributes: */
1638 typedef struct CvAttrList
1639 {
1640     const char** attr;         /* NULL-terminated array of (attribute_name,attribute_value) pairs. */
1641     struct CvAttrList* next;   /* Pointer to next chunk of the attributes list.                    */
1642 }
1643 CvAttrList;
1644
1645 CV_INLINE CvAttrList cvAttrList( const char** attr CV_DEFAULT(NULL),
1646                                  CvAttrList* next CV_DEFAULT(NULL) )
1647 {
1648     CvAttrList l;
1649     l.attr = attr;
1650     l.next = next;
1651
1652     return l;
1653 }
1654
1655 struct CvTypeInfo;
1656
1657 #define CV_NODE_NONE        0
1658 #define CV_NODE_INT         1
1659 #define CV_NODE_INTEGER     CV_NODE_INT
1660 #define CV_NODE_REAL        2
1661 #define CV_NODE_FLOAT       CV_NODE_REAL
1662 #define CV_NODE_STR         3
1663 #define CV_NODE_STRING      CV_NODE_STR
1664 #define CV_NODE_REF         4 /* not used */
1665 #define CV_NODE_SEQ         5
1666 #define CV_NODE_MAP         6
1667 #define CV_NODE_TYPE_MASK   7
1668
1669 #define CV_NODE_TYPE(flags)  ((flags) & CV_NODE_TYPE_MASK)
1670
1671 /* file node flags */
1672 #define CV_NODE_FLOW        8 /* Used only for writing structures in YAML format. */
1673 #define CV_NODE_USER        16
1674 #define CV_NODE_EMPTY       32
1675 #define CV_NODE_NAMED       64
1676
1677 #define CV_NODE_IS_INT(flags)        (CV_NODE_TYPE(flags) == CV_NODE_INT)
1678 #define CV_NODE_IS_REAL(flags)       (CV_NODE_TYPE(flags) == CV_NODE_REAL)
1679 #define CV_NODE_IS_STRING(flags)     (CV_NODE_TYPE(flags) == CV_NODE_STRING)
1680 #define CV_NODE_IS_SEQ(flags)        (CV_NODE_TYPE(flags) == CV_NODE_SEQ)
1681 #define CV_NODE_IS_MAP(flags)        (CV_NODE_TYPE(flags) == CV_NODE_MAP)
1682 #define CV_NODE_IS_COLLECTION(flags) (CV_NODE_TYPE(flags) >= CV_NODE_SEQ)
1683 #define CV_NODE_IS_FLOW(flags)       (((flags) & CV_NODE_FLOW) != 0)
1684 #define CV_NODE_IS_EMPTY(flags)      (((flags) & CV_NODE_EMPTY) != 0)
1685 #define CV_NODE_IS_USER(flags)       (((flags) & CV_NODE_USER) != 0)
1686 #define CV_NODE_HAS_NAME(flags)      (((flags) & CV_NODE_NAMED) != 0)
1687
1688 #define CV_NODE_SEQ_SIMPLE 256
1689 #define CV_NODE_SEQ_IS_SIMPLE(seq) (((seq)->flags & CV_NODE_SEQ_SIMPLE) != 0)
1690
1691 typedef struct CvString
1692 {
1693     int len;
1694     char* ptr;
1695 }
1696 CvString;
1697
1698 /* All the keys (names) of elements in the readed file storage
1699    are stored in the hash to speed up the lookup operations: */
1700 typedef struct CvStringHashNode
1701 {
1702     unsigned hashval;
1703     CvString str;
1704     struct CvStringHashNode* next;
1705 }
1706 CvStringHashNode;
1707
1708 typedef struct CvGenericHash CvFileNodeHash;
1709
1710 /* Basic element of the file storage - scalar or collection: */
1711 typedef struct CvFileNode
1712 {
1713     int tag;
1714     struct CvTypeInfo* info; /* type information
1715             (only for user-defined object, for others it is 0) */
1716     union
1717     {
1718         double f; /* scalar floating-point number */
1719         int i;    /* scalar integer number */
1720         CvString str; /* text string */
1721         CvSeq* seq; /* sequence (ordered collection of file nodes) */
1722         CvFileNodeHash* map; /* map (collection of named file nodes) */
1723     } data;
1724 }
1725 CvFileNode;
1726
1727 #ifdef __cplusplus
1728 extern "C" {
1729 #endif
1730 typedef int (CV_CDECL *CvIsInstanceFunc)( const void* struct_ptr );
1731 typedef void (CV_CDECL *CvReleaseFunc)( void** struct_dblptr );
1732 typedef void* (CV_CDECL *CvReadFunc)( CvFileStorage* storage, CvFileNode* node );
1733 typedef void (CV_CDECL *CvWriteFunc)( CvFileStorage* storage, const char* name,
1734                                       const void* struct_ptr, CvAttrList attributes );
1735 typedef void* (CV_CDECL *CvCloneFunc)( const void* struct_ptr );
1736 #ifdef __cplusplus
1737 }
1738 #endif
1739
1740 typedef struct CvTypeInfo
1741 {
1742     int flags;
1743     int header_size;
1744     struct CvTypeInfo* prev;
1745     struct CvTypeInfo* next;
1746     const char* type_name;
1747     CvIsInstanceFunc is_instance;
1748     CvReleaseFunc release;
1749     CvReadFunc read;
1750     CvWriteFunc write;
1751     CvCloneFunc clone;
1752 }
1753 CvTypeInfo;
1754
1755
1756 /**** System data types ******/
1757
1758 typedef struct CvPluginFuncInfo
1759 {
1760     void** func_addr;
1761     void* default_func_addr;
1762     const char* func_names;
1763     int search_modules;
1764     int loaded_from;
1765 }
1766 CvPluginFuncInfo;
1767
1768 typedef struct CvModuleInfo
1769 {
1770     struct CvModuleInfo* next;
1771     const char* name;
1772     const char* version;
1773     CvPluginFuncInfo* func_tab;
1774 }
1775 CvModuleInfo;
1776
1777 #endif /*_CXCORE_TYPES_H_*/
1778
1779 /* End of file. */