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