Fixed some implicitly type conversions between vector and scalar data type.

There are some mixed implicitly/explicitly type conversion between
scalar and vector. Although the spec allows those conversion, I prefer
to make them consistent and use explicitly all the cases.

Signed-off-by: Zhigang Gong <e04a7b9b70b1e4c6318cf117dcd1a9056e14b97a@intel.com>

/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Institute Of Software Chinese Academy Of Science, all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Zhang Ying, zhangying913@gmail.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors as is and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#ifdef DOUBLE_SUPPORT
#ifdef cl_amd_fp64
#pragma OPENCL EXTENSION cl_amd_fp64:enable
#elif defined (cl_khr_fp64)
#pragma OPENCL EXTENSION cl_khr_fp64:enable
#endif
#endif

#ifdef VECTORIZED

__kernel void threshold(__global const T * restrict src, int src_offset, int src_step,
                        __global T * dst, int dst_offset, int dst_step,
                        T thresh, T max_val, int max_index, int rows, int cols)
{
    int gx = get_global_id(0);
    int gy = get_global_id(1);

    if (gx < cols && gy < rows)
    {
        gx *= VECSIZE;
        int src_index = mad24(gy, src_step, src_offset + gx);
        int dst_index = mad24(gy, dst_step, dst_offset + gx);

#ifdef SRC_ALIGNED
        VT sdata = *((__global VT *)(src + src_index));
#else
        VT sdata = VLOADN(0, src + src_index);
#endif
        VT vthresh = (VT)(thresh);

#ifdef THRESH_BINARY
        VT vecValue = sdata > vthresh ? (VT)max_val : (VT)(0);
#elif defined THRESH_BINARY_INV
        VT vecValue = sdata > vthresh ? (VT)(0) : (VT)max_val;
#elif defined THRESH_TRUNC
        VT vecValue = sdata > vthresh ? (VT)thresh : sdata;
#elif defined THRESH_TOZERO
        VT vecValue = sdata > vthresh ? sdata : (VT)(0);
#elif defined THRESH_TOZERO_INV
        VT vecValue = sdata > vthresh ? (VT)(0) : sdata;
#endif

        if (gx + VECSIZE <= max_index)
#ifdef DST_ALIGNED
            *(__global VT*)(dst + dst_index) = vecValue;
#else
            VSTOREN(vecValue, 0, dst + dst_index);
#endif
        else
        {
            __attribute__(( aligned(sizeof(VT)) )) T array[VECSIZE];
            *((VT*)array) = vecValue;
            #pragma unroll
            for (int i = 0; i < VECSIZE; ++i)
                if (gx + i < max_index)
                    dst[dst_index + i] = array[i];
        }
    }
}

#else

__kernel void threshold(__global const T * restrict src, int src_offset, int src_step,
                        __global T * dst, int dst_offset, int dst_step,
                        T thresh, T max_val, int rows, int cols)
{
    int gx = get_global_id(0);
    int gy = get_global_id(1);

    if (gx < cols && gy < rows)
    {
        int src_index = mad24(gy, src_step, src_offset + gx);
        int dst_index = mad24(gy, dst_step, dst_offset + gx);

        T sdata = src[src_index];

#ifdef THRESH_BINARY
        dst[dst_index] = sdata > thresh ? max_val : (T)(0);
#elif defined THRESH_BINARY_INV
        dst[dst_index] = sdata > thresh ? (T)(0) : max_val;
#elif defined THRESH_TRUNC
        dst[dst_index] = sdata > thresh ? thresh : sdata;
#elif defined THRESH_TOZERO
        dst[dst_index] = sdata > thresh ? sdata : (T)(0);
#elif defined THRESH_TOZERO_INV
        dst[dst_index] = sdata > thresh ? (T)(0) : sdata;
#endif
    }
}

#endif

/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Institute Of Software Chinese Academy Of Science, all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Zhang Ying, zhangying913@gmail.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors as is and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#ifdef DOUBLE_SUPPORT
#ifdef cl_amd_fp64
#pragma OPENCL EXTENSION cl_amd_fp64:enable
#elif defined (cl_khr_fp64)
#pragma OPENCL EXTENSION cl_khr_fp64:enable
#endif
#endif

#ifdef VECTORIZED

__kernel void threshold(__global const T * restrict src, int src_offset, int src_step,
                        __global T * dst, int dst_offset, int dst_step,
                        T thresh, T max_val, int max_index, int rows, int cols)
{
    int gx = get_global_id(0);
    int gy = get_global_id(1);

    if (gx < cols && gy < rows)
    {
        gx *= VECSIZE;
        int src_index = mad24(gy, src_step, src_offset + gx);
        int dst_index = mad24(gy, dst_step, dst_offset + gx);

#ifdef SRC_ALIGNED
        VT sdata = *((__global VT *)(src + src_index));
#else
        VT sdata = VLOADN(0, src + src_index);
#endif
        VT vthresh = (VT)(thresh);

#ifdef THRESH_BINARY
        VT vecValue = sdata > vthresh ? max_val : (VT)(0);
#elif defined THRESH_BINARY_INV
        VT vecValue = sdata > vthresh ? (VT)(0) : max_val;
#elif defined THRESH_TRUNC
        VT vecValue = sdata > vthresh ? thresh : sdata;
#elif defined THRESH_TOZERO
        VT vecValue = sdata > vthresh ? sdata : (VT)(0);
#elif defined THRESH_TOZERO_INV
        VT vecValue = sdata > vthresh ? (VT)(0) : sdata;
#endif

        if (gx + VECSIZE <= max_index)
#ifdef DST_ALIGNED
            *(__global VT*)(dst + dst_index) = vecValue;
#else
            VSTOREN(vecValue, 0, dst + dst_index);
#endif
        else
        {
            __attribute__(( aligned(sizeof(VT)) )) T array[VECSIZE];
            *((VT*)array) = vecValue;
            #pragma unroll
            for (int i = 0; i < VECSIZE; ++i)
                if (gx + i < max_index)
                    dst[dst_index + i] = array[i];
        }
    }
}

#else

__kernel void threshold(__global const T * restrict src, int src_offset, int src_step,
                        __global T * dst, int dst_offset, int dst_step,
                        T thresh, T max_val, int rows, int cols)
{
    int gx = get_global_id(0);
    int gy = get_global_id(1);

    if (gx < cols && gy < rows)
    {
        int src_index = mad24(gy, src_step, src_offset + gx);
        int dst_index = mad24(gy, dst_step, dst_offset + gx);

        T sdata = src[src_index];

#ifdef THRESH_BINARY
        dst[dst_index] = sdata > thresh ? max_val : (T)(0);
#elif defined THRESH_BINARY_INV
        dst[dst_index] = sdata > thresh ? (T)(0) : max_val;
#elif defined THRESH_TRUNC
        dst[dst_index] = sdata > thresh ? thresh : sdata;
#elif defined THRESH_TOZERO
        dst[dst_index] = sdata > thresh ? sdata : (T)(0);
#elif defined THRESH_TOZERO_INV
        dst[dst_index] = sdata > thresh ? (T)(0) : sdata;
#endif
    }
}

#endif


OpenCL compile warning

OpenCL compile warning

/*
* This is based on the John The Ripper SHA512 code, modified for double SHA512 and for use as a miner in Bitmessage.
* This software is originally Copyright (c) 2012 Myrice <qqlddg at gmail dot com>
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without modification, are permitted.
*/

#ifdef cl_khr_byte_addressable_store
#pragma OPENCL EXTENSION cl_khr_byte_addressable_store : disable
#endif

#define uint8_t  unsigned char
#define uint32_t unsigned int
#define uint64_t unsigned long
#define SALT_SIZE 0

#define BINARY_SIZE 8
#define FULL_BINARY_SIZE 64

#define PLAINTEXT_LENGTH 72

#define CIPHERTEXT_LENGTH 128

/// Warning: This version of SWAP64(n) is slow and avoid bugs on AMD GPUs(7970)
#define SWAP64(n)       as_ulong(as_uchar8(n).s76543210)

/*
#define SWAP64(n) \
  (((n) << 56)					\
   | (((n) & 0xff00) << 40)			\
   | (((n) & 0xff0000) << 24)			\
   | (((n) & 0xff000000) << 8)			\
   | (((n) >> 8) & 0xff000000)			\
   | (((n) >> 24) & 0xff0000)			\
   | (((n) >> 40) & 0xff00)			\
   | ((n) >> 56))
*/

#define rol(x,n) ((x << n) | (x >> (64-n)))
#define ror(x,n) ((x >> n) | (x << (64-n)))
#define Ch(x,y,z) ((x & y) ^ ( (~x) & z))
#define Maj(x,y,z) ((x & y) ^ (x & z) ^ (y & z))
#define Sigma0(x) ((ror(x,28))  ^ (ror(x,34)) ^ (ror(x,39)))
#define Sigma1(x) ((ror(x,14))  ^ (ror(x,18)) ^ (ror(x,41)))
#define sigma0(x) ((ror(x,1))  ^ (ror(x,8)) ^(x>>7))
#define sigma1(x) ((ror(x,19)) ^ (ror(x,61)) ^(x>>6))

typedef struct { // notice memory align problem
	uint64_t H[8];
	uint32_t buffer[32];	//1024 bits
	uint32_t buflen;
} sha512_ctx;

typedef struct {
    uint64_t target;
    char v[PLAINTEXT_LENGTH+1];
} sha512_key;

/* Macros for reading/writing chars from int32's */
#define PUTCHAR(buf, index, val) (buf)[(index)>>2] = ((buf)[(index)>>2] & ~(0xffU << (((index) & 3) << 3))) + ((val) << (((index) & 3) << 3))

__constant uint64_t k[] = {
	0x428a2f98d728ae22UL, 0x7137449123ef65cdUL, 0xb5c0fbcfec4d3b2fUL,
	    0xe9b5dba58189dbbcUL,
	0x3956c25bf348b538UL, 0x59f111f1b605d019UL, 0x923f82a4af194f9bUL,
	    0xab1c5ed5da6d8118UL,
	0xd807aa98a3030242UL, 0x12835b0145706fbeUL, 0x243185be4ee4b28cUL,
	    0x550c7dc3d5ffb4e2UL,
	0x72be5d74f27b896fUL, 0x80deb1fe3b1696b1UL, 0x9bdc06a725c71235UL,
	    0xc19bf174cf692694UL,
	0xe49b69c19ef14ad2UL, 0xefbe4786384f25e3UL, 0x0fc19dc68b8cd5b5UL,
	    0x240ca1cc77ac9c65UL,
	0x2de92c6f592b0275UL, 0x4a7484aa6ea6e483UL, 0x5cb0a9dcbd41fbd4UL,
	    0x76f988da831153b5UL,
	0x983e5152ee66dfabUL, 0xa831c66d2db43210UL, 0xb00327c898fb213fUL,
	    0xbf597fc7beef0ee4UL,
	0xc6e00bf33da88fc2UL, 0xd5a79147930aa725UL, 0x06ca6351e003826fUL,
	    0x142929670a0e6e70UL,
	0x27b70a8546d22ffcUL, 0x2e1b21385c26c926UL, 0x4d2c6dfc5ac42aedUL,
	    0x53380d139d95b3dfUL,
	0x650a73548baf63deUL, 0x766a0abb3c77b2a8UL, 0x81c2c92e47edaee6UL,
	    0x92722c851482353bUL,
	0xa2bfe8a14cf10364UL, 0xa81a664bbc423001UL, 0xc24b8b70d0f89791UL,
	    0xc76c51a30654be30UL,
	0xd192e819d6ef5218UL, 0xd69906245565a910UL, 0xf40e35855771202aUL,
	    0x106aa07032bbd1b8UL,
	0x19a4c116b8d2d0c8UL, 0x1e376c085141ab53UL, 0x2748774cdf8eeb99UL,
	    0x34b0bcb5e19b48a8UL,
	0x391c0cb3c5c95a63UL, 0x4ed8aa4ae3418acbUL, 0x5b9cca4f7763e373UL,
	    0x682e6ff3d6b2b8a3UL,
	0x748f82ee5defb2fcUL, 0x78a5636f43172f60UL, 0x84c87814a1f0ab72UL,
	    0x8cc702081a6439ecUL,
	0x90befffa23631e28UL, 0xa4506cebde82bde9UL, 0xbef9a3f7b2c67915UL,
	    0xc67178f2e372532bUL,
	0xca273eceea26619cUL, 0xd186b8c721c0c207UL, 0xeada7dd6cde0eb1eUL,
	    0xf57d4f7fee6ed178UL,
	0x06f067aa72176fbaUL, 0x0a637dc5a2c898a6UL, 0x113f9804bef90daeUL,
	    0x1b710b35131c471bUL,
	0x28db77f523047d84UL, 0x32caab7b40c72493UL, 0x3c9ebe0a15c9bebcUL,
	    0x431d67c49c100d4cUL,
	0x4cc5d4becb3e42b6UL, 0x597f299cfc657e2aUL, 0x5fcb6fab3ad6faecUL,
	    0x6c44198c4a475817UL,
};

static void setup_ctx(sha512_ctx* ctx, const char * password, uint8_t pass_len)
{
	uint32_t* b32 = ctx->buffer;

	//set password to buffer
    for (uint32_t i = 0; i < pass_len; i++) {
		PUTCHAR(b32,i,password[i]);
	}
    ctx->buflen = pass_len;

	//append 1 to ctx buffer
	uint32_t length = ctx->buflen;
	PUTCHAR(b32, length, 0x80);
	while((++length & 3) != 0)  {
		PUTCHAR(b32, length, 0);
	}

	uint32_t* buffer32 = b32+(length>>2);
	for(uint32_t i = length; i < 128; i+=4) {// append 0 to 128
		*buffer32++=0;
	}

	//append length to buffer
	uint64_t *buffer64 = (uint64_t *)ctx->buffer;
	buffer64[15] = SWAP64(((uint64_t) ctx->buflen) * 8);
}

inline uint64_t sha512(char* password)
{
    __private sha512_ctx ctx;
	setup_ctx(&ctx, password, 72);
	// sha512 main`
	int i;

	uint64_t a = 0x6a09e667f3bcc908UL;
	uint64_t b = 0xbb67ae8584caa73bUL;
	uint64_t c = 0x3c6ef372fe94f82bUL;
	uint64_t d = 0xa54ff53a5f1d36f1UL;
	uint64_t e = 0x510e527fade682d1UL;
	uint64_t f = 0x9b05688c2b3e6c1fUL;
	uint64_t g = 0x1f83d9abfb41bd6bUL;
	uint64_t h = 0x5be0cd19137e2179UL;

	__private uint64_t w[16];

	uint64_t *data = (uint64_t *) ctx.buffer;

	for (i = 0; i < 16; i++)
		w[i] = SWAP64(data[i]);

	uint64_t t1, t2;
	for (i = 0; i < 16; i++) {
		t1 = k[i] + w[i] + h + Sigma1(e) + Ch(e, f, g);
		t2 = Maj(a, b, c) + Sigma0(a);

		h = g;
		g = f;
		f = e;
		e = d + t1;
		d = c;
		c = b;
		b = a;
		a = t1 + t2;
	}

	for (i = 16; i < 80; i++) {

		w[i & 15] =sigma1(w[(i - 2) & 15]) + sigma0(w[(i - 15) & 15]) + w[(i -16) & 15] + w[(i - 7) & 15];
		t1 = k[i] + w[i & 15] + h + Sigma1(e) + Ch(e, f, g);
		t2 = Maj(a, b, c) + Sigma0(a);

		h = g;
		g = f;
		f = e;
		e = d + t1;
		d = c;
		c = b;
		b = a;
		a = t1 + t2;
	}

	uint64_t finalhash[8];

	finalhash[0] = SWAP64(a + 0x6a09e667f3bcc908UL);
	finalhash[1] = SWAP64(b + 0xbb67ae8584caa73bUL);
	finalhash[2] = SWAP64(c + 0x3c6ef372fe94f82bUL);
	finalhash[3] = SWAP64(d + 0xa54ff53a5f1d36f1UL);
	finalhash[4] = SWAP64(e + 0x510e527fade682d1UL);
	finalhash[5] = SWAP64(f + 0x9b05688c2b3e6c1fUL);
	finalhash[6] = SWAP64(g + 0x1f83d9abfb41bd6bUL);
	finalhash[7] = SWAP64(h + 0x5be0cd19137e2179UL);

	setup_ctx(&ctx, (char*) finalhash, 64);

	a = 0x6a09e667f3bcc908UL;
	b = 0xbb67ae8584caa73bUL;
	c = 0x3c6ef372fe94f82bUL;
	d = 0xa54ff53a5f1d36f1UL;
	e = 0x510e527fade682d1UL;
	f = 0x9b05688c2b3e6c1fUL;
	g = 0x1f83d9abfb41bd6bUL;
	h = 0x5be0cd19137e2179UL;

	data = (uint64_t *) ctx.buffer;
	//((uint64_t*)ctx.buffer)[8] = SWAP64((uint64_t)0x80);

	for (i = 0; i < 16; i++)
		w[i] = SWAP64(data[i]);

	for (i = 0; i < 16; i++) {
		t1 = k[i] + w[i] + h + Sigma1(e) + Ch(e, f, g);
		t2 = Maj(a, b, c) + Sigma0(a);

		h = g;
		g = f;
		f = e;
		e = d + t1;
		d = c;
		c = b;
		b = a;
		a = t1 + t2;
	}

	for (i = 16; i < 80; i++) {

		w[i & 15] =sigma1(w[(i - 2) & 15]) + sigma0(w[(i - 15) & 15]) + w[(i -16) & 15] + w[(i - 7) & 15];
		t1 = k[i] + w[i & 15] + h + Sigma1(e) + Ch(e, f, g);
		t2 = Maj(a, b, c) + Sigma0(a);

		h = g;
		g = f;
		f = e;
		e = d + t1;
		d = c;
		c = b;
		b = a;
		a = t1 + t2;
	}
	return SWAP64(a + 0x6a09e667f3bcc908UL);
}

__kernel void kernel_sha512(__global const sha512_key *password,__global uint64_t *hash, uint64_t start)
{
    uint64_t idx = get_global_id(0);
	if (idx == 0 && start == 0) {
		*hash = 0;
	}
	uint64_t winval;

	uint64_t junk[9];

	__global uint64_t * source = (__global uint64_t*) password->v;
	for (int i = 1; i < 9; i++) {
		junk[i] = source[i];
	}

	junk[0] = SWAP64(idx + (start));

	winval = sha512((char*)junk);
	if (SWAP64(winval) < password->target) {
		*hash = SWAP64(junk[0]);
	}
}

/*
* This is based on the John The Ripper SHA512 code, modified for double SHA512 and for use as a miner in Bitmessage.
* This software is originally Copyright (c) 2012 Myrice <qqlddg at gmail dot com>
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without modification, are permitted.
*/

#ifdef cl_khr_byte_addressable_store
#pragma OPENCL EXTENSION cl_khr_byte_addressable_store : disable
#endif

#define uint8_t  unsigned char
#define uint32_t unsigned int
#define uint64_t unsigned long
#define SALT_SIZE 0

#define BINARY_SIZE 8
#define FULL_BINARY_SIZE 64

#define PLAINTEXT_LENGTH 72

#define CIPHERTEXT_LENGTH 128

/// Warning: This version of SWAP64(n) is slow and avoid bugs on AMD GPUs(7970)
#define SWAP64(n)       as_ulong(as_uchar8(n).s76543210)

/*
#define SWAP64(n) \
  (((n) << 56)					\
   | (((n) & 0xff00) << 40)			\
   | (((n) & 0xff0000) << 24)			\
   | (((n) & 0xff000000) << 8)			\
   | (((n) >> 8) & 0xff000000)			\
   | (((n) >> 24) & 0xff0000)			\
   | (((n) >> 40) & 0xff00)			\
   | ((n) >> 56))
*/

#define rol(x,n) ((x << n) | (x >> (64-n)))
#define ror(x,n) ((x >> n) | (x << (64-n)))
#define Ch(x,y,z) ((x & y) ^ ( (~x) & z))
#define Maj(x,y,z) ((x & y) ^ (x & z) ^ (y & z))
#define Sigma0(x) ((ror(x,28))  ^ (ror(x,34)) ^ (ror(x,39)))
#define Sigma1(x) ((ror(x,14))  ^ (ror(x,18)) ^ (ror(x,41)))
#define sigma0(x) ((ror(x,1))  ^ (ror(x,8)) ^(x>>7))
#define sigma1(x) ((ror(x,19)) ^ (ror(x,61)) ^(x>>6))

typedef struct { // notice memory align problem
	uint64_t H[8];
	uint32_t buffer[32];	//1024 bits
	uint32_t buflen;
} sha512_ctx;

typedef struct {
    uint64_t target;
    char v[PLAINTEXT_LENGTH+1];
} sha512_key;

/* Macros for reading/writing chars from int32's */
#define PUTCHAR(buf, index, val) (buf)[(index)>>2] = ((buf)[(index)>>2] & ~(0xffU << (((index) & 3) << 3))) + ((val) << (((index) & 3) << 3))

__constant uint64_t k[] = {
	0x428a2f98d728ae22UL, 0x7137449123ef65cdUL, 0xb5c0fbcfec4d3b2fUL,
	    0xe9b5dba58189dbbcUL,
	0x3956c25bf348b538UL, 0x59f111f1b605d019UL, 0x923f82a4af194f9bUL,
	    0xab1c5ed5da6d8118UL,
	0xd807aa98a3030242UL, 0x12835b0145706fbeUL, 0x243185be4ee4b28cUL,
	    0x550c7dc3d5ffb4e2UL,
	0x72be5d74f27b896fUL, 0x80deb1fe3b1696b1UL, 0x9bdc06a725c71235UL,
	    0xc19bf174cf692694UL,
	0xe49b69c19ef14ad2UL, 0xefbe4786384f25e3UL, 0x0fc19dc68b8cd5b5UL,
	    0x240ca1cc77ac9c65UL,
	0x2de92c6f592b0275UL, 0x4a7484aa6ea6e483UL, 0x5cb0a9dcbd41fbd4UL,
	    0x76f988da831153b5UL,
	0x983e5152ee66dfabUL, 0xa831c66d2db43210UL, 0xb00327c898fb213fUL,
	    0xbf597fc7beef0ee4UL,
	0xc6e00bf33da88fc2UL, 0xd5a79147930aa725UL, 0x06ca6351e003826fUL,
	    0x142929670a0e6e70UL,
	0x27b70a8546d22ffcUL, 0x2e1b21385c26c926UL, 0x4d2c6dfc5ac42aedUL,
	    0x53380d139d95b3dfUL,
	0x650a73548baf63deUL, 0x766a0abb3c77b2a8UL, 0x81c2c92e47edaee6UL,
	    0x92722c851482353bUL,
	0xa2bfe8a14cf10364UL, 0xa81a664bbc423001UL, 0xc24b8b70d0f89791UL,
	    0xc76c51a30654be30UL,
	0xd192e819d6ef5218UL, 0xd69906245565a910UL, 0xf40e35855771202aUL,
	    0x106aa07032bbd1b8UL,
	0x19a4c116b8d2d0c8UL, 0x1e376c085141ab53UL, 0x2748774cdf8eeb99UL,
	    0x34b0bcb5e19b48a8UL,
	0x391c0cb3c5c95a63UL, 0x4ed8aa4ae3418acbUL, 0x5b9cca4f7763e373UL,
	    0x682e6ff3d6b2b8a3UL,
	0x748f82ee5defb2fcUL, 0x78a5636f43172f60UL, 0x84c87814a1f0ab72UL,
	    0x8cc702081a6439ecUL,
	0x90befffa23631e28UL, 0xa4506cebde82bde9UL, 0xbef9a3f7b2c67915UL,
	    0xc67178f2e372532bUL,
	0xca273eceea26619cUL, 0xd186b8c721c0c207UL, 0xeada7dd6cde0eb1eUL,
	    0xf57d4f7fee6ed178UL,
	0x06f067aa72176fbaUL, 0x0a637dc5a2c898a6UL, 0x113f9804bef90daeUL,
	    0x1b710b35131c471bUL,
	0x28db77f523047d84UL, 0x32caab7b40c72493UL, 0x3c9ebe0a15c9bebcUL,
	    0x431d67c49c100d4cUL,
	0x4cc5d4becb3e42b6UL, 0x597f299cfc657e2aUL, 0x5fcb6fab3ad6faecUL,
	    0x6c44198c4a475817UL,
};

void setup_ctx(sha512_ctx* ctx, const char * password, uint8_t pass_len)
{
	uint32_t* b32 = ctx->buffer;

	//set password to buffer
    for (uint32_t i = 0; i < pass_len; i++) {
		PUTCHAR(b32,i,password[i]);
	}
    ctx->buflen = pass_len;

	//append 1 to ctx buffer
	uint32_t length = ctx->buflen;
	PUTCHAR(b32, length, 0x80);
	while((++length & 3) != 0)  {
		PUTCHAR(b32, length, 0);
	}

	uint32_t* buffer32 = b32+(length>>2);
	for(uint32_t i = length; i < 128; i+=4) {// append 0 to 128
		*buffer32++=0;
	}

	//append length to buffer
	uint64_t *buffer64 = (uint64_t *)ctx->buffer;
	buffer64[15] = SWAP64(((uint64_t) ctx->buflen) * 8);
}

inline uint64_t sha512(char* password)
{
    __private sha512_ctx ctx;
	setup_ctx(&ctx, password, 72);
	// sha512 main`
	int i;

	uint64_t a = 0x6a09e667f3bcc908UL;
	uint64_t b = 0xbb67ae8584caa73bUL;
	uint64_t c = 0x3c6ef372fe94f82bUL;
	uint64_t d = 0xa54ff53a5f1d36f1UL;
	uint64_t e = 0x510e527fade682d1UL;
	uint64_t f = 0x9b05688c2b3e6c1fUL;
	uint64_t g = 0x1f83d9abfb41bd6bUL;
	uint64_t h = 0x5be0cd19137e2179UL;

	__private uint64_t w[16];

	uint64_t *data = (uint64_t *) ctx.buffer;

	for (i = 0; i < 16; i++)
		w[i] = SWAP64(data[i]);

	uint64_t t1, t2;
	for (i = 0; i < 16; i++) {
		t1 = k[i] + w[i] + h + Sigma1(e) + Ch(e, f, g);
		t2 = Maj(a, b, c) + Sigma0(a);

		h = g;
		g = f;
		f = e;
		e = d + t1;
		d = c;
		c = b;
		b = a;
		a = t1 + t2;
	}

	for (i = 16; i < 80; i++) {

		w[i & 15] =sigma1(w[(i - 2) & 15]) + sigma0(w[(i - 15) & 15]) + w[(i -16) & 15] + w[(i - 7) & 15];
		t1 = k[i] + w[i & 15] + h + Sigma1(e) + Ch(e, f, g);
		t2 = Maj(a, b, c) + Sigma0(a);

		h = g;
		g = f;
		f = e;
		e = d + t1;
		d = c;
		c = b;
		b = a;
		a = t1 + t2;
	}

	uint64_t finalhash[8];

	finalhash[0] = SWAP64(a + 0x6a09e667f3bcc908UL);
	finalhash[1] = SWAP64(b + 0xbb67ae8584caa73bUL);
	finalhash[2] = SWAP64(c + 0x3c6ef372fe94f82bUL);
	finalhash[3] = SWAP64(d + 0xa54ff53a5f1d36f1UL);
	finalhash[4] = SWAP64(e + 0x510e527fade682d1UL);
	finalhash[5] = SWAP64(f + 0x9b05688c2b3e6c1fUL);
	finalhash[6] = SWAP64(g + 0x1f83d9abfb41bd6bUL);
	finalhash[7] = SWAP64(h + 0x5be0cd19137e2179UL);

	setup_ctx(&ctx, (char*) finalhash, 64);

	a = 0x6a09e667f3bcc908UL;
	b = 0xbb67ae8584caa73bUL;
	c = 0x3c6ef372fe94f82bUL;
	d = 0xa54ff53a5f1d36f1UL;
	e = 0x510e527fade682d1UL;
	f = 0x9b05688c2b3e6c1fUL;
	g = 0x1f83d9abfb41bd6bUL;
	h = 0x5be0cd19137e2179UL;

	data = (uint64_t *) ctx.buffer;
	//((uint64_t*)ctx.buffer)[8] = SWAP64((uint64_t)0x80);

	for (i = 0; i < 16; i++)
		w[i] = SWAP64(data[i]);

	for (i = 0; i < 16; i++) {
		t1 = k[i] + w[i] + h + Sigma1(e) + Ch(e, f, g);
		t2 = Maj(a, b, c) + Sigma0(a);

		h = g;
		g = f;
		f = e;
		e = d + t1;
		d = c;
		c = b;
		b = a;
		a = t1 + t2;
	}

	for (i = 16; i < 80; i++) {

		w[i & 15] =sigma1(w[(i - 2) & 15]) + sigma0(w[(i - 15) & 15]) + w[(i -16) & 15] + w[(i - 7) & 15];
		t1 = k[i] + w[i & 15] + h + Sigma1(e) + Ch(e, f, g);
		t2 = Maj(a, b, c) + Sigma0(a);

		h = g;
		g = f;
		f = e;
		e = d + t1;
		d = c;
		c = b;
		b = a;
		a = t1 + t2;
	}
	return SWAP64(a + 0x6a09e667f3bcc908UL);
}

__kernel void kernel_sha512(__global const sha512_key *password,__global uint64_t *hash, uint64_t start)
{
    uint64_t idx = get_global_id(0);
	if (idx == 0 && start == 0) {
		*hash = 0;
	}
	uint64_t winval;

	uint64_t junk[9];

	__global uint64_t * source = (__global uint64_t*) password->v;
	for (int i = 1; i < 9; i++) {
		junk[i] = source[i];
	}

	junk[0] = SWAP64(idx + (start));

	winval = sha512((char*)junk);
	if (SWAP64(winval) < password->target) {
		*hash = SWAP64(junk[0]);
	}
}


Use included header in render.cl

Use included header in render.cl

#include "liegroups.clh"

inline float3 raycast(const float3 plane_normal, const float3 plane_origin, const float3 ray_direction, const float3 ray_origin) {
  const float d =
      dot((plane_origin - ray_origin), plane_normal) / dot(ray_direction, plane_normal);
  return ray_origin + (d * ray_direction);
}

__kernel void ssd_r(
    __read_only image2d_t image1,
    __read_only image2d_t image2,
    __write_only image2d_t output) {
    const sampler_t smp = CLK_NORMALIZED_COORDS_FALSE |
                          CLK_ADDRESS_CLAMP |
                          CLK_FILTER_NEAREST;
                          // CLK_ADDRESS_NONE : Guarantee we won't leave the image

    const int col = get_global_id(0);
    const int row = get_global_id(1);

    const int2 translation = (int2) (col, row);

    //
    // For a hypothetical translation uv_sample = uv0 + (col, row)
    // Compute an SSD for the whole image
    //

    const int2 im1_size = get_image_dim(image1);
    const int2 im2_size = get_image_dim(image2);

    const int region_size = 50;
    const int half_region_size = region_size / 2;
    int ustart = max(col - half_region_size, 0);
    int uend = min(col + half_region_size, im1_size.x);

    int vstart = max(row - half_region_size, 0);
    int vend = min(row + half_region_size, im1_size.y);

    for (int u1 = ustart; u1 < uend; ++u1) {
        for (int v1 = vstart; v1 < vend; ++v1) {
            const int2 coord = (int2) (u1, v1);
            const float4 px_uv = read_imagef(image1, smp, coord).x;
        }
    }
}

__kernel void sum_squared_diff(
    __read_only image2d_t image_1,
    __read_only image2d_t image_2,
    __global float * local_sums,
    __global float * full_sum
    ) {
    const int2 read_coord = (int2) (get_global_id(0), get_global_id(1));
    const sampler_t smp = CLK_NORMALIZED_COORDS_FALSE |
                          CLK_ADDRESS_CLAMP |
                          CLK_FILTER_NEAREST;

    const float im1_val = read_imagef(image_1, smp, read_coord).x;
    const float im2_val = read_imagef(image_2, smp, read_coord).x;
    const float error = (im1_val - im2_val) / 255.0;
    const float error_sq = error * error;
    const float sum_partial = work_group_reduce_add(error_sq);

    const int write_loc = get_group_id(1);

    const int local_col = get_local_id(0);
    const int local_row = get_local_id(1);
    if (local_row == 0 && local_col == 0) {
      local_sums[write_loc] = sum_partial / ((float) get_local_size(0));
    }

    barrier(CLK_GLOBAL_MEM_FENCE);
    if (get_group_id(1) == 0) {
        if (local_row == 0 && local_col == 0) {
            float total = 0.0;
            for (int k = 0; k < 270; ++k) {
                total += local_sums[k];
            }
            full_sum[0] = total;
        }
    }
}

//
// Read from an image
//

__kernel void render(
    __read_only image2d_t input_image,
    __read_only image2d_t ray_lut,
    __write_only image2d_t output_image,
    const sampler_t sampler,
    const struct clSE3 camera_from_plane) {
    //
    // Render shit up
    //

    const float3 plane_normal_plane_frame = (float3) (0.0, 0.0, 1.0);
    const float3 plane_normal_camera_frame = mul_so3(camera_from_plane.rotation, plane_normal_plane_frame);
    const float3 plane_origin_camera_frame = camera_from_plane.translation;

    const int col = get_global_id(0);
    const int row = get_global_id(1);

    float2 sample_coords = (float) (col, row);
    int2 write_coords = (int2) (col, row);

    const float3 ray_dir_camera_frame = read_imagef(ray_lut, sampler, write_coords).xyz;
    const float3 ray_origin_camera_frame = (float3) (0.0, 0.0, 0.0);
    const float3 intersection_camera_frame = raycast(
        plane_normal_camera_frame,
        plane_origin_camera_frame,
        ray_dir_camera_frame,
        ray_origin_camera_frame
    );

    const struct clSE3 plane_from_camera = inverse_se3(camera_from_plane);
    const float2 intersection_plane_frame = mul_se3(plane_from_camera, intersection_camera_frame).xy;

    const float width = get_image_width(input_image);
    const float4 pixel = read_imagef(input_image, sampler, intersection_plane_frame * width);
    write_imagef(output_image, write_coords, pixel.x);
}

struct __attribute__((packed)) clSO3 {
  float3 r0;
  float3 r1;
  float3 r2;
};

struct __attribute__((packed)) clSE3 {
    struct clSO3 rotation;
    float3 translation;
};

inline float3 mul_so3(const struct clSO3 m, const float3 v) {
    float3 result;
    result.x = dot(m.r0, v);
    result.y = dot(m.r1, v);
    result.z = dot(m.r2, v);
    return result;
}

struct __attribute__((packed)) clSE2 {
    float2 r0;
    float2 r1;
    float2 translation;
};

inline struct clSO3 inverse_so3(const struct clSO3 m) {
    struct clSO3 result;
    result.r0.x = m.r0.x;
    result.r0.y = m.r1.x;
    result.r0.z = m.r2.x;

    result.r1.x = m.r0.y;
    result.r1.y = m.r1.y;
    result.r1.z = m.r2.y;

    result.r2.x = m.r0.z;
    result.r2.y = m.r1.z;
    result.r2.z = m.r2.z;
    return result;
}

inline struct clSE3 inverse_se3(const struct clSE3 m) {
    struct clSE3 result;
    result.rotation = inverse_so3(m.rotation);
    result.translation = -mul_so3(result.rotation, m.translation);
    return result;
}

inline float3 mul_se3(const struct clSE3 m, const float3 v) {
    float3 result = mul_so3(m.rotation, v) + m.translation;
    return result;
}

inline float2 mul_se2(const struct clSE2 m, const float2 v) {
    float2 result;
    result.x = dot(m.r0, v) + m.translation.x;
    result.y = dot(m.r1, v) + m.translation.y;
    return result;
}

inline float3 raycast(const float3 plane_normal, const float3 plane_origin, const float3 ray_direction, const float3 ray_origin) {
  const float d =
      dot((plane_origin - ray_origin), plane_normal) / dot(ray_direction, plane_normal);
  return ray_origin + (d * ray_direction);
}

__kernel void ssd_r(
    __read_only image2d_t image1,
    __read_only image2d_t image2,
    __write_only image2d_t output) {
    const sampler_t smp = CLK_NORMALIZED_COORDS_FALSE |
                          CLK_ADDRESS_CLAMP |
                          CLK_FILTER_NEAREST;
                          // CLK_ADDRESS_NONE : Guarantee we won't leave the image

    const int col = get_global_id(0);
    const int row = get_global_id(1);

    const int2 translation = (int2) (col, row);

    //
    // For a hypothetical translation uv_sample = uv0 + (col, row)
    // Compute an SSD for the whole image
    //

    const int2 im1_size = get_image_dim(image1);
    const int2 im2_size = get_image_dim(image2);

    const int region_size = 50;
    const int half_region_size = region_size / 2;
    int ustart = max(col - half_region_size, 0);
    int uend = min(col + half_region_size, im1_size.x);

    int vstart = max(row - half_region_size, 0);
    int vend = min(row + half_region_size, im1_size.y);

    for (int u1 = ustart; u1 < uend; ++u1) {
        for (int v1 = vstart; v1 < vend; ++v1) {
            const int2 coord = (int2) (u1, v1);
            const float4 px_uv = read_imagef(image1, smp, coord).x;
        }
    }
}

__kernel void sum_squared_diff(
    __read_only image2d_t image_1,
    __read_only image2d_t image_2,
    __global float * local_sums,
    __global float * full_sum
    ) {
    const int2 read_coord = (int2) (get_global_id(0), get_global_id(1));
    const sampler_t smp = CLK_NORMALIZED_COORDS_FALSE |
                          CLK_ADDRESS_CLAMP |
                          CLK_FILTER_NEAREST;

    const float im1_val = read_imagef(image_1, smp, read_coord).x;
    const float im2_val = read_imagef(image_2, smp, read_coord).x;
    const float error = (im1_val - im2_val) / 255.0;
    const float error_sq = error * error;
    const float sum_partial = work_group_reduce_add(error_sq);

    const int write_loc = get_group_id(1);

    const int local_col = get_local_id(0);
    const int local_row = get_local_id(1);
    if (local_row == 0 && local_col == 0) {
      local_sums[write_loc] = sum_partial / ((float) get_local_size(0));
    }

    barrier(CLK_GLOBAL_MEM_FENCE);
    if (get_group_id(1) == 0) {
        if (local_row == 0 && local_col == 0) {
            float total = 0.0;
            for (int k = 0; k < 270; ++k) {
                total += local_sums[k];
            }
            full_sum[0] = total;
        }
    }
}

//
// Read from an image
//

__kernel void render(
    __read_only image2d_t input_image,
    __read_only image2d_t ray_lut,
    __write_only image2d_t output_image,
    const sampler_t sampler,
    const struct clSE3 camera_from_plane) {
    //
    // Render shit up
    //

    const float3 plane_normal_plane_frame = (float3) (0.0, 0.0, 1.0);
    const float3 plane_normal_camera_frame = mul_so3(camera_from_plane.rotation, plane_normal_plane_frame);
    const float3 plane_origin_camera_frame = camera_from_plane.translation;

    const int col = get_global_id(0);
    const int row = get_global_id(1);

    float2 sample_coords = (float) (col, row);
    int2 write_coords = (int2) (col, row);

    const float3 ray_dir_camera_frame = read_imagef(ray_lut, sampler, write_coords).xyz;
    const float3 ray_origin_camera_frame = (float3) (0.0, 0.0, 0.0);
    const float3 intersection_camera_frame = raycast(
        plane_normal_camera_frame,
        plane_origin_camera_frame,
        ray_dir_camera_frame,
        ray_origin_camera_frame
    );

    const struct clSE3 plane_from_camera = inverse_se3(camera_from_plane);
    const float2 intersection_plane_frame = mul_se3(plane_from_camera, intersection_camera_frame).xy;

    const float4 pixel = read_imagef(input_image, sampler, intersection_plane_frame * 100.0f);
    write_imagef(output_image, write_coords, pixel.x);
}


Fix a bug found on Intel OpenCL SDK.

Fix a bug found on Intel OpenCL SDK.

/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Institute Of Software Chinese Academy Of Science, all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Jia Haipeng, jiahaipeng95@gmail.com
//    Peng Xiao,   pengxiao@outlook.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other GpuMaterials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors as is and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#if defined (DOUBLE_SUPPORT)

#ifdef cl_khr_fp64
#pragma OPENCL EXTENSION cl_khr_fp64:enable
#elif defined (cl_amd_fp64)
#pragma OPENCL EXTENSION cl_amd_fp64:enable
#endif

#endif

#ifdef T_FLOAT
#define T float
#else
#define T short
#endif

///////////////////////////////////////////////////////////////
/////////////////common///////////////////////////////////////
/////////////////////////////////////////////////////////////
T saturate_cast(float v){
#ifdef T_SHORT
    return convert_short_sat_rte(v);
#else
    return v;
#endif
}

#define FLOAT_MAX 3.402823466e+38f
typedef struct
{
    int   cndisp;
    float cmax_data_term;
    float cdata_weight;
    float cmax_disc_term;
    float cdisc_single_jump;
}con_srtuct_t;
///////////////////////////////////////////////////////////////
////////////////////////// comp data //////////////////////////
///////////////////////////////////////////////////////////////

float pix_diff_1(__global const uchar *ls, __global const uchar *rs)
{
    return abs((int)(*ls) - *rs);
}

float pix_diff_3(__global const uchar *ls, __global const uchar *rs)
{
    const float tr = 0.299f;
    const float tg = 0.587f;
    const float tb = 0.114f;

    float val;

    val =  tb * abs((int)ls[0] - rs[0]);
    val += tg * abs((int)ls[1] - rs[1]);
    val += tr * abs((int)ls[2] - rs[2]);

    return val;
}
float pix_diff_4(__global const uchar *ls, __global const uchar *rs)
{
    uchar4 l, r;
    l = *((__global uchar4 *)ls);
    r = *((__global uchar4 *)rs);

    const float tr = 0.299f;
    const float tg = 0.587f;
    const float tb = 0.114f;

    float val;

    val  = tb * abs((int)l.x - r.x);
    val += tg * abs((int)l.y - r.y);
    val += tr * abs((int)l.z - r.z);

    return val;
}

#ifndef CN
#define CN 4
#endif

#define CAT(X,Y) X##Y
#define CAT2(X,Y) CAT(X,Y)

#define PIX_DIFF CAT2(pix_diff_, CN)

__kernel void comp_data(__global uchar *left,  int left_rows,  int left_cols,  int left_step,
                        __global uchar *right, int right_step,
                        __global T *data, int data_step,
                        __constant con_srtuct_t *con_st)
{
    int x = get_global_id(0);
    int y = get_global_id(1);

    if (y > 0 && y < (left_rows - 1) && x > 0 && x < (left_cols - 1))
    {
        data_step /= sizeof(T);
        const __global uchar* ls = left  + y * left_step  + x * CN;
        const __global uchar* rs = right + y * right_step + x * CN;

        __global T *ds = data + y * data_step + x;

        const unsigned int disp_step = data_step * left_rows;

        for (int disp = 0; disp < con_st -> cndisp; disp++)
        {
            if (x - disp >= 1)
            {
                float val = 0;
                val = PIX_DIFF(ls, rs - disp * CN);
                ds[disp * disp_step] =  saturate_cast(fmin(con_st -> cdata_weight * val,
                    con_st -> cdata_weight * con_st -> cmax_data_term));
            }
            else
            {
                ds[disp * disp_step] =  saturate_cast(con_st -> cdata_weight * con_st -> cmax_data_term);
            }
        }
    }
}

///////////////////////////////////////////////////////////////
//////////////////////// data step down ///////////////////////
///////////////////////////////////////////////////////////////
__kernel void data_step_down(__global T *src, int src_rows,
                             __global T *dst, int dst_rows, int dst_cols,
                             int src_step, int dst_step,
                             int cndisp)
{
    const int x = get_global_id(0);
    const int y = get_global_id(1);

    if (x < dst_cols && y < dst_rows)
    {
        src_step /= sizeof(T);
        dst_step /= sizeof(T);
        for (int d = 0; d < cndisp; ++d)
        {
            float dst_reg;
            dst_reg  = src[(d * src_rows + min(2*y+0, src_rows-1)) * src_step + 2*x+0];
            dst_reg += src[(d * src_rows + min(2*y+1, src_rows-1)) * src_step + 2*x+0];
            dst_reg += src[(d * src_rows + min(2*y+0, src_rows-1)) * src_step + 2*x+1];
            dst_reg += src[(d * src_rows + min(2*y+1, src_rows-1)) * src_step + 2*x+1];

            dst[(d * dst_rows + y) * dst_step + x] = saturate_cast(dst_reg);
        }
    }
}

///////////////////////////////////////////////////////////////
/////////////////// level up messages  ////////////////////////
///////////////////////////////////////////////////////////////
__kernel void level_up_message(__global T *src, int src_rows, int src_step,
                               __global T *dst, int dst_rows, int dst_cols, int dst_step,
                               int cndisp)
{
    const int x = get_global_id(0);
    const int y = get_global_id(1);

    if (x < dst_cols && y < dst_rows)
    {
        src_step /= sizeof(T);
        dst_step /= sizeof(T);

        const int dst_disp_step = dst_step * dst_rows;
        const int src_disp_step = src_step * src_rows;

        __global T       *dstr = dst + y * dst_step + x;
        __global const T *srcr = src + (y / 2 * src_step) + (x / 2);

        for (int d = 0; d < cndisp; ++d)
            dstr[d * dst_disp_step] = srcr[d * src_disp_step];
    }
}

///////////////////////////////////////////////////////////////
////////////////////  calc all iterations /////////////////////
///////////////////////////////////////////////////////////////
void calc_min_linear_penalty(__global T * dst, int disp_step,
                             int cndisp, float cdisc_single_jump)
{
    float prev = dst[0];
    float cur;

    for (int disp = 1; disp < cndisp; ++disp)
    {
        prev += cdisc_single_jump;
        cur = dst[disp_step * disp];

        if (prev < cur)
        {
            cur = prev;
            dst[disp_step * disp] = saturate_cast(prev);
        }

        prev = cur;
    }

    prev = dst[(cndisp - 1) * disp_step];
    for (int disp = cndisp - 2; disp >= 0; disp--)
    {
        prev += cdisc_single_jump;
        cur = dst[disp_step * disp];

        if (prev < cur)
        {
            cur = prev;
            dst[disp_step * disp] = saturate_cast(prev);
        }
        prev = cur;
    }
}
void message(const __global T *msg1, const __global T *msg2,
             const __global T *msg3, const __global T *data, __global T *dst,
             int msg_disp_step, int data_disp_step, int cndisp, float cmax_disc_term, float cdisc_single_jump)
{
    float minimum = FLOAT_MAX;

    for(int i = 0; i < cndisp; ++i)
    {
        float dst_reg;
        dst_reg  = msg1[msg_disp_step * i];
        dst_reg += msg2[msg_disp_step * i];
        dst_reg += msg3[msg_disp_step * i];
        dst_reg += data[data_disp_step * i];

        if (dst_reg < minimum)
            minimum = dst_reg;

        dst[msg_disp_step * i] = saturate_cast(dst_reg);
    }

    calc_min_linear_penalty(dst, msg_disp_step, cndisp, cdisc_single_jump);

    minimum += cmax_disc_term;

    float sum = 0;
    for(int i = 0; i < cndisp; ++i)
    {
        float dst_reg = dst[msg_disp_step * i];
        if (dst_reg > minimum)
        {
            dst_reg = minimum;
            dst[msg_disp_step * i] = saturate_cast(minimum);
        }
        sum += dst_reg;
    }
    sum /= cndisp;

    for(int i = 0; i < cndisp; ++i)
        dst[msg_disp_step * i] -= sum;
}
__kernel void one_iteration(__global T *u,    int u_step,
                            __global T *data, int data_step,
                            __global T *d,    __global T *l, __global T *r,
                            int t, int cols, int rows,
                            int cndisp, float cmax_disc_term, float cdisc_single_jump)
{
    const int y = get_global_id(1);
    const int x = ((get_global_id(0)) << 1) + ((y + t) & 1);

    if ((y > 0) && (y < rows - 1) && (x > 0) && (x < cols - 1))
    {
        u_step    /= sizeof(T);
        data_step /= sizeof(T);

        __global T *us = u + y * u_step + x;
        __global T *ds = d + y * u_step + x;
        __global T *ls = l + y * u_step + x;
        __global T *rs = r + y * u_step + x;
        const __global  T *dt = data + y * data_step + x;

        int msg_disp_step = u_step * rows;
        int data_disp_step = data_step * rows;

        message(us + u_step, ls      + 1, rs - 1, dt, us, msg_disp_step, data_disp_step, cndisp,
            cmax_disc_term, cdisc_single_jump);
        message(ds - u_step, ls      + 1, rs - 1, dt, ds, msg_disp_step, data_disp_step, cndisp,
            cmax_disc_term, cdisc_single_jump);

        message(us + u_step, ds - u_step, rs - 1, dt, rs, msg_disp_step, data_disp_step, cndisp,
            cmax_disc_term, cdisc_single_jump);
        message(us + u_step, ds - u_step, ls + 1, dt, ls, msg_disp_step, data_disp_step, cndisp,
            cmax_disc_term, cdisc_single_jump);
    }
}

///////////////////////////////////////////////////////////////
/////////////////////////// output ////////////////////////////
///////////////////////////////////////////////////////////////
__kernel void output(const __global T *u, int u_step,
                     const __global T *d, const __global T *l,
                     const __global T *r, const __global T *data,
                     __global T *disp, int disp_rows, int disp_cols, int disp_step,
                     int cndisp)
{
    const int x = get_global_id(0);
    const int y = get_global_id(1);

    if (y > 0 && y < disp_rows - 1 && x > 0 && x < disp_cols - 1)
    {
        u_step    /= sizeof(T);
        disp_step /= sizeof(T);
        const __global T *us = u + (y + 1) * u_step + x;
        const __global T *ds = d + (y - 1) * u_step + x;
        const __global T *ls = l + y * u_step + (x + 1);
        const __global T *rs = r + y * u_step + (x - 1);
        const __global T *dt = data + y * u_step + x;

        int disp_steps = disp_rows * u_step;

        int best = 0;
        float best_val = FLOAT_MAX;
        for (int d = 0; d < cndisp; ++d)
        {
            float val;
            val  = us[d * disp_steps];
            val += ds[d * disp_steps];
            val += ls[d * disp_steps];
            val += rs[d * disp_steps];
            val += dt[d * disp_steps];

            if (val < best_val)
            {
                best_val = val;
                best = d;
            }
        }

        (disp + y * disp_step)[x] = convert_short_sat(best);
    }
}

/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Institute Of Software Chinese Academy Of Science, all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Jia Haipeng, jiahaipeng95@gmail.com
//    Peng Xiao,   pengxiao@outlook.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other GpuMaterials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors as is and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#if defined (DOUBLE_SUPPORT)

#ifdef cl_khr_fp64
#pragma OPENCL EXTENSION cl_khr_fp64:enable
#elif defined (cl_amd_fp64)
#pragma OPENCL EXTENSION cl_amd_fp64:enable
#endif

#endif

#ifdef T_FLOAT
#define T float
#else
#define T short
#endif

///////////////////////////////////////////////////////////////
/////////////////common///////////////////////////////////////
/////////////////////////////////////////////////////////////
T saturate_cast(float v){
#ifdef T_SHORT
    return convert_short_sat_rte(v);
#else
    return v;
#endif
}

#define FLOAT_MAX 3.402823466e+38f
typedef struct
{
    int   cndisp;
    float cmax_data_term;
    float cdata_weight;
    float cmax_disc_term;
    float cdisc_single_jump;
}con_srtuct_t;
///////////////////////////////////////////////////////////////
////////////////////////// comp data //////////////////////////
///////////////////////////////////////////////////////////////

float pix_diff_1(__global const uchar *ls, __global const uchar *rs)
{
    return abs((int)(*ls) - *rs);
}

float pix_diff_3(__global const uchar *ls, __global const uchar *rs)
{
    const float tr = 0.299f;
    const float tg = 0.587f;
    const float tb = 0.114f;

    float val;

    val =  tb * abs((int)ls[0] - rs[0]);
    val += tg * abs((int)ls[1] - rs[1]);
    val += tr * abs((int)ls[2] - rs[2]);

    return val;
}
float pix_diff_4(__global const uchar *ls, __global const uchar *rs)
{
    uchar4 l, r;
    l = *((__global uchar4 *)ls);
    r = *((__global uchar4 *)rs);

    const float tr = 0.299f;
    const float tg = 0.587f;
    const float tb = 0.114f;

    float val;

    val  = tb * abs((int)l.x - r.x);
    val += tg * abs((int)l.y - r.y);
    val += tr * abs((int)l.z - r.z);

    return val;
}

#ifndef CN
#define CN 4
#endif

#define CAT(X,Y) X##Y
#define CAT2(X,Y) CAT(X,Y)

#define PIX_DIFF CAT2(pix_diff_, CN)

__kernel void comp_data(__global uchar *left,  int left_rows,  int left_cols,  int left_step,
                        __global uchar *right, int right_step,
                        __global T *data, int data_step,
                        __constant con_srtuct_t *con_st)
{
    int x = get_global_id(0);
    int y = get_global_id(1);

    if (y > 0 && y < (left_rows - 1) && x > 0 && x < (left_cols - 1))
    {
        data_step /= sizeof(T);
        const __global uchar* ls = left  + y * left_step  + x * CN;
        const __global uchar* rs = right + y * right_step + x * CN;

        __global T *ds = data + y * data_step + x;

        const unsigned int disp_step = data_step * left_rows;

        for (int disp = 0; disp < con_st -> cndisp; disp++)
        {
            if (x - disp >= 1)
            {
                float val = 0;
                val = PIX_DIFF(ls, rs - disp * CN);
                ds[disp * disp_step] =  saturate_cast(fmin(con_st -> cdata_weight * val,
                    con_st -> cdata_weight * con_st -> cmax_data_term));
            }
            else
            {
                ds[disp * disp_step] =  saturate_cast(con_st -> cdata_weight * con_st -> cmax_data_term);
            }
        }
    }
}

///////////////////////////////////////////////////////////////
//////////////////////// data step down ///////////////////////
///////////////////////////////////////////////////////////////
__kernel void data_step_down(__global T *src, int src_rows,
                             __global T *dst, int dst_rows, int dst_cols,
                             int src_step, int dst_step,
                             int cndisp)
{
    const int x = get_global_id(0);
    const int y = get_global_id(1);

    if (x < dst_cols && y < dst_rows)
    {
        src_step /= sizeof(T);
        dst_step /= sizeof(T);
        for (int d = 0; d < cndisp; ++d)
        {
            float dst_reg;
            dst_reg  = src[(d * src_rows + (2*y+0)) * src_step + 2*x+0];
            dst_reg += src[(d * src_rows + (2*y+1)) * src_step + 2*x+0];
            dst_reg += src[(d * src_rows + (2*y+0)) * src_step + 2*x+1];
            dst_reg += src[(d * src_rows + (2*y+1)) * src_step + 2*x+1];

            dst[(d * dst_rows + y) * dst_step + x] = saturate_cast(dst_reg);
        }
    }
}

///////////////////////////////////////////////////////////////
/////////////////// level up messages  ////////////////////////
///////////////////////////////////////////////////////////////
__kernel void level_up_message(__global T *src, int src_rows, int src_step,
                               __global T *dst, int dst_rows, int dst_cols, int dst_step,
                               int cndisp)
{
    const int x = get_global_id(0);
    const int y = get_global_id(1);

    if (x < dst_cols && y < dst_rows)
    {
        src_step /= sizeof(T);
        dst_step /= sizeof(T);

        const int dst_disp_step = dst_step * dst_rows;
        const int src_disp_step = src_step * src_rows;

        __global T       *dstr = dst + y * dst_step + x;
        __global const T *srcr = src + (y / 2 * src_step) + (x / 2);

        for (int d = 0; d < cndisp; ++d)
            dstr[d * dst_disp_step] = srcr[d * src_disp_step];
    }
}

///////////////////////////////////////////////////////////////
////////////////////  calc all iterations /////////////////////
///////////////////////////////////////////////////////////////
void calc_min_linear_penalty(__global T * dst, int disp_step,
                             int cndisp, float cdisc_single_jump)
{
    float prev = dst[0];
    float cur;

    for (int disp = 1; disp < cndisp; ++disp)
    {
        prev += cdisc_single_jump;
        cur = dst[disp_step * disp];

        if (prev < cur)
        {
            cur = prev;
            dst[disp_step * disp] = saturate_cast(prev);
        }

        prev = cur;
    }

    prev = dst[(cndisp - 1) * disp_step];
    for (int disp = cndisp - 2; disp >= 0; disp--)
    {
        prev += cdisc_single_jump;
        cur = dst[disp_step * disp];

        if (prev < cur)
        {
            cur = prev;
            dst[disp_step * disp] = saturate_cast(prev);
        }
        prev = cur;
    }
}
void message(const __global T *msg1, const __global T *msg2,
             const __global T *msg3, const __global T *data, __global T *dst,
             int msg_disp_step, int data_disp_step, int cndisp, float cmax_disc_term, float cdisc_single_jump)
{
    float minimum = FLOAT_MAX;

    for(int i = 0; i < cndisp; ++i)
    {
        float dst_reg;
        dst_reg  = msg1[msg_disp_step * i];
        dst_reg += msg2[msg_disp_step * i];
        dst_reg += msg3[msg_disp_step * i];
        dst_reg += data[data_disp_step * i];

        if (dst_reg < minimum)
            minimum = dst_reg;

        dst[msg_disp_step * i] = saturate_cast(dst_reg);
    }

    calc_min_linear_penalty(dst, msg_disp_step, cndisp, cdisc_single_jump);

    minimum += cmax_disc_term;

    float sum = 0;
    for(int i = 0; i < cndisp; ++i)
    {
        float dst_reg = dst[msg_disp_step * i];
        if (dst_reg > minimum)
        {
            dst_reg = minimum;
            dst[msg_disp_step * i] = saturate_cast(minimum);
        }
        sum += dst_reg;
    }
    sum /= cndisp;

    for(int i = 0; i < cndisp; ++i)
        dst[msg_disp_step * i] -= sum;
}
__kernel void one_iteration(__global T *u,    int u_step,
                            __global T *data, int data_step,
                            __global T *d,    __global T *l, __global T *r,
                            int t, int cols, int rows,
                            int cndisp, float cmax_disc_term, float cdisc_single_jump)
{
    const int y = get_global_id(1);
    const int x = ((get_global_id(0)) << 1) + ((y + t) & 1);

    if ((y > 0) && (y < rows - 1) && (x > 0) && (x < cols - 1))
    {
        u_step    /= sizeof(T);
        data_step /= sizeof(T);

        __global T *us = u + y * u_step + x;
        __global T *ds = d + y * u_step + x;
        __global T *ls = l + y * u_step + x;
        __global T *rs = r + y * u_step + x;
        const __global  T *dt = data + y * data_step + x;

        int msg_disp_step = u_step * rows;
        int data_disp_step = data_step * rows;

        message(us + u_step, ls      + 1, rs - 1, dt, us, msg_disp_step, data_disp_step, cndisp,
            cmax_disc_term, cdisc_single_jump);
        message(ds - u_step, ls      + 1, rs - 1, dt, ds, msg_disp_step, data_disp_step, cndisp,
            cmax_disc_term, cdisc_single_jump);

        message(us + u_step, ds - u_step, rs - 1, dt, rs, msg_disp_step, data_disp_step, cndisp,
            cmax_disc_term, cdisc_single_jump);
        message(us + u_step, ds - u_step, ls + 1, dt, ls, msg_disp_step, data_disp_step, cndisp,
            cmax_disc_term, cdisc_single_jump);
    }
}

///////////////////////////////////////////////////////////////
/////////////////////////// output ////////////////////////////
///////////////////////////////////////////////////////////////
__kernel void output(const __global T *u, int u_step,
                     const __global T *d, const __global T *l,
                     const __global T *r, const __global T *data,
                     __global T *disp, int disp_rows, int disp_cols, int disp_step,
                     int cndisp)
{
    const int x = get_global_id(0);
    const int y = get_global_id(1);

    if (y > 0 && y < disp_rows - 1 && x > 0 && x < disp_cols - 1)
    {
        u_step    /= sizeof(T);
        disp_step /= sizeof(T);
        const __global T *us = u + (y + 1) * u_step + x;
        const __global T *ds = d + (y - 1) * u_step + x;
        const __global T *ls = l + y * u_step + (x + 1);
        const __global T *rs = r + y * u_step + (x - 1);
        const __global T *dt = data + y * u_step + x;

        int disp_steps = disp_rows * u_step;

        int best = 0;
        float best_val = FLOAT_MAX;
        for (int d = 0; d < cndisp; ++d)
        {
            float val;
            val  = us[d * disp_steps];
            val += ds[d * disp_steps];
            val += ls[d * disp_steps];
            val += rs[d * disp_steps];
            val += dt[d * disp_steps];

            if (val < best_val)
            {
                best_val = val;
                best = d;
            }
        }

        (disp + y * disp_step)[x] = convert_short_sat(best);
    }
}


Removed commented-out code

Removed commented-out code

#define getIndex(i, j) (i) * width + (j)

__kernel void diffusion(__global float *currentGrid, int width) {
	int tx = get_global_id(0);
	int ty = get_global_id(1);

	if(tx > 0 && tx < width - 1 && ty > 0 && ty < width - 1) {
		float left = currentGrid[getIndex(tx - 1, ty)];
		float right = currentGrid[getIndex(tx + 1, ty)];
		float up = currentGrid[getIndex(tx, ty - 1)];
		float down = currentGrid[getIndex(tx, ty + 1)];

		currentGrid[getIndex(tx, ty)] = (left + right + up + down) * 0.25;
	}
}

#define getIndex(i, j) (i) * width + (j)

#define BLOCK_SIZE 4
#define TILE_SIZE 4

__kernel void diffusion(__global float *currentGrid, int width) {
	int tx = get_global_id(0);
	int ty = get_global_id(1);

	int lx = get_local_id(0);
	int ly = get_local_id(1);

	int bx = get_group_id(0);
	int by = get_group_id(1);

//	int begin = width * BLOCK_SIZE * by;
//	int end = begin + width - 1;
//	int step = BLOCK_SIZE;
//
//	float average = 100;
//	for(int i = begin; i < end; i += step) {
//		__local float subGrid[BLOCK_SIZE][BLOCK_SIZE];
//		subGrid[ly][lx] = currentGrid[i + width * ty + tx];
//		barrier(CLK_LOCAL_MEM_FENCE);
//		if(tx > 0 && tx < width - 1 && ty > 0 && ty < width - 1) {
//			float left, right, up, down;
//			if(lx == 0) {
//				left = currentGrid[getIndex(tx - 1, ty)];
//			} else if(lx == TILE_SIZE) {
//				right = currentGrid[getIndex(tx - 1, ty)];
//			} else {
//				left = subGrid[lx - 1][ly];
//				right = subGrid[lx + 1][ly];
//			}
//
//			if(ly == 0) {
//				up = currentGrid[getIndex(tx, ty - 1)];
//			} else if(ly == TILE_SIZE) {
//				down = currentGrid[getIndex(tx, ty - 1)];
//			} else {
//				up = subGrid[lx][ly - 1];
//				down = subGrid[lx + 1][ly + 1];
//			}
//
//			average = (left + right + up + down) * 0.25;
//			barrier(CLK_LOCAL_MEM_FENCE);
//		}
//
//	}
//
//	currentGrid[getIndex(tx, ty)] = average;

	if(tx > 0 && tx < width - 1 && ty > 0 && ty < width - 1) {
		float left = currentGrid[getIndex(tx - 1, ty)];
		float right = currentGrid[getIndex(tx + 1, ty)];
		float up = currentGrid[getIndex(tx, ty - 1)];
		float down = currentGrid[getIndex(tx, ty + 1)];
		currentGrid[getIndex(tx, ty)] = (left + right + up + down) * 0.25;
	}
}


Added a set-to-one function for kernels

Added a set-to-one function for kernels

// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
// project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
// width of 100 characters per line.
//
// Author(s):
//   Cedric Nugteren <www.cedricnugteren.nl>
//
// This file contains the common defines and type-defs for the CLBlast OpenCL kernels.
//
// =================================================================================================

// Enables loading of this file using the C++ pre-processor's #include (C++11 standard raw string
// literal). Comment-out this line for syntax-highlighting when developing.
R"(
// =================================================================================================

// Parameters set by the tuner or by the database. Here they are given a basic default value in case
// this file is used outside of the CLBlast library.
#ifndef PRECISION
  #define PRECISION 32      // Data-types: single or double precision, complex or regular
#endif

// =================================================================================================

// Enable support for double-precision
#if PRECISION == 64 || PRECISION == 6464
  #if __OPENCL_VERSION__ <= CL_VERSION_1_1
     #pragma OPENCL EXTENSION cl_khr_fp64: enable
  #endif
#endif

// Single-precision
#if PRECISION == 32
  typedef float real;
  typedef float2 real2;
  typedef float4 real4;
  typedef float8 real8;
  typedef float16 real16;
  #define ZERO 0.0f
  #define ONE 1.0f

// Double-precision
#elif PRECISION == 64
  typedef double real;
  typedef double2 real2;
  typedef double4 real4;
  typedef double8 real8;
  typedef double16 real16;
  #define ZERO 0.0
  #define ONE 1.0

// Complex single-precision
#elif PRECISION == 3232
  typedef struct cfloat {float x; float y;} real;
  typedef struct cfloat2 {real x; real y;} real2;
  typedef struct cfloat4 {real x; real y; real z; real w;} real4;
  typedef struct cfloat8 {real s0; real s1; real s2; real s3;
                          real s4; real s5; real s6; real s7;} real8;
  typedef struct cfloat16 {real s0; real s1; real s2; real s3;
                           real s4; real s5; real s6; real s7;
                           real s8; real s9; real sA; real sB;
                           real sC; real sD; real sE; real sF;} real16;
  #define ZERO 0.0f
  #define ONE 1.0f

// Complex Double-precision
#elif PRECISION == 6464
  typedef struct cdouble {double x; double y;} real;
  typedef struct cdouble2 {real x; real y;} real2;
  typedef struct cdouble4 {real x; real y; real z; real w;} real4;
  typedef struct cdouble8 {real s0; real s1; real s2; real s3;
                           real s4; real s5; real s6; real s7;} real8;
  typedef struct cdouble16 {real s0; real s1; real s2; real s3;
                            real s4; real s5; real s6; real s7;
                            real s8; real s9; real sA; real sB;
                            real sC; real sD; real sE; real sF;} real16;
  #define ZERO 0.0
  #define ONE 1.0
#endif

// =================================================================================================

// Don't use the non-IEEE754 compliant OpenCL built-in mad() instruction
#define USE_CL_MAD 0

// Sets a variable to zero
#if PRECISION == 3232 || PRECISION == 6464
  #define SetToZero(a) a.x = ZERO; a.y = ZERO
#else
  #define SetToZero(a) a = ZERO
#endif

// Sets a variable to one
#if PRECISION == 3232 || PRECISION == 6464
  #define SetToOne(a) a.x = ONE; a.y = ZERO
#else
  #define SetToOne(a) a = ONE
#endif

// Multiply two complex variables (used in the define below)
#if PRECISION == 3232 || PRECISION == 6464
  #define MulReal(a, b) a.x*b.x - a.y*b.y
  #define MulImag(a, b) a.x*b.y + a.y*b.x
#endif

// The scalar multiply-add function
#if PRECISION == 3232 || PRECISION == 6464
  #define MultiplyAdd(c, a, b) c.x += MulReal(a,b); c.y += MulImag(a,b)
#else
  #if USE_CL_MAD == 1
    #define MultiplyAdd(c, a, b) c = mad(a, b, c)
  #else
    #define MultiplyAdd(c, a, b) c += a * b
  #endif
#endif

// The scalar AXPBY function
#if PRECISION == 3232 || PRECISION == 6464
  #define AXPBY(e, a, b, c, d) e.x = MulReal(a,b) + MulReal(c,d); e.y = MulImag(a,b) + MulImag(c,d)
#else
  #define AXPBY(e, a, b, c, d) e = a*b + c*d
#endif

// The complex conjugate operation for complex transforms
#if PRECISION == 3232 || PRECISION == 6464
  #define COMPLEX_CONJUGATE(value) value.x = value.x; value.y = -value.y
#else
  #define COMPLEX_CONJUGATE(value) value = value
#endif

// =================================================================================================

// End of the C++11 raw string literal
)";

// =================================================================================================

// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
// project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
// width of 100 characters per line.
//
// Author(s):
//   Cedric Nugteren <www.cedricnugteren.nl>
//
// This file contains the common defines and type-defs for the CLBlast OpenCL kernels.
//
// =================================================================================================

// Enables loading of this file using the C++ pre-processor's #include (C++11 standard raw string
// literal). Comment-out this line for syntax-highlighting when developing.
R"(
// =================================================================================================

// Parameters set by the tuner or by the database. Here they are given a basic default value in case
// this file is used outside of the CLBlast library.
#ifndef PRECISION
  #define PRECISION 32      // Data-types: single or double precision, complex or regular
#endif

// =================================================================================================

// Enable support for double-precision
#if PRECISION == 64 || PRECISION == 6464
  #if __OPENCL_VERSION__ <= CL_VERSION_1_1
     #pragma OPENCL EXTENSION cl_khr_fp64: enable
  #endif
#endif

// Single-precision
#if PRECISION == 32
  typedef float real;
  typedef float2 real2;
  typedef float4 real4;
  typedef float8 real8;
  typedef float16 real16;
  #define ZERO 0.0f

// Double-precision
#elif PRECISION == 64
  typedef double real;
  typedef double2 real2;
  typedef double4 real4;
  typedef double8 real8;
  typedef double16 real16;
  #define ZERO 0.0

// Complex single-precision
#elif PRECISION == 3232
  typedef struct cfloat {float x; float y;} real;
  typedef struct cfloat2 {real x; real y;} real2;
  typedef struct cfloat4 {real x; real y; real z; real w;} real4;
  typedef struct cfloat8 {real s0; real s1; real s2; real s3;
                          real s4; real s5; real s6; real s7;} real8;
  typedef struct cfloat16 {real s0; real s1; real s2; real s3;
                           real s4; real s5; real s6; real s7;
                           real s8; real s9; real sA; real sB;
                           real sC; real sD; real sE; real sF;} real16;
  #define ZERO 0.0f

// Complex Double-precision
#elif PRECISION == 6464
  typedef struct cdouble {double x; double y;} real;
  typedef struct cdouble2 {real x; real y;} real2;
  typedef struct cdouble4 {real x; real y; real z; real w;} real4;
  typedef struct cdouble8 {real s0; real s1; real s2; real s3;
                           real s4; real s5; real s6; real s7;} real8;
  typedef struct cdouble16 {real s0; real s1; real s2; real s3;
                            real s4; real s5; real s6; real s7;
                            real s8; real s9; real sA; real sB;
                            real sC; real sD; real sE; real sF;} real16;
  #define ZERO 0.0
#endif

// =================================================================================================

// Don't use the non-IEEE754 compliant OpenCL built-in mad() instruction
#define USE_CL_MAD 0

// Sets a variable to zero
#if PRECISION == 3232 || PRECISION == 6464
  #define SetToZero(a) a.x = ZERO; a.y = ZERO
#else
  #define SetToZero(a) a = ZERO
#endif

// Multiply two complex variables (used in the define below)
#if PRECISION == 3232 || PRECISION == 6464
  #define MulReal(a, b) a.x*b.x - a.y*b.y
  #define MulImag(a, b) a.x*b.y + a.y*b.x
#endif

// The scalar multiply-add function
#if PRECISION == 3232 || PRECISION == 6464
  #define MultiplyAdd(c, a, b) c.x += MulReal(a,b); c.y += MulImag(a,b)
#else
  #if USE_CL_MAD == 1
    #define MultiplyAdd(c, a, b) c = mad(a, b, c)
  #else
    #define MultiplyAdd(c, a, b) c += a * b
  #endif
#endif

// The scalar AXPBY function
#if PRECISION == 3232 || PRECISION == 6464
  #define AXPBY(e, a, b, c, d) e.x = MulReal(a,b) + MulReal(c,d); e.y = MulImag(a,b) + MulImag(c,d)
#else
  #define AXPBY(e, a, b, c, d) e = a*b + c*d
#endif

// The complex conjugate operation for complex transforms
#if PRECISION == 3232 || PRECISION == 6464
  #define COMPLEX_CONJUGATE(value) value.x = value.x; value.y = -value.y
#else
  #define COMPLEX_CONJUGATE(value) value = value
#endif

// =================================================================================================

// End of the C++11 raw string literal
)";

// =================================================================================================


reformat code for readibility

reformat code for readibility

/*ckwg +5
 * Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

__constant sampler_t imageSampler = CLK_NORMALIZED_COORDS_FALSE |
                                    CLK_ADDRESS_CLAMP_TO_EDGE |
                                    CLK_FILTER_NEAREST;

// A Brief descriptor is represented as 128 bits
//using 4 32 bit integers in the int4 datat type
typedef int4 brief_descr;

// Hamming distance between brief descriptors.
// This function counts the number of bits (pop count)
// between 4 32 ints in parallel then sums the result
int brief_dist(brief_descr b1, brief_descr b2)
{
  int4 v = b1 ^ b2; //Find the bits that differ

  //Count the bits in v in parallel
  v = v - ((v >> 1) & 0x55555555);
  v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
  int4 c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;

  //Sum the counts
  return c.x + c.y + c.z + c.w;
}

__kernel void track(__global    int2        *kpts2,
                    __read_only image2d_t    kptmap1,
                    __global    brief_descr *descriptors1,
                    __global    brief_descr *descriptors2,
                    __global    int         *tracks,
                                int          window)
{
  //index into kpts1 and descriptors1
  int index = get_global_id(0);
  brief_descr descr = descriptors2[index];

  //kptmap is 1/2 the size of the original image
  int2 pixel = kpts2[index] / 2;

  int2 loc;
  int closest_dist = 15;
  int closest_index = -1;
  for (loc.x = pixel.x - window; loc.x <= pixel.x + window; loc.x++)
  {
    for (loc.y = pixel.y - window; loc.y <= pixel.y + window; loc.y++)
    {
      int val = read_imagei(kptmap1, imageSampler, loc).x;
      if (val > -1)
      {
        int dist = brief_dist(descriptors1[val], descr);
        if (dist <= closest_dist)
        {
          closest_dist = dist;
          closest_index = val;
        }
      }
    }
  }

  tracks[index] = closest_index;
}

/*ckwg +5
 * Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

__constant sampler_t imageSampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE | CLK_FILTER_NEAREST;

// A Brief descriptor is represented as 128 bits
//using 4 32 bit integers in the int4 datat type
typedef int4 brief_descr;

//Hamming distance between brief descriptors.  This function counts the number of bits
//(pop count) between 4 32 ints in parallel then sums the result
int brief_dist(brief_descr b1, brief_descr b2)
{
  int4 v = b1 ^ b2; //Find the bits that differ

  //Count the bits in v in parallel
  v = v - ((v >> 1) & 0x55555555);
  v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
  int4 c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;

  //Sum the counts
  return c.x + c.y + c.z + c.w;
}

__kernel void track(__global int2 *kpts2, __read_only image2d_t kptmap1,
                    __global brief_descr *descriptors1, __global brief_descr *descriptors2,
                    __global int *tracks, int window)
{
  //index into kpts1 and descriptors1
  int index = get_global_id(0);
  brief_descr descr = descriptors2[index];

  //kptmap is 1/2 the size of the original image
  int2 pixel = kpts2[index] / 2;

  int2 loc;
  int closest_dist = 15;
  int closest_index = -1;
  for (loc.x = pixel.x - window; loc.x <= pixel.x + window; loc.x++)
  {
    for (loc.y = pixel.y - window; loc.y <= pixel.y + window; loc.y++)
    {
      int val = read_imagei(kptmap1, imageSampler, loc).x;
      if (val > -1)
      {
        int dist = brief_dist(descriptors1[val], descr);
        if (dist <= closest_dist)
        {
          closest_dist = dist;
          closest_index = val;
        }
      }
    }
  }

  tracks[index] = closest_index;
}