sixtracklib/opencl: fix issue with no longer present num_particles parameter in the NS(BeamMonitor) assignment OpenCL kernel (debug version)

#ifndef SIXTRACKLIB_OPENCL_KERNELS_BE_MONITORS_ASSIGN_OUT_BUFFER_DEBUG_KERNEL_CL__
#define SIXTRACKLIB_OPENCL_KERNELS_BE_MONITORS_ASSIGN_OUT_BUFFER_DEBUG_KERNEL_CL__

#if !defined( SIXTRL_NO_INCLUDES )
    #include "sixtracklib/opencl/internal/default_compile_options.h"

    #include "sixtracklib/common/definitions.h"
    #include "sixtracklib/common/buffer/managed_buffer_minimal.h"
    #include "sixtracklib/common/buffer/managed_buffer_remap.h"
    #include "sixtracklib/common/internal/particles_defines.h"
    #include "sixtracklib/common/particles.h"
    #include "sixtracklib/common/be_monitor/be_monitor.h"
    #include "sixtracklib/common/be_monitor/output_buffer.h"
#endif /* !defined( SIXTRL_NO_INCLUDES ) */

#pragma OPENCL_EXTENSION cl_khr_int32_extended_atomics

__kernel void NS(BeamMonitor_assign_out_buffer_from_offset_debug_opencl)(
    SIXTRL_BUFFER_DATAPTR_DEC unsigned char* SIXTRL_RESTRICT beam_elements_buf,
    SIXTRL_BUFFER_DATAPTR_DEC unsigned char* SIXTRL_RESTRICT out_buffer,
    SIXTRL_UINT64_T const out_particles_block_offset,
    SIXTRL_BUFFER_DATAPTR_DEC SIXTRL_INT32_T* SIXTRL_RESTRICT ptr_success_flag );

__kernel void NS(BeamMonitor_clear_all_line_obj_debug_opencl)(
    SIXTRL_BUFFER_DATAPTR_DEC unsigned char* SIXTRL_RESTRICT beam_elements_buf,
    SIXTRL_BUFFER_DATAPTR_DEC SIXTRL_INT32_T* SIXTRL_RESTRICT ptr_success_flag );

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

__kernel void NS(BeamMonitor_assign_out_buffer_from_offset_debug_opencl)(
    SIXTRL_BUFFER_DATAPTR_DEC unsigned char* SIXTRL_RESTRICT beam_elements_buf,
    SIXTRL_BUFFER_DATAPTR_DEC unsigned char* SIXTRL_RESTRICT out_buffer,
    SIXTRL_UINT64_T const out_particles_block_offset,
    SIXTRL_BUFFER_DATAPTR_DEC SIXTRL_INT32_T* SIXTRL_RESTRICT ptr_success_flag )
{
    typedef NS(buffer_size_t) buf_size_t;
    buf_size_t const slot_size = ( size_t )8u;

    SIXTRL_INT32_T success_flag = ( SIXTRL_INT32_T )-1;

    if( ( !NS(ManagedBuffer_needs_remapping)( beam_elements_buf, slot_size ) ) &&
        ( !NS(ManagedBuffer_needs_remapping)( out_buffer, slot_size ) ) &&
        (  NS(ManagedBuffer_get_num_objects)( out_buffer, slot_size ) >=
            out_particles_block_offset ) )
    {
        size_t const gid_to_assign_out_buffer = ( size_t )0u;
        size_t const global_id = get_global_id( 0 );

        success_flag = ( SIXTRL_INT32_T )0u;

        if( global_id == gid_to_assign_out_buffer )
        {
            success_flag = NS(BeamMonitor_assign_managed_particles_out_buffer)(
                beam_elements_buf, out_buffer, out_particles_block_offset, slot_size );
        }
    }

    if( ( success_flag != 0 ) && ( ptr_success_flag != SIXTRL_NULLPTR ) )
    {
        atomic_or( ptr_success_flag, success_flag );
    }

    return;
}

__kernel void NS(BeamMonitor_clear_all_line_obj_debug_opencl)(
    SIXTRL_BUFFER_DATAPTR_DEC unsigned char* SIXTRL_RESTRICT beam_elements_buf,
    SIXTRL_BUFFER_DATAPTR_DEC SIXTRL_INT32_T* SIXTRL_RESTRICT ptr_success_flag )
{
    typedef NS(buffer_size_t) buf_size_t;
    typedef SIXTRL_BUFFER_OBJ_ARGPTR_DEC NS(Object)* obj_iter_t;
    typedef SIXTRL_BE_ARGPTR_DEC NS(BeamMonitor)* ptr_beam_monitor_t;

    SIXTRL_INT32_T success_flag = ( SIXTRL_INT32_T )-1;
    buf_size_t const  slot_size = ( buf_size_t )8u;

    if( ( !NS(ManagedBuffer_needs_remapping)( beam_elements_buf, slot_size ) ) &&
        (  NS(ManagedBuffer_get_objects_index_begin)(
                beam_elements_buf, slot_size ) != SIXTRL_NULLPTR ) &&
        (  NS(ManagedBuffer_get_num_objects)( beam_elements_buf, slot_size ) >
            ( buf_size_t )0u ) )
    {
        buf_size_t beam_element_id = get_global_id( 0 );
        buf_size_t const    stride = get_global_size( 0 );

        buf_size_t const num_beam_elements =
            NS(ManagedBuffer_get_num_objects)( beam_elements_buf, slot_size );

        obj_iter_t be_begin = NS(ManagedBuffer_get_objects_index_begin)(
            beam_elements_buf, slot_size );

        success_flag = ( SIXTRL_INT32_T )0u;

        SIXTRL_ASSERT( ( be_begin + num_beam_elements ) !=
            NS(ManagedBuffer_get_objects_index_end)(
                beam_elements_buf, slot_size ) );

        for( ; beam_element_id < num_beam_elements ; beam_element_id += stride )
        {
            obj_iter_t be_it = be_begin + beam_element_id;

            if( NS(Object_get_type_id)( be_it ) == NS(OBJECT_TYPE_BEAM_MONITOR) )
            {
                ptr_beam_monitor_t beam_monitor = ( ptr_beam_monitor_t)( uintptr_t
                    )NS(Object_get_begin_addr)( be_it );

                if( beam_monitor != SIXTRL_NULLPTR )
                {
                    SIXTRL_ASSERT( NS(Object_get_size)( be_it ) >=
                           sizeof( NS(BeamMonitor) ) );

                    NS(BeamMonitor_clear)( beam_monitor );
                }
                else
                {
                    success_flag = -1;
                }
            }
        }
    }

    if( ( success_flag != ( SIXTRL_INT32_T )0 ) &&
        ( ptr_success_flag != SIXTRL_NULLPTR ) )
    {
        atomic_or( ptr_success_flag, success_flag );
    }

    return;
}

#endif /* SIXTRACKLIB_OPENCL_KERNELS_BE_MONITORS_ASSIGN_OUT_BUFFER_DEBUG_KERNEL_CL__ */

/* end: sixtracklib/opencl/kernels/be_monitors_assign_out_buffer_debug.cl */

#ifndef SIXTRACKLIB_OPENCL_KERNELS_BE_MONITORS_ASSIGN_OUT_BUFFER_DEBUG_KERNEL_CL__
#define SIXTRACKLIB_OPENCL_KERNELS_BE_MONITORS_ASSIGN_OUT_BUFFER_DEBUG_KERNEL_CL__

#if !defined( SIXTRL_NO_INCLUDES )
    #include "sixtracklib/opencl/internal/default_compile_options.h"

    #include "sixtracklib/common/definitions.h"
    #include "sixtracklib/common/buffer/managed_buffer_minimal.h"
    #include "sixtracklib/common/buffer/managed_buffer_remap.h"
    #include "sixtracklib/common/internal/particles_defines.h"
    #include "sixtracklib/common/particles.h"
    #include "sixtracklib/common/be_monitor/be_monitor.h"
    #include "sixtracklib/common/be_monitor/output_buffer.h"
#endif /* !defined( SIXTRL_NO_INCLUDES ) */

#pragma OPENCL_EXTENSION cl_khr_int32_extended_atomics

__kernel void NS(BeamMonitor_assign_out_buffer_from_offset_debug_opencl)(
    SIXTRL_BUFFER_DATAPTR_DEC unsigned char* SIXTRL_RESTRICT beam_elements_buf,
    SIXTRL_BUFFER_DATAPTR_DEC unsigned char* SIXTRL_RESTRICT out_buffer,
    SIXTRL_UINT64_T const out_particles_block_offset,
    SIXTRL_BUFFER_DATAPTR_DEC SIXTRL_INT32_T* SIXTRL_RESTRICT ptr_success_flag );

__kernel void NS(BeamMonitor_clear_all_line_obj_debug_opencl)(
    SIXTRL_BUFFER_DATAPTR_DEC unsigned char* SIXTRL_RESTRICT beam_elements_buf,
    SIXTRL_BUFFER_DATAPTR_DEC SIXTRL_INT32_T* SIXTRL_RESTRICT ptr_success_flag );

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

__kernel void NS(BeamMonitor_assign_out_buffer_from_offset_debug_opencl)(
    SIXTRL_BUFFER_DATAPTR_DEC unsigned char* SIXTRL_RESTRICT beam_elements_buf,
    SIXTRL_BUFFER_DATAPTR_DEC unsigned char* SIXTRL_RESTRICT out_buffer,
    SIXTRL_UINT64_T const out_particles_block_offset,
    SIXTRL_BUFFER_DATAPTR_DEC SIXTRL_INT32_T* SIXTRL_RESTRICT ptr_success_flag )
{
    typedef NS(buffer_size_t) buf_size_t;
    buf_size_t const slot_size = ( size_t )8u;

    SIXTRL_INT32_T success_flag = ( SIXTRL_INT32_T )-1;

    if( ( num_particles > ( SIXTRL_UINT64_T )0u ) &&
        ( !NS(ManagedBuffer_needs_remapping)( beam_elements_buf, slot_size ) ) &&
        ( !NS(ManagedBuffer_needs_remapping)( out_buffer, slot_size ) ) &&
        (  NS(ManagedBuffer_get_num_objects)( out_buffer, slot_size ) >=
            out_particles_block_offset ) )
    {
        size_t const gid_to_assign_out_buffer = ( size_t )0u;
        size_t const global_id = get_global_id( 0 );

        success_flag = ( SIXTRL_INT32_T )0u;

        if( global_id == gid_to_assign_out_buffer )
        {
            success_flag = NS(BeamMonitor_assign_managed_out_buffer)(
                beam_elements_buf, out_buffer, out_particles_block_offset, slot_size );
        }
    }

    if( ( success_flag != 0 ) && ( ptr_success_flag != SIXTRL_NULLPTR ) )
    {
        atomic_or( ptr_success_flag, success_flag );
    }

    return;
}

__kernel void NS(BeamMonitor_clear_all_line_obj_debug_opencl)(
    SIXTRL_BUFFER_DATAPTR_DEC unsigned char* SIXTRL_RESTRICT beam_elements_buf,
    SIXTRL_BUFFER_DATAPTR_DEC SIXTRL_INT32_T* SIXTRL_RESTRICT ptr_success_flag )
{
    typedef NS(buffer_size_t) buf_size_t;
    typedef SIXTRL_BUFFER_OBJ_ARGPTR_DEC NS(Object)* obj_iter_t;
    typedef SIXTRL_BE_ARGPTR_DEC NS(BeamMonitor)* ptr_beam_monitor_t;

    SIXTRL_INT32_T success_flag = ( SIXTRL_INT32_T )-1;
    buf_size_t const  slot_size = ( buf_size_t )8u;

    if( ( !NS(ManagedBuffer_needs_remapping)( beam_elements_buf, slot_size ) ) &&
        (  NS(ManagedBuffer_get_objects_index_begin)(
                beam_elements_buf, slot_size ) != SIXTRL_NULLPTR ) &&
        (  NS(ManagedBuffer_get_num_objects)( beam_elements_buf, slot_size ) >
            ( buf_size_t )0u ) )
    {
        buf_size_t beam_element_id = get_global_id( 0 );
        buf_size_t const    stride = get_global_size( 0 );

        buf_size_t const num_beam_elements =
            NS(ManagedBuffer_get_num_objects)( beam_elements_buf, slot_size );

        obj_iter_t be_begin = NS(ManagedBuffer_get_objects_index_begin)(
            beam_elements_buf, slot_size );

        success_flag = ( SIXTRL_INT32_T )0u;

        SIXTRL_ASSERT( ( be_begin + num_beam_elements ) !=
            NS(ManagedBuffer_get_objects_index_end)(
                beam_elements_buf, slot_size ) );

        for( ; beam_element_id < num_beam_elements ; beam_element_id += stride )
        {
            obj_iter_t be_it = be_begin + beam_element_id;

            if( NS(Object_get_type_id)( be_it ) == NS(OBJECT_TYPE_BEAM_MONITOR) )
            {
                ptr_beam_monitor_t beam_monitor = ( ptr_beam_monitor_t)( uintptr_t
                    )NS(Object_get_begin_addr)( be_it );

                if( beam_monitor != SIXTRL_NULLPTR )
                {
                    SIXTRL_ASSERT( NS(Object_get_size)( be_it ) >=
                           sizeof( NS(BeamMonitor) ) );

                    NS(BeamMonitor_clear)( beam_monitor );
                }
                else
                {
                    success_flag = -1;
                }
            }
        }
    }

    if( ( success_flag != ( SIXTRL_INT32_T )0 ) &&
        ( ptr_success_flag != SIXTRL_NULLPTR ) )
    {
        atomic_or( ptr_success_flag, success_flag );
    }

    return;
}

#endif /* SIXTRACKLIB_OPENCL_KERNELS_BE_MONITORS_ASSIGN_OUT_BUFFER_DEBUG_KERNEL_CL__ */

/* end: sixtracklib/opencl/kernels/be_monitors_assign_out_buffer_debug.cl */


FIX: OpenCL call to distance replaced by sqrt

// OpenCL Kernel
// https://www.khronos.org/files/opencl-1-2-quick-reference-card.pdf

kernel void convolve_image(__read_only image2d_t image,
                           __read_only image2d_t pattern,
                           __global __write_only float* output,
                           sampler_t sampler,
                           const int2 top_left_rc,   // image (row, column)
                           const int image_start_r,  // where in the image row to start writing (for partitions)
                           const int image_end_r)    // end row writing (for partitions)
{
   // From a birds-eye-view what this kernel does is to compute a similarity
   // measure almost like a convolve operation, but with a distance measure
   // that uses the alpha channel of the pattern as a mask (to ignore or
   // down-weight parts of the pattern) and further uses a squared distance
   // measure. One call to this method computes a single pixel
   // in the `output` image (`output` is our region-of-interest (ROI)). The
   // output just contains float values (NOT in scale 0..1) for how similar
   // pattern and image are at that pixel. Lower value mean "more similar".
   // `top_left_rc` defines to which pixel coordinate the (0, 0) pixel in the
   // output corresponds.

    // Position (row, column) of the pixel in the output image.
    // Note, that OpenCL has uses column-major ("fortran"-style) storage, so
    // in the end we have to access the pixel data (through a sampler) in
    // (column, row) order. But we stick to naming like "C"-style row-major
    // ordering and just do the flip in the two nested for-loops in the loop
    // variables c and r, which are then used according to OpenCL's convention.
    const int2 pos = {get_global_id(0), get_global_id(1)};

    // The width of the image
    const int image_width = get_image_width(image);

    // The pattern should be at least 3x3 and have an odd width and height
    const int pattern_half_w = (get_image_width(pattern)-1) / 2;
    const int pattern_half_h = (get_image_height(pattern)-1) / 2;

    // 4-tuple of the RGBA values from the pattern image and RRB of the image.
    float4 pattern_color = (float4)(0.0, 0.0, 0.0, 0.0);
    float4 image_color = (float4)(0.0, 0.0, 0.0, 0.0);

    // The (column, row) of the center pixel in the pattern is computed
    // Note, that later one we use this as (column, row), therefore we switch
    // already here the .s0 and .s1 assignment
    // (s0 is the first entry, s1 second)
    int2 pattern_pos_cr = (int2)(0, 0);
    pattern_pos_cr.s1 = -top_left_rc.s0 - pos.s0 + pattern_half_h; // row
    pattern_pos_cr.s0 = -top_left_rc.s1 - pos.s1 + pattern_half_w; // column

    // value for the output pixel we are going to compute in this kernel
    float value = 0.0;
    // the distance in the color-space between the image and the pattern
    float dist = 0.0f;
    const float max_dist = sqrt(3.0);

    // Go though all pixel of the pattern image
    for (int r = image_start_r; r < image_end_r; r++) {

        for (int c = 0; c < image_width; c++) {

            pattern_color = read_imagef(pattern, sampler, pattern_pos_cr + (int2)(c, r));

            if(pattern_color.w > 0.0f) {
                // Use the alpha value `.w` from an RGBA image (pattern) as
                // weight and compute the `distance` which is the squared
                // absolute difference
                image_color = read_imagef(image, sampler, (int2)(c, r));
                dist = fast_distance(pattern_color.xyz, image_color.xyz);
                value += (1-pattern_color.w) * max_dist + pattern_color.w * dist;
            } else {
                // Just add a constant that represents the maximal possible
                // difference between image and pattern for a single pixel.
                // E.g. from white (1,1,1) to black (0,0,0).
                value += max_dist;
            }
        }
    }

    output[pos.s0 * get_global_size(1) + pos.s1] = value;
}

// OpenCL Kernel
// https://www.khronos.org/files/opencl-1-2-quick-reference-card.pdf

kernel void convolve_image(__read_only image2d_t image,
                           __read_only image2d_t pattern,
                           __global __write_only float* output,
                           sampler_t sampler,
                           const int2 top_left_rc,   // image (row, column)
                           const int image_start_r,  // where in the image row to start writing (for partitions)
                           const int image_end_r)    // end row writing (for partitions)
{
   // From a birds-eye-view what this kernel does is to compute a similarity
   // measure almost like a convolve operation, but with a distance measure
   // that uses the alpha channel of the pattern as a mask (to ignore or
   // down-weight parts of the pattern) and further uses a squared distance
   // measure. One call to this method computes a single pixel
   // in the `output` image (`output` is our region-of-interest (ROI)). The
   // output just contains float values (NOT in scale 0..1) for how similar
   // pattern and image are at that pixel. Lower value mean "more similar".
   // `top_left_rc` defines to which pixel coordinate the (0, 0) pixel in the
   // output corresponds.

    // Position (row, column) of the pixel in the output image.
    // Note, that OpenCL has uses column-major ("fortran"-style) storage, so
    // in the end we have to access the pixel data (through a sampler) in
    // (column, row) order. But we stick to naming like "C"-style row-major
    // ordering and just do the flip in the two nested for-loops in the loop
    // variables c and r, which are then used according to OpenCL's convention.
    const int2 pos = {get_global_id(0), get_global_id(1)};

    // The width of the image
    const int image_width = get_image_width(image);

    // The pattern should be at least 3x3 and have an odd width and height
    const int pattern_half_w = (get_image_width(pattern)-1) / 2;
    const int pattern_half_h = (get_image_height(pattern)-1) / 2;

    // 4-tuple of the RGBA values from the pattern image and RRB of the image.
    float4 pattern_color = (float4)(0.0, 0.0, 0.0, 0.0);
    float4 image_color = (float4)(0.0, 0.0, 0.0, 0.0);

    // The (column, row) of the center pixel in the pattern is computed
    // Note, that later one we use this as (column, row), therefore we switch
    // already here the .s0 and .s1 assignment
    // (s0 is the first entry, s1 second)
    int2 pattern_pos_cr = (int2)(0, 0);
    pattern_pos_cr.s1 = -top_left_rc.s0 - pos.s0 + pattern_half_h; // row
    pattern_pos_cr.s0 = -top_left_rc.s1 - pos.s1 + pattern_half_w; // column

    // value for the output pixel we are going to compute in this kernel
    float value = 0.0;
    // the distance in the color-space between the image and the pattern
    float dist = 0.0f;
    const float max_dist = distance(1+1+1);

    // Go though all pixel of the pattern image
    for (int r = image_start_r; r < image_end_r; r++) {

        for (int c = 0; c < image_width; c++) {

            pattern_color = read_imagef(pattern, sampler, pattern_pos_cr + (int2)(c, r));

            if(pattern_color.w > 0.0f) {
                // Use the alpha value `.w` from an RGBA image (pattern) as
                // weight and compute the `distance` which is the squared
                // absolute difference
                image_color = read_imagef(image, sampler, (int2)(c, r));
                dist = fast_distance(pattern_color.xyz, image_color.xyz);
                value += (1-pattern_color.w) * max_dist + pattern_color.w * dist;
            } else {
                // Just add a constant that represents the maximal possible
                // difference between image and pattern for a single pixel.
                // E.g. from white (1,1,1) to black (0,0,0).
                value += max_dist;
            }
        }
    }

    output[pos.s0 * get_global_size(1) + pos.s1] = value;
}


find max number of bit planes in code block

/*  Copyright 2014 Aaron Boxer

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#include "ocl_platform.cl"

/*

BPC Scan Pattern

Xx4 stripes

The stripes are scanned from top to bottom, and the columns within a
stripe are scanned from left to right.

*/

#define BOUNDARY 1

CONSTANT sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE  | CLK_FILTER_NEAREST;

void KERNEL run(write_only image2d_t R,
						 write_only image2d_t G,
						 write_only image2d_t B,
						 write_only image2d_t A , const unsigned int  width, const unsigned int height) {

	// Red channel

    //find maximum number of bits in code block
	LOCAL char msbScratch[CODEBLOCKX];

    // between one and 32 - zero value indicates that this code block is identically zero

	int2 posIn = (int2)(getLocalId(0) + getGlobalId(0)*CODEBLOCKX,  getGlobalId(1)*CODEBLOCKY);
	int maxVal = -2147483647-1;
	for (int i = 0; i < CODEBLOCKY; ++i) {
		maxVal = max(maxVal, read_imagei(R, sampler, posIn).x);
		posIn.y++;
	}

	char msbWI = 32 - clz(maxVal);
	msbScratch[getLocalId(0)] =msbWI;
	localMemoryFence();

	//group by twos
	if ( (getLocalId(0)&1) == 0) {
		msbWI = max(msbWI, msbScratch[getLocalId(0)+1]);
	}
	localMemoryFence();

	//group by fours
	if ( (getLocalId(0)&3) == 0) {
		msbWI = max(msbWI, msbScratch[getLocalId(0)+2]);
	}
	localMemoryFence();

	//group by eights
	if ( (getLocalId(0)&7) == 0) {
		msbWI = max(msbWI, msbScratch[getLocalId(0)+4]);
	}
	localMemoryFence();

	//group by 16ths
	if ( (getLocalId(0)&15) == 0) {
		msbWI = max(msbWI, msbScratch[getLocalId(0)+8]);
	}
	localMemoryFence();

	if (getLocalId(0) == 0) {
		msbScratch[0] = max(msbWI, msbScratch[16]);  //crashes here with access violation while reading location .....
	}
	localMemoryFence();

}

/*  Copyright 2014 Aaron Boxer

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#include "ocl_platform.cl"

/*

BPC Scan Pattern

Xx4 stripes

The stripes are scanned from top to bottom, and the columns within a
stripe are scanned from left to right.

*/

#define BOUNDARY 1

CONSTANT sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE  | CLK_FILTER_NEAREST;

void KERNEL run(write_only image2d_t R,
						 write_only image2d_t G,
						 write_only image2d_t B,
						 write_only image2d_t A , const unsigned int  width, const unsigned int height) {

    //find max bit plane number
	LOCAL char msb;
	LOCAL char msbScratch[CODEBLOCKX];

	msb = 0;							// between one and 32 - zero value indicates that this code block is identically zero
	msbScratch[getLocalId(0)] = 0;

	int2 posIn = (int2)(getLocalId(0) + getGlobalId(0)*CODEBLOCKX,  getGlobalId(1)*CODEBLOCKY);
	int4 max = -2147483647-1;
	for (int i = 0; i < CODEBLOCKY; ++i) {
		int4 temp = read_imagei(R, sampler, posIn);
		posIn.y++;
	}

	posIn = (int2)(getLocalId(0) + getGlobalId(0)*CODEBLOCKX,  getGlobalId(1)*CODEBLOCKY);
	for (int i = 0; i < CODEBLOCKY; ++i) {
		int4 temp = read_imagei(G, sampler, posIn);
		posIn.y++;
	}
	posIn = (int2)(getLocalId(0) + getGlobalId(0)*CODEBLOCKX,  getGlobalId(1)*CODEBLOCKY);
	for (int i = 0; i < CODEBLOCKY; ++i) {
		int4 temp = read_imagei(B, sampler, posIn);
		posIn.y++;
	}
	posIn = (int2)(getLocalId(0) + getGlobalId(0)*CODEBLOCKX,  getGlobalId(1)*CODEBLOCKY);
	for (int i = 0; i < CODEBLOCKY; ++i) {
		int4 temp = read_imagei(A, sampler, posIn);
		posIn.y++;
	}

	/*

	int4 pixelMsb = 32 - clz(val);  // between one and 32 - zero value indicates that this pixel has zero magnitude
	int currentBit = 32;            // between one and 32

	// wait until all work items have unset msb
	localMemoryFence();

	while(!msb && currentBit) {
	     if (pixelMsb.x == currentBit){
		    msb = currentBit;
		}
		// wait to see if any work item has set msb in this iteration
		localMemoryFence();

        currentBit--;
	}
	//now we know the msb for the x channel of this code block
	if (!msb)
		return;
*/

}


Fix layer_deltas kernel

Fix layer_deltas kernel

/* clang-format off */
/**
 *
 * Calculate deltas*activation_func_derivative of previous layer.
 *
 * In following notation (l), (l-1) describes relative layer and [...] lower indices.
 *
 * Algo for delta_ijn on layer (l-1), where:
 *   i = 0..output_w(l-1),
 *   j = 0..output_h(l-1),
 *   n = 0..filter_count(l-1):
 *
 * delta[i,j,n](l-1) = 0
 * for a = 0..spatial_size(l+1):
 *   for b = 0..spatial_size(l+1):
 *     for k = 0..filter_count(l+1):
 *       delta[i,j,n](l-1) += \
 *         w[abnk](l-1)               # (1) weight of edge between [i,j,n](l-1) and [i+a,j+b,k](l)
 *         * delta[i-a,j-b,k](l)      # (2) error term for [i-a,j-b,k](l). minus since we have point (i,j) and we asking: 'which output point are we affecting with w[a,b,_,_]'
 *         #* f`( x[i+a,j+b,n](l-1) )  # (3) derivative of activation function
 *         * f`(x[i,j,n](l-1) )       # (3) derivative of activation function at measured point
 *
 * TODO in (3) should index be x[i+a,j+b,n] or x[i,j,n]?
 * TODO in popular notation it's [i-a,j-b,_], is this just because matlab's
 *      native conv2 expects transposition ?
 *
 * TODO send layer_out as int2, not pair of ints
 *
 * macros:
 * 	CURRENT_FILTER_COUNT                   filter_count(l-1)
 *
 * @param  float*      deltas_next_layer   size: output_w(l) * output_w(l) * filter_count(l)
 * @param  float*      layer_output        size: output_w(l-1) * output_w(l-1) * filter_count(l-1)
 * @param  float*      target              size: output_w(l-1) * output_w(l-1) * filter_count(l-1)
 * @param  float*      W                   weights between (l-1) and (l).
 *                                         WARN: w3 is between (l2) and (l3), w2 -> (l1) and (l2), w1 -> (input) and (l1)
 *                                         size: f_spatial_size*f_spatial_size*filter_count(l-1)*filter_count(l)
 * @param  uint        f_spatial_size      spatial/kernel size for (l-1)
 * @param  uint        f_next_spatial_size spatial/kernel size for (l)
 * @param  uint        n_next_filter_cnt   filter_count(l)
 * @param  uint        layer_out_w         output_w(l-1)
 * @param  uint        layer_out_h         output_h(l-1)
 * @return {[type]}                        [description]
 */
/* clang-format on */
__kernel void main(__read_only __global float* deltas_next_layer,  //
                   __read_only __global float* layer_output,       //
                   __global float* target,                         //
                   __read_only __global float* W,                  //
                   uint f_spatial_size,                            //
                   uint f_next_spatial_size,                       //
                   uint n_next_filter_cnt,                         //
                   uint layer_out_w, uint layer_out_h) {
  // x=col=i; range: 0..layer_out_w
  // y=row=j; range: 0..layer_out_h
  const int2 pos = {get_global_id(0), get_global_id(1)};
  const int2 out_dim = {layer_out_w, layer_out_h};
  const int idx = ((pos.y * out_dim.x) + pos.x) * CURRENT_FILTER_COUNT;
  const int2 next_layer_out = {out_dim.x - f_next_spatial_size + 1,
                               out_dim.y - f_next_spatial_size + 1};

  // zeroed result cache and read read output values for output[i,j,n]
  float delta_for_filter[CURRENT_FILTER_COUNT];
  float activation_func_derivatives[CURRENT_FILTER_COUNT];

  // range check for i,j
  if (pos.x >= 0 && pos.x < out_dim.x &&  //
      pos.y >= 0 && pos.y < out_dim.y) {
    // fill tmp buffer values
    for (size_t n = 0; n < CURRENT_FILTER_COUNT; n++) {
      delta_for_filter[n] = 0.0f;
      // (3) f`( x[i,j,n](l-1) )
      float y_ijn = layer_output[idx + n];
      activation_func_derivatives[n] = y_ijn > 0.0f ? 1.0f : 0.0f;
    }

    for (size_t dy = 0; dy < f_next_spatial_size; dy++) {
      for (size_t dx = 0; dx < f_next_spatial_size; dx++) {
        // NOTE: dy=a, dx=b
        int2 next_layer_pos = {pos.x - dx, pos.y - dy};
        size_t w_idx_2D = ((dy * f_next_spatial_size) + dx) *
                          n_next_filter_cnt * CURRENT_FILTER_COUNT;

        for (size_t k = 0; k < n_next_filter_cnt; k++) {
          // (2) delta[i+a,j+b,k](l)
          // this requires us to map curent output_pos to next layer coords,
          // but some of the point may not be in range. f.e. point(i=0,j=0) does
          // not affect output with w[a,b] if a!=0 && b!=0
          int next_layer_idx =
              ((next_layer_pos.y * next_layer_out.x) + next_layer_pos.x) *
              n_next_filter_cnt;
          bool in_range =
              next_layer_pos.x >= 0 && next_layer_pos.x < next_layer_out.x &&
              next_layer_pos.y >= 0 && next_layer_pos.y < next_layer_out.y;
          float delta = in_range ? deltas_next_layer[next_layer_idx + k] : 0.0f;

          for (size_t n = 0; n < CURRENT_FILTER_COUNT; n++) {
            // (1) w[abnk](l-1)
            // NOTE: n iterates over lower layer's filters
            size_t w_idx = w_idx_2D + n * n_next_filter_cnt + k;
            float w = W[w_idx];

            // (3) f`( x[i,j,n](l-1) )
            float activation_func_derivative = activation_func_derivatives[n];

            // result
            delta_for_filter[n] += delta * w * activation_func_derivative;
          }
        }

        //
      }
    }

    // write results
    for (size_t n = 0; n < CURRENT_FILTER_COUNT; n++) {
      target[idx + n] = delta_for_filter[n];
    }

    // end
  }
}

/* clang-format off */
/**
 *
 * Calculate deltas*activation_func_derivative of previous layer.
 *
 * In following notation (l), (l-1) describes relative layer and [...] lower indices.
 *
 * Algo for delta_ijn on layer (l-1), where:
 *   i = 0..output_w(l-1),
 *   j = 0..output_h(l-1),
 *   n = 0..filter_count(l-1):
 *
 * delta[i,j,n](l-1) = 0
 * for a = 0..spatial_size(l+1):
 *   for b = 0..spatial_size(l+1):
 *     for k = 0..filter_count(l+1):
 *       delta[i,j,n](l-1) += \
 *         w[abnk](l-1)               # (1) weight of edge between [i,j,n](l-1) and [i+a,j+b,k](l)
 *         * delta[i-a,j-b,k](l)      # (2) error term for [i-a,j-b,k](l). minus since we have point (i,j) and we asking: 'which output point are we affecting with w[a,b,_,_]'
 *         #* f`( x[i+a,j+b,n](l-1) )  # (3) derivative of activation function
 *         * f`(x[i,j,n](l-1) )       # (3) derivative of activation function at measured point
 *
 * TODO in (3) should index be x[i+a,j+b,n] or x[i,j,n]?
 * TODO in popular notation it's [i-a,j-b,_], is this just because matlab's
 *      native conv2 expects transposition ?
 *
 * TODO send layer_out as int2, not pair of ints
 *
 * macros:
 * 	CURRENT_FILTER_COUNT                   filter_count(l-1)
 *
 * @param  float*      deltas_next_layer   size: output_w(l) * output_w(l) * filter_count(l)
 * @param  float*      layer_output        size: output_w(l-1) * output_w(l-1) * filter_count(l-1)
 * @param  float*      target              size: output_w(l-1) * output_w(l-1) * filter_count(l-1)
 * @param  float*      W                   weights between (l-1) and (l).
 *                                         WARN: w3 is between (l2) and (l3), w2 -> (l1) and (l2), w1 -> (input) and (l1)
 *                                         size: f_spatial_size*f_spatial_size*filter_count(l-1)*filter_count(l)
 * @param  uint        f_spatial_size      spatial/kernel size for (l-1)
 * @param  uint        f_next_spatial_size spatial/kernel size for (l)
 * @param  uint        n_next_filter_cnt   filter_count(l)
 * @param  uint        layer_out_w         output_w(l-1)
 * @param  uint        layer_out_h         output_h(l-1)
 * @return {[type]}                        [description]
 */
/* clang-format on */
__kernel void main(__read_only __global float* deltas_next_layer,  //
                   __read_only __global float* layer_output,       //
                   __global float* target,                         //
                   __read_only __global float* W,                  //
                   uint f_spatial_size,                            //
                   uint f_next_spatial_size,                       //
                   uint n_next_filter_cnt,                         //
                   uint layer_out_w, uint layer_out_h) {
  // x=col=i; range: 0..layer_out_w
  // y=row=j; range: 0..layer_out_h
  const int2 pos = {get_global_id(0), get_global_id(1)};
  const int2 out_dim = {layer_out_w, layer_out_h};
  const int idx = ((pos.y * out_dim.x) + pos.x) * CURRENT_FILTER_COUNT;
  const int2 next_layer_out = {out_dim.x - f_next_spatial_size + 1,
                               out_dim.y - f_next_spatial_size + 1};

  // zeroed result cache and read read output values for output[i,j,n]
  float delta_for_filter[CURRENT_FILTER_COUNT];
  float activation_func_derivatives[CURRENT_FILTER_COUNT];

  // range check for i,j
  if (pos.x >= 0 && pos.x < out_dim.x &&  //
      pos.y >= 0 && pos.y < out_dim.y) {
    // fill tmp buffer values
    for (size_t n = 0; n < CURRENT_FILTER_COUNT; n++) {
      delta_for_filter[n] = 0.0f;
      // (3) f`( x[i,j,n](l-1) )
      float y_ijn = layer_output[idx + n];
      float relu_deriv = y_ijn > 0.0f ? 1.0f : 0.0f;
    }

    for (size_t dy = 0; dy < f_next_spatial_size; dy++) {
      for (size_t dx = 0; dx < f_next_spatial_size; dx++) {
        // NOTE: dy=a, dx=b
        int2 next_layer_pos = {pos.x - dx, pos.y - dy};
        size_t w_idx_2D = ((dy * f_next_spatial_size) + dx) *
                          n_next_filter_cnt * CURRENT_FILTER_COUNT;

        for (size_t k = 0; k < n_next_filter_cnt; k++) {
          // (2) delta[i+a,j+b,k](l)
          // this requires us to map curent output_pos to next layer coords,
          // but some of the point may not be in range. f.e. point(i=0,j=0) does
          // not affect output with w[a,b] if a!=0 && b!=0
          int next_layer_idx =
              ((next_layer_pos.y * next_layer_out.x) + next_layer_pos.x) *
              n_next_filter_cnt;
          bool in_range =
              next_layer_pos.x >= 0 && next_layer_pos.x < next_layer_out.x &&
              next_layer_pos.y >= 0 && next_layer_pos.y < next_layer_out.y;
          float delta = in_range ? deltas_next_layer[next_layer_idx + k] : 0.0f;

          for (size_t n = 0; n < CURRENT_FILTER_COUNT; n++) {
            // (1) w[abnk](l-1)
            // NOTE: n iterates over lower layer's filters
            size_t w_idx = w_idx_2D + n * n_next_filter_cnt + k;
            float w = W[w_idx];

            // (3) f`( x[i,j,n](l-1) )
            float activation_func_derivative = activation_func_derivatives[n];

            // result
            delta_for_filter[n] += delta * w * activation_func_derivative;
          }
        }

        //
      }
    }

    // write results
    for (size_t n = 0; n < CURRENT_FILTER_COUNT; n++) {
      target[idx + n] = delta_for_filter[n];
    }

    // end
  }
}


tcleanup: warn about unknown files

tcleanup: warn about unknown files

And ignore .iso files.  They're special (and rare).


new files

new files


got the window to bounce up and down, at a silky 30 FPS. Assuming the appropriate optimizations are taken, this should be enough for any layout animations.

(proclaim '(optimize (speed 0) (safety 3) (debug 3)))

(ql:quickload '(alexandria iterate anaphora cl-cairo2 cl-cairo2-xlib cl-pango) :silent t)

(defpackage arboreta
  (:use cl iterate anaphora cl-cairo2))

(in-package arboreta)

;; TODO & NOTES
;; find a way to fix the screen tearing issue
;; can we blit windows, or do they just have to be redrawn?
;; does normal pango layouts allow for smooth scolling?
;; text selection is going to be really weird, if implemented
;;   can we pull the font height from pango or fc for highlighting?
;;   how do we change the cursor to the text selection one?
;;     do we even have a cursor in wm mode?
;;   "worse is better" solution
;;     use internal clipboard, disregard people trying to use the applications by themselves
;;   alternative ("the right thing") solutions
;;     try to interface with x font rendering
;;       that means the main clipboard would need to be used
;;       using cl-x, probably
;;     switch platforms -- low preference

(defparameter context nil)
(defparameter surface nil)
(defparameter layout nil)
(defparameter font nil)

(defparameter w 600)
(defparameter h 400)

(defstruct window
   (attributes (make-hash-table :test #'eq))
   (draw nil))

(defun draw (window)
   (funcall (window-draw window) window))

(defun draw-subwindows (window)
   (awhen (gethash 'subwindows (window-attributes window))
          (iter (for x in it)
                (draw x))))

(defparameter root-window
   (make-window :draw
      (lambda (window)
         (new-path)
         (set-source-rgb 37/255 46/255 50/255)
         (rectangle 0 0 w h)
         (fill-path)
         (draw-subwindows window))))

(defun add-as-subwindow (source-window target-window)
   (push source-window (gethash 'subwindows (window-attributes target-window))))

(defun pango-update ()
   (pango:pango_cairo_update_layout (slot-value *context* 'cairo::pointer) layout)
   (pango:pango_cairo_show_layout (slot-value *context* 'cairo::pointer) layout))

(defun flush-surface ()
   (surface-flush surface)
   (cairo::sync context))

(defun window-update-loop ()
   (iter (for x = (get-internal-real-time))
         (for y = (+ x 33))
         (draw root-window)
         (flush-surface)
         (sleep (let ((a (/ (- y (get-internal-real-time)) 1000)))
                      (if (> a 0) a 0)))))

(defun unicode-test ()
   (setf layout (pango:pango_cairo_create_layout (slot-value cairo:*context* 'cairo::pointer)))
   (setf font (pango:pango_font_description_from_string "Fantasque sans mono 10"))
   (pango:pango_layout_set_font_description layout font)

   (set-source-rgb 37/255 46/255 50/255)
   (rectangle 0 0 w h)
   (fill-path)
   (new-path)
   (move-to 0 0)
   (set-source-rgb 148/255 163/255 165/255)

   (pango:pango_layout_set_text layout
     (format nil "~{~a~%~}"
       '("Hello, glorious pango text rendering!"
         "いあだ〜〜ずかしいです〜〜"
         "Τη γλώσσα μου έδωσαν ελληνική"
         "ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ"
         "ಬಾ ಇಲ್ಲಿ ಸಂಭವಿಸು ಇಂದೆನ್ನ ಹೃದಯದಲಿ "
         "मैं काँच खा सकता हूँ और मुझे उससे कोई चोट नहीं पहुंचती "))
     -1)

   (pango-update)
   (flush-surface))

(defparameter raven "Once upon a midnight dreary, while I pondered, weak and weary...")

;; you might not have this font, change it to a good non-bitmap monospaced font you do have.
(defun update-test ()
   (setf layout (pango:pango_cairo_create_layout (slot-value cairo:*context* 'cairo::pointer)))
   (setf font (pango:pango_font_description_from_string "Fantasque sans mono 10"))
   (pango:pango_layout_set_font_description layout font)

   (iter (for x from 0 to (length raven))
         (set-source-rgb 37/255 46/255 50/255)
         (rectangle 0 0 w h)
         (fill-path)
         (new-path)
         (move-to 0 0)
         (set-source-rgb 148/255 163/255 165/255)
         (pango:pango_layout_set_text layout (subseq raven 0 x) -1)
         (pango-update)
         (flush-surface)
         (sleep 0.1)))

(defparameter index 0)
(defparameter timer 0)

(defun windowing-test ()
   (setf layout (pango:pango_cairo_create_layout (slot-value cairo:*context* 'cairo::pointer)))
   (setf font (pango:pango_font_description_from_string "Fantasque sans mono 10"))
   (pango:pango_layout_set_font_description layout font)

   (add-as-subwindow
      (make-window :draw
         (lambda (window)
            (incf timer)
            (new-path)
            (set-source-rgb 47/255 56/255 60/255)
            (rectangle 20 (+ 20 (* 0.7 h (sin (/ timer 10)))) (- w 40) (- h 40))
            (fill-path)

            (new-path)
            (move-to 20 (+ 20 (* 0.7 h (sin (/ timer 10)))))
            (set-source-rgb 148/255 163/255 165/255)
            (if (< index (length raven)) (incf index))
            (pango:pango_layout_set_text layout (subseq raven 0 index) -1)
            (pango-update)

            (draw-subwindows window)))
      root-window)
   (window-update-loop))

;; had to do it without the helper macros, because they cause context errors for some reason
(defun create-xlib-window ()
   (setf context (create-xlib-image-context w h :window-name "pango-test"))
   (setf surface (get-target context))
   (with-context (context)
      (windowing-test)))

(defun main ()
  (sb-thread:make-thread 'create-xlib-window :name "rendering-thread")

  (read-line)
  (cairo:destroy context)
  (sb-ext:exit))

;; (sb-ext:save-lisp-and-die "arboreta" :toplevel #'main :executable t)
(main)

(proclaim '(optimize (speed 0) (safety 3) (debug 3)))

(ql:quickload '(alexandria iterate anaphora cl-cairo2 cl-cairo2-xlib cl-pango) :silent t)

(defpackage arboreta
  (:use cl iterate anaphora cl-cairo2))

(in-package arboreta)

;; TODO & NOTES
;; can we blit windows, or do they just have to be redrawn?
;; does normal pango layouts allow for smooth scolling?
;; text selection is going to be really weird, if implemented
;;   can we pull the font height from pango or fc for highlighting?
;;   how do we change the cursor to the text selection one?
;;     do we even have a cursor in wm mode?
;;   "worse is better" solution
;;     use internal clipboard, disregard people trying to use the applications by themselves
;;   alternative ("the right thing") solutions
;;     try to interface with x font rendering
;;       that means the main clipboard would need to be used
;;       using cl-x, probably
;;     switch platforms -- low preference

(defparameter context nil)
(defparameter surface nil)
(defparameter layout nil)
(defparameter font nil)

(defparameter w 1200)
(defparameter h 800)

(defstruct window
   (attributes (make-hash-table :test #'eq))
   (draw nil))

(defun draw (window)
   (funcall (window-draw window) window))

(defun draw-subwindows (window)
   (awhen (gethash 'subwindows (window-attributes window))
          (iter (for x in it)
                (draw x))))

(defparameter root-window
   (make-window :draw
      (lambda (window)
         (new-path)
         (set-source-rgb 37/255 46/255 50/255)
         (rectangle 0 0 w h)
         (fill-path)
         (draw-subwindows window))))

(defun add-as-subwindow (source-window target-window)
   (push source-window (gethash 'subwindows (window-attributes target-window))))

(defun pango-update ()
   (pango:pango_cairo_update_layout (slot-value *context* 'cairo::pointer) layout)
   (pango:pango_cairo_show_layout (slot-value *context* 'cairo::pointer) layout))

(defun flush-surface ()
   (surface-flush surface)
   (cairo::sync context))

;; sleeps so that it doesn't eat all the CPU, need some way to limit drawing or something
(defun window-update-loop ()
   (iter (draw root-window)
         (flush-surface)
         (sleep 0.05)))

(defun unicode-test ()
   (setf layout (pango:pango_cairo_create_layout (slot-value cairo:*context* 'cairo::pointer)))
   (setf font (pango:pango_font_description_from_string "Fantasque sans mono 10"))
   (pango:pango_layout_set_font_description layout font)

   (set-source-rgb 37/255 46/255 50/255)
   (rectangle 0 0 w h)
   (fill-path)
   (new-path)
   (move-to 0 0)
   (set-source-rgb 148/255 163/255 165/255)

   (pango:pango_layout_set_text layout
     (format nil "~{~a~%~}"
       '("Hello, glorious pango text rendering!"
         "いあだ〜〜ずかしいです〜〜"
         "Τη γλώσσα μου έδωσαν ελληνική"
         "ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ"
         "ಬಾ ಇಲ್ಲಿ ಸಂಭವಿಸು ಇಂದೆನ್ನ ಹೃದಯದಲಿ "
         "मैं काँच खा सकता हूँ और मुझे उससे कोई चोट नहीं पहुंचती "))
     -1)

   (pango-update)
   (flush-surface))

;; you might not have this font, change it to a good non-bitmap monospaced font you do have.
(defun update-test ()
   (setf layout (pango:pango_cairo_create_layout (slot-value cairo:*context* 'cairo::pointer)))
   (setf font (pango:pango_font_description_from_string "Fantasque sans mono 10"))
   (pango:pango_layout_set_font_description layout font)

   (iter (with str = "Once upon a midnight dreary, while I pondered, weak and weary...")
         (for x from 0 to (length str))
         (set-source-rgb 37/255 46/255 50/255)
         (rectangle 0 0 w h)
         (fill-path)
         (new-path)
         (move-to 0 0)
         (set-source-rgb 148/255 163/255 165/255)
         (pango:pango_layout_set_text layout (subseq str 0 x) -1)
         (pango-update)
         (flush-surface)
         (sleep 0.1)))

(defun windowing-test ()
   (add-as-subwindow
      (make-window :draw
         (lambda (window)
            (new-path)
            (set-source-rgb 47/255 56/255 60/255)
            (rectangle 20 20 (- w 40) (- h 40))
            (fill-path)
            (draw-subwindows window)))
      root-window)
   (window-update-loop))

;; had to do it without the helper macros, because they cause context errors for some reason
(defun create-xlib-window ()
   (setf context (create-xlib-image-context w h :window-name "pango-test"))
   (setf surface (get-target context))
   (with-context (context)
      (update-test)))

(defun main ()
  (sb-thread:make-thread 'create-xlib-window :name "rendering-thread")

  (read-line)
  (cairo:destroy context)
  (sb-ext:exit))

;;(sb-ext:save-lisp-and-die "arboreta" :toplevel #'main :executable t)
(main)


fixed the kitty error

fixed the kitty error

#include "kernel_header.h"

float3			sub_vect(float3 v1, float3 v2)
{
	float3		res;

	res.x = v1.x - v2.x;
	res.y = v1.y - v2.y;
	res.z = v1.z - v2.z;
	return (res);
}

float3			add_vect(float3 v1, float3 v2)
{
	float3		res;

	res.x = v1.x + v2.x;
	res.y = v1.y + v2.y;
	res.z = v1.z + v2.z;
	return (res);
}

float			norme_vect(float3 v)
{
	return (sqrt(v.x * v.x + v.y * v.y + v.z * v.z));
}

float3			normalize_vect(float3 v)
{
	float3		res;
	int			id = 1 / sqrt(v.x * v.x + v.y * v.y + v.z * v.z);

	res.x = v.x * id;
	res.y = v.y * id;
	res.z = v.z * id;
	return (res);
}

float			dot_vect(float3 v1, float3 v2)
{
	return (v1.x * v2.x + v1.y * v2.y + v1.z * v2.z);
}

float3			mult_fvect(float m, float3 v)
{
	float3		res;

	res.x = m * v.x;
	res.y = m * v.y;
	res.z = m * v.z;
	return (res);
}

float3			get_abc(float radius, float3 ray, float3 origin)
{
	float3		abc;

	abc.x = dot_vect(ray, ray);
	abc.y = 2 * dot_vect(ray, origin);
	abc.z = dot_vect(origin, origin) - (radius * radius);
	return (abc);
}

float			inter_sphere(float radius, float3 ray, float3 cam_origin, float3 sphere_origin)
{
	float3		abc;
	float		d;
	float		res1;
	float		res2;

	cam_origin.x -= sphere_origin.x;
	cam_origin.y -= sphere_origin.y;
	cam_origin.z -= sphere_origin.z;
	abc = get_abc(radius, ray, cam_origin);
	d = (abc.y * abc.y) - (4 * (abc.x * abc.z));
	if (d < 0)
		return (1000000000);
	if (d == 0)
		return ((-abc[1]) / (2 * abc[0]));
	res1 = (((-abc[1]) + sqrt(d)) / (2 * abc[0]));
	res2 = (((-abc[1]) - sqrt(d)) / (2 * abc[0]));
	if (res1 < res2)
		return(res1);
	return(res2);
}

float			inter_plan(float3 plan_origin, float3 plan_normale, float3 ray, float3 cam_origin)
{
	float		t;

	t = dot_vect(ray, plan_normale);

	t = dot_vect(sub_vect(plan_origin, cam_origin), plan_normale) / t;
	if (t < 0.0000001)
		return (1000000000);
	return (t);
}

float			modh_vect(int x)
{
	return ((float)((float)x - (WINX / 2.0)) / (WINX / 2.0));
}

float			modv_vect(int y)
{
	return ((float)(((float)y - (WINY / 2.0)) / (WINY / 2.0) * WINY / WINX));
}

float3			get_ray(float3 n, float3 v, float3 h, int x, int y)
{
	float3		res;

	h = mult_fvect(modh_vect(x), h);
	v = mult_fvect(modv_vect(y), v);
	res = add_vect(n, v);
	res = add_vect(res, h);
	return (res);
}

__kernel void	ray_trace(__global char *output,
							float mvx,
							float mvy,
							float mvz,
							__constant t_object *scene)
{
	int		id = get_global_id(0);
	int		x = id % WINX;
	int		y = id / WINX;

	// CAM
	float3	cam_origin;
	cam_origin.x = 0 + mvx;
	cam_origin.y = 0 + mvy;
	cam_origin.z = 0 + mvz;
	float3	hor;
	hor.x = 0.6;
	hor.y = 0;
	hor.z = 0;
	float3	vert;
	vert.x = 0;
	vert.y = 0.6;
	vert.z = 0;
	float3	cam_dir;
	cam_dir.x = 0;
	cam_dir.y = 0;
	cam_dir.z = 1;

	// SPHERE
	float3	boule_origin;
	boule_origin.x = 0;
	boule_origin.y = 10;
	boule_origin.z = 200;
	float	radius = 10;

	// SPHERE2
	float3	boule_origin2;
	boule_origin2.x = 0;
	boule_origin2.y = -10;
	boule_origin2.z = 50;
	float	radius2 = 10;

	// PLANE
	float3	plan_origin;
	plan_origin.x = 0;
	plan_origin.y = 0;
	plan_origin.z = 300;
	float3	plan_normale;
	plan_normale.x = 0;
	plan_normale.y = -1;
	plan_normale.z = 0;

	float plan;
	float sphere;
	float sphere2;

	float3 ray = get_ray(cam_dir, vert, hor, x ,y);
	if (( plan = inter_plan(plan_origin, plan_normale, ray, cam_origin)) < 0)
		plan = 1000000000;
	if (( sphere= inter_sphere(radius, ray, cam_origin, boule_origin)) < 0)
		sphere = 1000000000;
	if ((sphere2 = inter_sphere(radius2, ray, cam_origin, boule_origin2)) < 0)
		sphere2 = 1000000000;
	if (sphere == 1000000000 && plan == 1000000000 && sphere2 == 1000000000)
		OUTPUTE = BACKCOLOR;
	else if (sphere < plan && sphere < sphere2)
		OUTPUTE = SCOLOR;
	else if (sphere2 < sphere && sphere2 < plan)
		OUTPUTE = SSCOLOR;
	else
		OUTPUTE = PCOLOR;
}

#include "kernel_header.h"

float3			sub_vect(float3 v1, float3 v2)
{
	float3		res;

	res.x = v1.x - v2.x;
	res.y = v1.y - v2.y;
	res.z = v1.z - v2.z;
	return (res);
}

float3			add_vect(float3 v1, float3 v2)
{
	float3		res;

	res.x = v1.x + v2.x;
	res.y = v1.y + v2.y;
	res.z = v1.z + v2.z;
	return (res);
}

float			norme_vect(float3 v)
{
	return (sqrt(v.x * v.x + v.y * v.y + v.z * v.z));
}

float3			normalize_vect(float3 v)
{
	float3		res;
	int			id = 1 / sqrt(v.x * v.x + v.y * v.y + v.z * v.z);

	res.x = v.x * id;
	res.y = v.y * id;
	res.z = v.z * id;
	return (res);
}

float			dot_vect(float3 v1, float3 v2)
{
	return (v1.x * v2.x + v1.y * v2.y + v1.z * v2.z);
}

float3			mult_fvect(float m, float3 v)
{
	float3		res;

	res.x = m * v.x;
	res.y = m * v.y;
	res.z = m * v.z;
	return (res);
}

float3			get_abc(float radius, float3 ray, float3 origin)
{
	float3		abc;

	abc.x = dot_vect(ray, ray);
	abc.y = 2 * dot_vect(ray, origin);
	abc.z = dot_vect(origin, origin) - (radius * radius);
	return (abc);
}

float			inter_sphere(float radius, float3 ray, float3 cam_origin, float3 sphere_origin)
{
	float3		abc;
	float		d;
	float		res1;
	float		res2;

	cam_origin.x -= sphere_origin.x;
	cam_origin.y -= sphere_origin.y;
	cam_origin.z -= sphere_origin.z;
	abc = get_abc(radius, ray, cam_origin);
	d = (abc.y * abc.y) - (4 * (abc.x * abc.z));
	if (d < 0)
		return (1000000000);
	if (d == 0)
		return ((-abc[1]) / (2 * abc[0]));
	res1 = (((-abc[1]) + sqrt(d)) / (2 * abc[0]));
	res2 = (((-abc[1]) - sqrt(d)) / (2 * abc[0]));
	if (res1 < res2)
		return(res1);
	return(res2);
}

float			inter_plan(float3 plan_origin, float3 plan_normale, float3 ray, float3 cam_origin)
{
	float		t;

	t = dot_vect(ray, plan_normale);

	t = dot_vect(sub_vect(plan_origin, cam_origin), plan_normale) / t;
	if (t < 0.0000001)
		return (1000000000);
	return (t);
}

float			modh_vect(int x)
{
	return ((float)((float)x - (WINX / 2.0)) / (WINX / 2.0));
}

float			modv_vect(int y)
{
	return ((float)(((float)y - (WINY / 2.0)) / (WINY / 2.0) * WINY / WINX));
}

float3			get_ray(float3 n, float3 v, float3 h, int x, int y)
{
	float3		res;

	h = mult_fvect(modh_vect(x), h);
	v = mult_fvect(modv_vect(y), v);
	res = add_vect(n, v);
	res = add_vect(res, h);
	return (res);
}

__kernel void	ray_trace(__global char *output,
							float mvx,
							float mvy,
							float mvz,
							__constant t_object *scene)
{
	int		id = get_global_id(0);
	int		x = id % WINX;
	int		y = id / WINX;

	if (id == 1)
		printf("test %f\n", scene[0].cam.hor.x);

	// CAM
	float3	cam_origin;
	cam_origin.x = 0 + mvx;
	cam_origin.y = 0 + mvy;
	cam_origin.z = 0 + mvz;
	float3	hor;
	hor.x = 0.6;
	hor.y = 0;
	hor.z = 0;
	float3	vert;
	vert.x = 0;
	vert.y = 0.6;
	vert.z = 0;
	float3	cam_dir;
	cam_dir.x = 0;
	cam_dir.y = 0;
	cam_dir.z = 1;

	// SPHERE
	float3	boule_origin;
	boule_origin.x = 0;
	boule_origin.y = 10;
	boule_origin.z = 200;
	float	radius = 10;

	// SPHERE2
	float3	boule_origin2;
	boule_origin2.x = 0;
	boule_origin2.y = -10;
	boule_origin2.z = 50;
	float	radius2 = 10;

	// PLANE
	float3	plan_origin;
	plan_origin.x = 0;
	plan_origin.y = 0;
	plan_origin.z = 300;
	float3	plan_normale;
	plan_normale.x = 0;
	plan_normale.y = -1;
	plan_normale.z = 0;

	float plan;
	float sphere;
	float sphere2;

	float3 ray = get_ray(cam_dir, vert, hor, x ,y);
	if (( plan = inter_plan(plan_origin, plan_normale, ray, cam_origin)) < 0)
		plan = 1000000000;
	if (( sphere= inter_sphere(radius, ray, cam_origin, boule_origin)) < 0)
		sphere = 1000000000;
	if ((sphere2 = inter_sphere(radius2, ray, cam_origin, boule_origin2)) < 0)
		sphere2 = 1000000000;
//	if (id > (WINX * WINY / 3) && id < (WINX * WINY / 3 * 2))
//	printf("plan = %f sphere = %f\n", plan, sphere);
	if (sphere == 1000000000 && plan == 1000000000 && sphere2 == 1000000000)
		OUTPUTE = BACKCOLOR;
	else if (sphere < plan && sphere < sphere2)
		OUTPUTE = SCOLOR;
	else if (sphere2 < sphere && sphere2 < plan)
		OUTPUTE = SSCOLOR;
	else
		OUTPUTE = PCOLOR;
}


fixed memory access error

fixed memory access error

/*
 * Copyright (c) 2016 AMD Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and/or associated documentation files (the
 * "Materials"), to deal in the Materials without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Materials, and to
 * permit persons to whom the Materials are furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Materials.
 *
 * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
 */

#define _FLOAT					float
#define _FLOAT2					float2
#define _FLOAT4					float4
#define _FLOAT8					float8

#ifndef FLT_MAX
#define FLT_MAX         3.402823466e+38F        /* max value */
#endif

#define MLO_FILTER_SZ (MLO_FILTER_SIZE1*MLO_FILTER_SIZE0)

#define MLO_GRP_SZ0  (MLO_GRP_TILE0*MLO_GRP_TILE1)
#define MLO_GRP_SZ1 1
#define MLO_GRP_SZ2 1
#define MLO_GRP_SZ (MLO_GRP_SZ0*MLO_GRP_SZ1*MLO_GRP_SZ2)
#define MLO_N_PROC_WAVES ((MLO_GRP_SZ + MLO_N_READ_PROCS - 1)/MLO_N_READ_PROCS)
#define MLO_OUT_TILE_SZ (MLO_OUT_PIX_TILE1*MLO_OUT_PIX_TILE0)
#define MLO_ALU_TILE_SZ (MLO_ALU_VTILE1*MLO_ALU_VTILE0)

#if MLO_IN_TILE0 < MLO_OUT_WIDTH || MLO_IN_TILE1 < MLO_OUT_HEIGHT
#define MLO_LARGE_MAP 1
#else
#define MLO_LARGE_MAP 0
#endif

#if (MLO_IN_WIDTH == MLO_OUT_WIDTH && (MLO_IN_WIDTH / MLO_IN_TILE0 ) * MLO_IN_TILE0 == MLO_IN_WIDTH && MLO_IN_HEIGHT == MLO_OUT_HEIGHT && (MLO_IN_HEIGHT / MLO_IN_TILE1 ) * MLO_IN_TILE1 == MLO_IN_HEIGHT)
#define MLO_OUT_ALIGNED 1
#else
#define MLO_OUT_ALIGNED 0
#endif

#define MLO_ALUTILES_STACK_SZ (MLO_N_ALUTILES_PERSTACK*MLO_ALU_TILE_SZ)
#define MLO_N_IN_TILES_TOTAL (MLO_N_IN_TILES_PERSTACK*MLO_N_STACKS)

#define MLO_N_OUT_TILE_BLOCKS0 ((MLO_OUT_WIDTH+MLO_IN_TILE0-1)/MLO_IN_TILE0)
#define MLO_N_OUT_TILE_BLOCKS1 ((MLO_OUT_HEIGHT+MLO_IN_TILE1-1)/MLO_IN_TILE1)
#define MLO_N_IN_PACKS  (MLO_N_INPUTS/MLO_N_IN_TILES_PERSTACK)

#define MLO_N_IN_READ (MLO_N_IN_PACKS*MLO_N_IN_TILES_PERSTACK)
#if MLO_N_IN_READ == MLO_N_INPUTS
#define MLO_INPUTS_ALIGNED 1
#else
#define MLO_INPUTS_ALIGNED 0
#endif

#define MLO_N_OUT_PACKS  (MLO_N_OUTPUTS/MLO_N_OUT_TILES_PERSTACK)
#if MLO_N_OUT_PACKS*MLO_N_OUT_TILES_PERSTACK == MLO_N_OUTPUTS && MLO_N_OUT_TILES_PERSTACK != MLO_N_OUTPUTS
#define MLO_OUTPUTS_ALIGNED 1
#else
#define MLO_OUTPUTS_ALIGNED 0
#endif

#define MLO_N_BATCH_PACKS (MLO_BATCH_SZ/MLO_N_STACKS)
#if MLO_N_BATCH_PACKS*MLO_N_STACKS == MLO_BATCH_SZ && MLO_N_STACKS != MLO_BATCH_SZ
#define MLO_BATCH_ALIGNED 1
#else
#define MLO_BATCH_ALIGNED 0
#endif

#define MLO_IN_LCL_WIDTH (MLO_IN_TILE0 + MLO_FILTER_SIZE0 - 1)  // here we use kernel size. it's important when padding == 0
#define MLO_IN_LCL_HEIGHT (MLO_IN_TILE1 + MLO_FILTER_SIZE1 - 1)
#define MLO_IN_LCL_TILE_SZ (MLO_IN_LCL_WIDTH*MLO_IN_LCL_HEIGHT)
#define MLO_IN_LCL_PERSTACK_SZ (MLO_IN_LCL_TILE_SZ*MLO_N_IN_TILES_PERSTACK)
#define MLO_IN_LCL_SZ (MLO_IN_LCL_PERSTACK_SZ*MLO_N_STACKS)

#define MLO_WEIGHTS_SZ (MLO_N_OUT_TILES_PERSTACK*MLO_N_IN_TILES_PERSTACK*MLO_FILTER_SZ)

#define MLO_PVT_ACCUM_DATA_SZ (MLO_N_OUT_TILES * MLO_OUT_TILE_SZ)
#define MLO_PVT_IN_WIDTH (MLO_FILTER_SIZE0 + MLO_OUT_PIX_TILE0 - 1)
#define MLO_PVT_IN_HEIGHT (MLO_OUT_PIX_TILE1)

#define MLO_LCL_WEIGHTS 1

inline void calculateXYPos(int linPos, int width, int *x, int *y)
{

	(*y) = (int)((float)linPos / (float)width + 0.00001f);

	(*x) = linPos - (*y) * width;
}

inline int calculateOffset(int stride, int x, int y)
{
	int ret = y * stride + x;
	return(ret);
}

inline void readDataElem(int linPos,__local _FLOAT *lcl_data, int lcl_base, int lcl_height, int lcl_width, int lcl_stride, int lcl_y, int lcl_x,
					 const __global _FLOAT * gbl_data, int gbl_base, int gbl_height, int gbl_width, int gbl_stride, int gbl_y, int gbl_x,
					 bool vis,
					 bool debug)
{
	int x, y;
	calculateXYPos(linPos, lcl_width, &x, &y);
	int g_x = x + gbl_x;
	int g_y = y + gbl_y;
	int gbl_off0 = calculateOffset(gbl_stride, g_x, g_y);
	int gbl_off = gbl_off0 + gbl_base;

	int l_x = x + lcl_x;
	int l_y = y + lcl_y;
	int lcl_off = lcl_base +
#if MLO_LARGE_MAP == 1
		linPos
#else
		mad24(l_y, lcl_stride, l_x);
#endif
	 ;

#if MLO_LARGE_MAP == 1
	 vis &= (g_x >= 0 && g_x < gbl_width && g_y >= 0 && g_y < gbl_height);
#endif
	 gbl_off = (vis) ? gbl_off : 0;
	 _FLOAT gbl_val = gbl_data[gbl_off];
	 gbl_val = (vis) ? gbl_val : 0;

	lcl_data[lcl_off] = gbl_val;

}

inline void readData(int lcl_id, int size, int lcl_p_stride, __local _FLOAT *lcl_data, int lcl_base, int lcl_height, int lcl_width, int lcl_stride, int lcl_y, int lcl_x,
					 const __global _FLOAT * gbl_data, int gbl_base, int gbl_height, int gbl_width, int gbl_stride, int gbl_y, int gbl_x,
					 bool vis,
					 bool debug
					 )
{

	for(int i = lcl_id; i < size; i+= lcl_p_stride)
	{
		readDataElem(i, lcl_data, lcl_base, lcl_height, lcl_width, lcl_stride, lcl_y, lcl_x,
					 gbl_data, gbl_base, gbl_height, gbl_width, gbl_stride, gbl_y, gbl_x,
					 vis,
					 debug);
	}

}

inline void loadData(int lcl_id, int lcl_p_stride,
					__local _FLOAT * lcl_data,
					int lcl_off, int lcl_size, int lcl_height, int lcl_width, int lcl_stride, int lcl_bot_y, int lcl_bot_x,
					const __global _FLOAT * gbl_data,
					int gbl_off, int gbl_size, int gbl_height, int glb_width, int gbl_stride, int gbl_bot_y, int gbl_bot_x,
					int buf_block_ind, int max_n_bufs, int lcl_n_bufs,
					bool debug)
{

	for(int c = 0; c < lcl_n_bufs;
		 ++c, lcl_off += lcl_size, gbl_off += gbl_size )
	{
		bool vis = (buf_block_ind + c <  max_n_bufs);
		readData(lcl_id, lcl_size, lcl_p_stride,
				 lcl_data, lcl_off, lcl_height, lcl_width, lcl_stride, lcl_bot_y, lcl_bot_x,
				 gbl_data, gbl_off, gbl_height, glb_width, gbl_stride, gbl_bot_y, gbl_bot_x,
				 vis,
				 (debug));
	}

}

inline void Conv(int o_map_base,
				int in_stg_off,
				 _FLOAT *pvt_in_stage, __local _FLOAT * lcl_indata,
				 _FLOAT *pvt_wei_stage, __local _FLOAT * lcl_wei,
				 _FLOAT *pvt_accum
				 )
{
// convolution

		// over all inputs in stack
		int in_stg_off1 = in_stg_off;
		for(int i_c = 0; i_c < MLO_N_IN_TILES_PERSTACK; ++i_c, in_stg_off1 += MLO_IN_LCL_TILE_SZ)
		{
        // preload input
			int wei_stg_base_off = mad24(o_map_base, (int)(MLO_N_IN_TILES_PERSTACK*MLO_FILTER_SZ), mul24(i_c,(int)MLO_FILTER_SZ));
			int in_stg_off2 = in_stg_off1;
			for(int j = 0; j < MLO_PVT_IN_HEIGHT-1; ++j, in_stg_off2+=MLO_IN_LCL_WIDTH
					)
			{
				for(int i = 0; i < MLO_PVT_IN_WIDTH; ++i)
				{
					pvt_in_stage[j*MLO_PVT_IN_WIDTH + i] = lcl_indata[in_stg_off2 + i];
				}
			}

		// over filter rows
			for(int k = 0; k < MLO_FILTER_SIZE1; ++k, in_stg_off2+=MLO_IN_LCL_WIDTH
			)
			{
				int k_act = 0;
#if MLO_DIR_FORWARD==1
				k_act = k;
#else
// load filter in reverse order
				k_act = MLO_FILTER_SIZE1 - 1 - k;
#endif
		// load next input row
				for(int i_pvt = 0; i_pvt < MLO_PVT_IN_WIDTH; ++i_pvt)
				{
					pvt_in_stage[(MLO_PVT_IN_HEIGHT-1)*MLO_PVT_IN_WIDTH + i_pvt] = lcl_indata[in_stg_off2 + i_pvt];
				}

		// over all outputs
				for(int o_c = 0; o_c < MLO_N_OUT_TILES; ++o_c)
				{
					int wei_stg_off = wei_stg_base_off + o_c * MLO_N_IN_TILES_PERSTACK*MLO_FILTER_SZ + k_act * MLO_FILTER_SIZE0;
					for(int i = 0; i < MLO_FILTER_SIZE0; ++i)
					{
						pvt_wei_stage[i] = lcl_wei[wei_stg_off + i];
					}

		// actual conv

					for( int j = 0; j < MLO_OUT_PIX_TILE1; ++j)
					{
						for(int i = 0; i < MLO_OUT_PIX_TILE0; ++i)
						{
							for(int l = 0; l < MLO_FILTER_SIZE0; ++l)
							{

								int l_act = 0;
#if MLO_DIR_FORWARD==1
								l_act = l;

#else
// in reverse horizontal and vertical orders
								l_act = MLO_FILTER_SIZE0 - 1 - l;

#endif

								pvt_accum[(o_c * MLO_OUT_PIX_TILE1 + j) * MLO_OUT_PIX_TILE0 + i]
									 += pvt_in_stage[j * MLO_PVT_IN_WIDTH + i + l] * pvt_wei_stage[l_act];

							}

						}
					}

				} // for(int o_c = 0; o_c < MLO_N_OUT_TILES; ++o_c)

               // move data up
				for(int j = 0; j < MLO_PVT_IN_HEIGHT-1; ++j)
				{
					for(int i = 0; i < MLO_PVT_IN_WIDTH; ++i)
					{
						pvt_in_stage[j*MLO_PVT_IN_WIDTH + i] = pvt_in_stage[(j+1)*MLO_PVT_IN_WIDTH + i];
					}
				}

//				mem_fence(CLK_LOCAL_MEM_FENCE);

			} // for(int k = 0; k < MLO_FILER_SIZE1; ++k,in_stg_off2+=MLO_IN_LCL_WIDTH)

		} // for(int i_c = 0; i_c < MLO_N_IN_TILES_PERSTACK; ++i_c, in_stg_off1 += MLO_IN_LCL_PERSTACK_SZ)

}

__attribute__((reqd_work_group_size(MLO_GRP_SZ0, MLO_GRP_SZ1, MLO_GRP_SZ2)))
__kernel void MLOpenConvUniC(
       const __global _FLOAT * in,
       const __global _FLOAT * weights,
#if MLO_CONV_BIAS
       const __global _FLOAT * bias,
#endif
 	  __global _FLOAT *out,
	   _FLOAT padding_val
	   )
{
	__local _FLOAT lcl_indata[MLO_IN_LCL_SZ];
	__local _FLOAT lcl_wei[MLO_WEIGHTS_SZ];
	__private _FLOAT pvt_accum[MLO_PVT_ACCUM_DATA_SZ];
	__private _FLOAT pvt_in_stage[MLO_PVT_IN_HEIGHT * MLO_PVT_IN_WIDTH];
	__private _FLOAT pvt_wei_stage[MLO_FILTER_SIZE0];

	int grp_id0 = get_group_id(0);
	int y_tile_blk = (int)((float)grp_id0 / (float) MLO_N_OUT_TILE_BLOCKS0 + 0.00001f);
	int x_tile_blk = grp_id0 - mul24(y_tile_blk, (int)MLO_N_OUT_TILE_BLOCKS0);
	int o_pack = get_group_id(1); // block of outputs
	int b_pack = get_group_id(2); // batch block

	int lcl_id = get_local_id(0);
	int stack = (int)((float)lcl_id/(float)MLO_ALUTILES_STACK_SZ + 0.00001f);  // stack
	int alu_stack_id = lcl_id - mul24(stack, (int)MLO_ALUTILES_STACK_SZ);  // alu index in stack
// ALU plane inside stack
	int alu_out_plane_id = (int)((float)alu_stack_id / (float)MLO_ALU_TILE_SZ + 0.00001f);  // alu output plane index
	int alu_out_id = alu_stack_id - mul24(alu_out_plane_id, (int)MLO_ALU_TILE_SZ); // alu index inside an ALU output plane
// pos inside ALU tile
	int alu_tl1 = (int)((float)alu_out_id/(float)MLO_ALU_VTILE0 + 0.00001f);
	int alu_tl0 = alu_out_id - mul24(alu_tl1, (int)MLO_ALU_VTILE0);

	int o_map_plane = o_pack * MLO_N_OUT_TILES_PERSTACK; // first output maps index per full ALU plane stack
	int o_map_base = alu_out_plane_id*MLO_N_OUT_TILES;  // local output map offset
	int o_map = o_map_plane + o_map_base; // output map index per ALU plane
	int b_index = b_pack * MLO_N_STACKS;

	int wave_id = (int)((float)lcl_id / (float)MLO_N_READ_PROCS + 0.00001f);
	int wave_lcl_id = lcl_id - mul24(wave_id, (int)MLO_N_READ_PROCS);

	int x_grp = x_tile_blk * MLO_IN_TILE0;
	int y_grp = y_tile_blk * MLO_IN_TILE1;

// TO DO: scale
	int x_in_grp = x_grp - MLO_FILTER_PAD0;
	int y_in_grp = y_grp - MLO_FILTER_PAD1;

	int x_in_lcl = alu_tl0 * MLO_OUT_PIX_TILE0;
	int y_in_lcl = alu_tl1 * MLO_OUT_PIX_TILE1;

// base offset to read data from local input data
	int in_stg_off = stack*MLO_IN_LCL_PERSTACK_SZ + (y_in_lcl) * MLO_IN_LCL_WIDTH + x_in_lcl;

    int in_off = b_index * MLO_IN_BATCH_STRIDE;

#if MLO_DIR_FORWARD==1
	int wei_off = mul24(o_map_plane, MLO_N_INPUTS * MLO_FILTER_SZ);
#else
	int wei_off = mul24(o_map_plane,MLO_FILTER_SZ);
#endif

#if MLO_LARGE_MAP == 0
	for(int i = lcl_id; i < MLO_IN_LCL_SZ;  i += MLO_GRP_SZ)
	{
		lcl_indata[i] = 0;
	}
#endif

	for(int i = 0; i < MLO_PVT_ACCUM_DATA_SZ; ++i)
	{
		pvt_accum[i] = 0;
	}

	for(int ic = 0; ic < MLO_N_INPUTS; ic += MLO_N_IN_TILES_PERSTACK, in_off += MLO_IN_CHANNEL_STRIDE*MLO_N_IN_TILES_PERSTACK,
				wei_off += MLO_N_IN_TILES_PERSTACK * MLO_FILTER_SZ
#if MLO_DIR_FORWARD==0
							* MLO_N_OUTPUTS
#endif
	)
	{
		barrier(CLK_LOCAL_MEM_FENCE);

// small map has been read in full continiously into the lDS buffer within padded rect,
// padding has been done on initilization.
// large map calculates padding on the fly and fills it with 0.

#if 1 // all inputs

#if MLO_LARGE_MAP == 1
		int in_lcl_off1 = 0;
		int in_off1 = in_off;
		for(int i_b = 0; i_b < MLO_N_STACKS; ++i_b, in_off1 += MLO_IN_BATCH_STRIDE, in_lcl_off1 += MLO_IN_LCL_PERSTACK_SZ)
		{
			bool vis = true;
#if MLO_BATCH_ALIGNED == 0
			vis &= (b_index + i_b < MLO_BATCH_SZ);
#endif

// over all inputs in stack
			int in_off2 = in_off1;
			int in_lcl_off2 = in_lcl_off1;
			for(int i_c = 0; i_c < MLO_N_IN_TILES_PERSTACK; ++i_c, in_off2 += MLO_IN_CHANNEL_STRIDE, in_lcl_off2 += MLO_IN_LCL_TILE_SZ)
			{
#if MLO_INPUTS_ALIGNED == 0
				vis &= (ic + i_c < MLO_N_INPUTS);
#endif

				int elem_id = lcl_id;
				int lcl_p_stride = MLO_GRP_SZ0;
				int lcl_base = 0;
				int lcl_y = 0;
				int lcl_x = 0;
				int gbl_base = 0;

				readData(elem_id, (MLO_IN_LCL_HEIGHT * MLO_IN_LCL_WIDTH), lcl_p_stride,
						&lcl_indata[in_lcl_off2], lcl_base, MLO_IN_LCL_HEIGHT, MLO_IN_LCL_WIDTH, MLO_IN_LCL_WIDTH, lcl_y, lcl_x,
						&in[in_off2], gbl_base, MLO_IN_HEIGHT, MLO_IN_WIDTH, MLO_IN_STRIDE, y_in_grp, x_in_grp,
						vis,
						true
					 );
			}

		}
#else
		for(int i = wave_id; i < MLO_N_IN_TILES_TOTAL;  i += MLO_N_PROC_WAVES)
		{
		//(MLO_N_STACKS * MLO_N_OUT_TILES_PERSTACK)
			int i_b = (int)((float)i / (float)MLO_N_IN_TILES_PERSTACK + 0.00001f);
			int i_c = i - mul24(i_b, (int)MLO_N_IN_TILES_PERSTACK);

			bool vis = true;

#if MLO_BATCH_ALIGNED == 0
			vis &= (b_index + i_b < MLO_BATCH_SZ);
#endif

#if MLO_INPUTS_ALIGNED == 0
			vis &= (ic + i_c < MLO_N_INPUTS);
#endif
			int in_off2 = in_off + i_b * MLO_IN_BATCH_STRIDE + i_c * MLO_IN_CHANNEL_STRIDE;
			int in_lcl_off2 = i_b * MLO_IN_LCL_PERSTACK_SZ + i_c * MLO_IN_LCL_TILE_SZ;

			int elem_id = wave_lcl_id;
			int lcl_p_stride = MLO_N_READ_PROCS;
			int lcl_base = 0;
			int lcl_y = MLO_FILTER_PAD1;
			int lcl_x = MLO_FILTER_PAD0;
			int gbl_base = 0;

			readData(elem_id, (MLO_IN_HEIGHT * MLO_IN_WIDTH), lcl_p_stride,
						&lcl_indata[in_lcl_off2], lcl_base, MLO_IN_HEIGHT, MLO_IN_WIDTH, MLO_IN_LCL_WIDTH, lcl_y, lcl_x,
						&in[in_off2], gbl_base, MLO_IN_HEIGHT, MLO_IN_WIDTH, MLO_IN_STRIDE, y_grp, x_grp,
						vis,
						true
					 );
		}
#endif

// read inputs and weights
// put weights into LDS

#if 1  // only weights

		for(int i = lcl_id; i < MLO_WEIGHTS_SZ; i += MLO_GRP_SZ)
		{
#if MLO_DIR_FORWARD==1
// here is [tops][bottoms]
			int lcl_o = (int)((float)i / (float)(MLO_N_IN_TILES_PERSTACK * MLO_FILTER_SZ) + 0.00001f);
			int gbl_i = i - mul24(lcl_o, (int)(MLO_N_IN_TILES_PERSTACK * MLO_FILTER_SZ));
			if((wei_off + lcl_o * MLO_N_INPUTS * MLO_FILTER_SZ + gbl_i) < (MLO_N_OUTPUTS*MLO_N_INPUTS*MLO_FILTER_SZ))
				lcl_wei[i] = weights[wei_off + lcl_o * MLO_N_INPUTS * MLO_FILTER_SZ + gbl_i];
			else
				lcl_wei[i] = weights[0];
#else
// outputs are botoms(inputs))
// inputs are tops(outputs)

			int lcl_o = (int)((float)i/ (float)(MLO_N_OUT_TILES_PERSTACK * MLO_FILTER_SZ) + 0.00001f);
			int gbl_i = i - mul24(lcl_o, (int)(MLO_N_OUT_TILES_PERSTACK * MLO_FILTER_SZ));
			int lcl_c = (int)((float)gbl_i/ (float)MLO_FILTER_SZ + 0.00001f);
			int lcl_i = gbl_i - mul24(lcl_c, (int)MLO_FILTER_SZ);

			int lcl_we_off = mad24(mad24(lcl_c, (int)MLO_N_IN_TILES_PERSTACK, lcl_o), (int)MLO_FILTER_SZ, lcl_i);
			int gbl_we_off = mad24(mad24(lcl_o, (int)MLO_N_OUTPUTS, lcl_c), (int)MLO_FILTER_SZ, wei_off + lcl_i);
			bool within_range = gbl_we_off < (MLO_N_OUTPUTS*MLO_N_INPUTS*MLO_FILTER_SZ);
			gbl_we_off = (within_range) ? gbl_we_off : 0;
			_FLOAT wei = weights[gbl_we_off];
			wei = (within_range) ? wei : 0;
			lcl_wei[lcl_we_off]
				= wei;

#endif

		}

#endif

// over all batch stacks

#endif  // all input

		barrier(CLK_LOCAL_MEM_FENCE);

// convolution
#if MLO_GRP_SZ > MLO_ACTIVE_ALUS
		if (lcl_id < MLO_ACTIVE_ALUS)
#endif
		Conv(o_map_base,
			in_stg_off,
			pvt_in_stage, lcl_indata,
			pvt_wei_stage, lcl_wei,
			pvt_accum
			);

//		barrier(CLK_LOCAL_MEM_FENCE);
	}

#if MLO_GRP_SZ > MLO_ACTIVE_ALUS
	if (lcl_id >= MLO_ACTIVE_ALUS)
	{
		return;
	}
#endif
// write results out
	int x_out_grp = x_grp;
	int y_out_grp = y_grp;
	int x_out_lcl = alu_tl0 * MLO_OUT_PIX_TILE0;
	int y_out_lcl = alu_tl1 * MLO_OUT_PIX_TILE1;

    int out_off = (b_index + stack) * MLO_OUT_BATCH_STRIDE + o_map * MLO_OUT_CHANNEL_STRIDE + (y_out_grp + y_out_lcl) * MLO_OUT_STRIDE + x_out_grp + x_out_lcl;
// over all local stacks
#if MLO_BATCH_ALIGNED == 0
	if (b_index + stack < MLO_BATCH_SZ)
#endif
	{

// over all local outputs
		int out_off1 = out_off;
		for(int o = 0; o < MLO_N_OUT_TILES
						; ++o, out_off1 += MLO_OUT_CHANNEL_STRIDE
						)
		{
// over output tile
			_FLOAT  bias_val = 0;
#if MLO_CONV_BIAS
			bias_val = bias[o_map + o];
#endif
			int out_off2 = out_off1;
			for( int j = 0; j < MLO_OUT_PIX_TILE1; ++j, out_off2 += MLO_OUT_STRIDE)
			{
				for(int i = 0; i < MLO_OUT_PIX_TILE0; ++i)
				{
					if ( true
#if 1 //MLO_OUT_ALIGNED == 0
					&& y_out_lcl + j < MLO_OUT_TILE1 && y_out_grp + y_out_lcl + j < MLO_OUT_HEIGHT &&  x_out_lcl + i < MLO_OUT_TILE0 && x_out_grp + x_out_lcl + i < MLO_OUT_WIDTH
#endif
#if MLO_OUTPUTS_ALIGNED == 0
						&& o_map + o < MLO_N_OUTPUTS
#endif
					)
					{
						out[out_off2 + i] = pvt_accum[o*MLO_OUT_TILE_SZ + j * MLO_OUT_PIX_TILE0 + i] + bias_val;
#if 0
						if ( out_off2 + i == 1 /*y_out_grp + y_out_lcl + j == 2 && x_out_grp + x_out_lcl + i == 0*/)
						{
							printf("K:out: %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d    %f %f %f\n",
								MLO_OUT_TILE1,
								MLO_OUT_TILE0,
								grp_id0,
								lcl_id,
								alu_out_plane_id,
								alu_out_id,
								b_index + stack,
								o,
								o_map,
								out_off,
								out_off1,
								out_off2,
								y_out_grp,
								y_out_lcl,
								x_out_grp,
								x_out_lcl,
								j,
								i,
								pvt_accum[o*MLO_OUT_TILE_SZ + j * MLO_OUT_PIX_TILE0 + i],
								 bias_val,
								out[out_off2 + i]
								);
						}
#endif
					}

				}
			}

		}
	}

}

/*
 * Copyright (c) 2016 AMD Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and/or associated documentation files (the
 * "Materials"), to deal in the Materials without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Materials, and to
 * permit persons to whom the Materials are furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Materials.
 *
 * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
 */

#define _FLOAT					float
#define _FLOAT2					float2
#define _FLOAT4					float4
#define _FLOAT8					float8

#ifndef FLT_MAX
#define FLT_MAX         3.402823466e+38F        /* max value */
#endif

#define MLO_FILTER_SZ (MLO_FILTER_SIZE1*MLO_FILTER_SIZE0)

#define MLO_GRP_SZ0  (MLO_GRP_TILE0*MLO_GRP_TILE1)
#define MLO_GRP_SZ1 1
#define MLO_GRP_SZ2 1
#define MLO_GRP_SZ (MLO_GRP_SZ0*MLO_GRP_SZ1*MLO_GRP_SZ2)
#define MLO_N_PROC_WAVES ((MLO_GRP_SZ + MLO_N_READ_PROCS - 1)/MLO_N_READ_PROCS)
#define MLO_OUT_TILE_SZ (MLO_OUT_PIX_TILE1*MLO_OUT_PIX_TILE0)
#define MLO_ALU_TILE_SZ (MLO_ALU_VTILE1*MLO_ALU_VTILE0)

#if MLO_IN_TILE0 < MLO_OUT_WIDTH || MLO_IN_TILE1 < MLO_OUT_HEIGHT
#define MLO_LARGE_MAP 1
#else
#define MLO_LARGE_MAP 0
#endif

#if (MLO_IN_WIDTH == MLO_OUT_WIDTH && (MLO_IN_WIDTH / MLO_IN_TILE0 ) * MLO_IN_TILE0 == MLO_IN_WIDTH && MLO_IN_HEIGHT == MLO_OUT_HEIGHT && (MLO_IN_HEIGHT / MLO_IN_TILE1 ) * MLO_IN_TILE1 == MLO_IN_HEIGHT)
#define MLO_OUT_ALIGNED 1
#else
#define MLO_OUT_ALIGNED 0
#endif

#define MLO_ALUTILES_STACK_SZ (MLO_N_ALUTILES_PERSTACK*MLO_ALU_TILE_SZ)
#define MLO_N_IN_TILES_TOTAL (MLO_N_IN_TILES_PERSTACK*MLO_N_STACKS)

#define MLO_N_OUT_TILE_BLOCKS0 ((MLO_OUT_WIDTH+MLO_IN_TILE0-1)/MLO_IN_TILE0)
#define MLO_N_OUT_TILE_BLOCKS1 ((MLO_OUT_HEIGHT+MLO_IN_TILE1-1)/MLO_IN_TILE1)
#define MLO_N_IN_PACKS  (MLO_N_INPUTS/MLO_N_IN_TILES_PERSTACK)

#define MLO_N_IN_READ (MLO_N_IN_PACKS*MLO_N_IN_TILES_PERSTACK)
#if MLO_N_IN_READ == MLO_N_INPUTS
#define MLO_INPUTS_ALIGNED 1
#else
#define MLO_INPUTS_ALIGNED 0
#endif

#define MLO_N_OUT_PACKS  (MLO_N_OUTPUTS/MLO_N_OUT_TILES_PERSTACK)
#if MLO_N_OUT_PACKS*MLO_N_OUT_TILES_PERSTACK == MLO_N_OUTPUTS && MLO_N_OUT_TILES_PERSTACK != MLO_N_OUTPUTS
#define MLO_OUTPUTS_ALIGNED 1
#else
#define MLO_OUTPUTS_ALIGNED 0
#endif

#define MLO_N_BATCH_PACKS (MLO_BATCH_SZ/MLO_N_STACKS)
#if MLO_N_BATCH_PACKS*MLO_N_STACKS == MLO_BATCH_SZ && MLO_N_STACKS != MLO_BATCH_SZ
#define MLO_BATCH_ALIGNED 1
#else
#define MLO_BATCH_ALIGNED 0
#endif

#define MLO_IN_LCL_WIDTH (MLO_IN_TILE0 + MLO_FILTER_SIZE0 - 1)  // here we use kernel size. it's important when padding == 0
#define MLO_IN_LCL_HEIGHT (MLO_IN_TILE1 + MLO_FILTER_SIZE1 - 1)
#define MLO_IN_LCL_TILE_SZ (MLO_IN_LCL_WIDTH*MLO_IN_LCL_HEIGHT)
#define MLO_IN_LCL_PERSTACK_SZ (MLO_IN_LCL_TILE_SZ*MLO_N_IN_TILES_PERSTACK)
#define MLO_IN_LCL_SZ (MLO_IN_LCL_PERSTACK_SZ*MLO_N_STACKS)

#define MLO_WEIGHTS_SZ (MLO_N_OUT_TILES_PERSTACK*MLO_N_IN_TILES_PERSTACK*MLO_FILTER_SZ)

#define MLO_PVT_ACCUM_DATA_SZ (MLO_N_OUT_TILES * MLO_OUT_TILE_SZ)
#define MLO_PVT_IN_WIDTH (MLO_FILTER_SIZE0 + MLO_OUT_PIX_TILE0 - 1)
#define MLO_PVT_IN_HEIGHT (MLO_OUT_PIX_TILE1)

#define MLO_LCL_WEIGHTS 1

inline void calculateXYPos(int linPos, int width, int *x, int *y)
{

	(*y) = (int)((float)linPos / (float)width + 0.00001f);

	(*x) = linPos - (*y) * width;
}

inline int calculateOffset(int stride, int x, int y)
{
	int ret = y * stride + x;
	return(ret);
}

inline void readDataElem(int linPos,__local _FLOAT *lcl_data, int lcl_base, int lcl_height, int lcl_width, int lcl_stride, int lcl_y, int lcl_x,
					 const __global _FLOAT * gbl_data, int gbl_base, int gbl_height, int gbl_width, int gbl_stride, int gbl_y, int gbl_x,
					 bool vis,
					 bool debug)
{
	int x, y;
	calculateXYPos(linPos, lcl_width, &x, &y);
	int g_x = x + gbl_x;
	int g_y = y + gbl_y;
	int gbl_off0 = calculateOffset(gbl_stride, g_x, g_y);
	int gbl_off = gbl_off0 + gbl_base;

	int l_x = x + lcl_x;
	int l_y = y + lcl_y;
	int lcl_off = lcl_base +
#if MLO_LARGE_MAP == 1
		linPos
#else
		mad24(l_y, lcl_stride, l_x);
#endif
	 ;

#if MLO_LARGE_MAP == 1
	 vis &= (g_x >= 0 && g_x < gbl_width && g_y >= 0 && g_y < gbl_height);
#endif
	 gbl_off = (vis) ? gbl_off : 0;
	 _FLOAT gbl_val = gbl_data[gbl_off];
	 gbl_val = (vis) ? gbl_val : 0;

	lcl_data[lcl_off] = gbl_val;

}

inline void readData(int lcl_id, int size, int lcl_p_stride, __local _FLOAT *lcl_data, int lcl_base, int lcl_height, int lcl_width, int lcl_stride, int lcl_y, int lcl_x,
					 const __global _FLOAT * gbl_data, int gbl_base, int gbl_height, int gbl_width, int gbl_stride, int gbl_y, int gbl_x,
					 bool vis,
					 bool debug
					 )
{

	for(int i = lcl_id; i < size; i+= lcl_p_stride)
	{
		readDataElem(i, lcl_data, lcl_base, lcl_height, lcl_width, lcl_stride, lcl_y, lcl_x,
					 gbl_data, gbl_base, gbl_height, gbl_width, gbl_stride, gbl_y, gbl_x,
					 vis,
					 debug);
	}

}

inline void loadData(int lcl_id, int lcl_p_stride,
					__local _FLOAT * lcl_data,
					int lcl_off, int lcl_size, int lcl_height, int lcl_width, int lcl_stride, int lcl_bot_y, int lcl_bot_x,
					const __global _FLOAT * gbl_data,
					int gbl_off, int gbl_size, int gbl_height, int glb_width, int gbl_stride, int gbl_bot_y, int gbl_bot_x,
					int buf_block_ind, int max_n_bufs, int lcl_n_bufs,
					bool debug)
{

	for(int c = 0; c < lcl_n_bufs;
		 ++c, lcl_off += lcl_size, gbl_off += gbl_size )
	{
		bool vis = (buf_block_ind + c <  max_n_bufs);
		readData(lcl_id, lcl_size, lcl_p_stride,
				 lcl_data, lcl_off, lcl_height, lcl_width, lcl_stride, lcl_bot_y, lcl_bot_x,
				 gbl_data, gbl_off, gbl_height, glb_width, gbl_stride, gbl_bot_y, gbl_bot_x,
				 vis,
				 (debug));
	}

}

inline void Conv(int o_map_base,
				int in_stg_off,
				 _FLOAT *pvt_in_stage, __local _FLOAT * lcl_indata,
				 _FLOAT *pvt_wei_stage, __local _FLOAT * lcl_wei,
				 _FLOAT *pvt_accum
				 )
{
// convolution

		// over all inputs in stack
		int in_stg_off1 = in_stg_off;
		for(int i_c = 0; i_c < MLO_N_IN_TILES_PERSTACK; ++i_c, in_stg_off1 += MLO_IN_LCL_TILE_SZ)
		{
        // preload input
			int wei_stg_base_off = mad24(o_map_base, (int)(MLO_N_IN_TILES_PERSTACK*MLO_FILTER_SZ), mul24(i_c,(int)MLO_FILTER_SZ));
			int in_stg_off2 = in_stg_off1;
			for(int j = 0; j < MLO_PVT_IN_HEIGHT-1; ++j, in_stg_off2+=MLO_IN_LCL_WIDTH
					)
			{
				for(int i = 0; i < MLO_PVT_IN_WIDTH; ++i)
				{
					pvt_in_stage[j*MLO_PVT_IN_WIDTH + i] = lcl_indata[in_stg_off2 + i];
				}
			}

		// over filter rows
			for(int k = 0; k < MLO_FILTER_SIZE1; ++k, in_stg_off2+=MLO_IN_LCL_WIDTH
			)
			{
				int k_act = 0;
#if MLO_DIR_FORWARD==1
				k_act = k;
#else
// load filter in reverse order
				k_act = MLO_FILTER_SIZE1 - 1 - k;
#endif
		// load next input row
				for(int i_pvt = 0; i_pvt < MLO_PVT_IN_WIDTH; ++i_pvt)
				{
					pvt_in_stage[(MLO_PVT_IN_HEIGHT-1)*MLO_PVT_IN_WIDTH + i_pvt] = lcl_indata[in_stg_off2 + i_pvt];
				}

		// over all outputs
				for(int o_c = 0; o_c < MLO_N_OUT_TILES; ++o_c)
				{
					int wei_stg_off = wei_stg_base_off + o_c * MLO_N_IN_TILES_PERSTACK*MLO_FILTER_SZ + k_act * MLO_FILTER_SIZE0;
					for(int i = 0; i < MLO_FILTER_SIZE0; ++i)
					{
						pvt_wei_stage[i] = lcl_wei[wei_stg_off + i];
					}

		// actual conv

					for( int j = 0; j < MLO_OUT_PIX_TILE1; ++j)
					{
						for(int i = 0; i < MLO_OUT_PIX_TILE0; ++i)
						{
							for(int l = 0; l < MLO_FILTER_SIZE0; ++l)
							{

								int l_act = 0;
#if MLO_DIR_FORWARD==1
								l_act = l;

#else
// in reverse horizontal and vertical orders
								l_act = MLO_FILTER_SIZE0 - 1 - l;

#endif

								pvt_accum[(o_c * MLO_OUT_PIX_TILE1 + j) * MLO_OUT_PIX_TILE0 + i]
									 += pvt_in_stage[j * MLO_PVT_IN_WIDTH + i + l] * pvt_wei_stage[l_act];

							}

						}
					}

				} // for(int o_c = 0; o_c < MLO_N_OUT_TILES; ++o_c)

               // move data up
				for(int j = 0; j < MLO_PVT_IN_HEIGHT-1; ++j)
				{
					for(int i = 0; i < MLO_PVT_IN_WIDTH; ++i)
					{
						pvt_in_stage[j*MLO_PVT_IN_WIDTH + i] = pvt_in_stage[(j+1)*MLO_PVT_IN_WIDTH + i];
					}
				}

//				mem_fence(CLK_LOCAL_MEM_FENCE);

			} // for(int k = 0; k < MLO_FILER_SIZE1; ++k,in_stg_off2+=MLO_IN_LCL_WIDTH)

		} // for(int i_c = 0; i_c < MLO_N_IN_TILES_PERSTACK; ++i_c, in_stg_off1 += MLO_IN_LCL_PERSTACK_SZ)

}

__attribute__((reqd_work_group_size(MLO_GRP_SZ0, MLO_GRP_SZ1, MLO_GRP_SZ2)))
__kernel void MLOpenConvUniC(
       const __global _FLOAT * in,
       const __global _FLOAT * weights,
#if MLO_CONV_BIAS
       const __global _FLOAT * bias,
#endif
 	  __global _FLOAT *out,
	   _FLOAT padding_val
	   )
{
	__local _FLOAT lcl_indata[MLO_IN_LCL_SZ];
	__local _FLOAT lcl_wei[MLO_WEIGHTS_SZ];
	__private _FLOAT pvt_accum[MLO_PVT_ACCUM_DATA_SZ];
	__private _FLOAT pvt_in_stage[MLO_PVT_IN_HEIGHT * MLO_PVT_IN_WIDTH];
	__private _FLOAT pvt_wei_stage[MLO_FILTER_SIZE0];

	int grp_id0 = get_group_id(0);
	int y_tile_blk = (int)((float)grp_id0 / (float) MLO_N_OUT_TILE_BLOCKS0 + 0.00001f);
	int x_tile_blk = grp_id0 - mul24(y_tile_blk, (int)MLO_N_OUT_TILE_BLOCKS0);
	int o_pack = get_group_id(1); // block of outputs
	int b_pack = get_group_id(2); // batch block

	int lcl_id = get_local_id(0);
	int stack = (int)((float)lcl_id/(float)MLO_ALUTILES_STACK_SZ + 0.00001f);  // stack
	int alu_stack_id = lcl_id - mul24(stack, (int)MLO_ALUTILES_STACK_SZ);  // alu index in stack
// ALU plane inside stack
	int alu_out_plane_id = (int)((float)alu_stack_id / (float)MLO_ALU_TILE_SZ + 0.00001f);  // alu output plane index
	int alu_out_id = alu_stack_id - mul24(alu_out_plane_id, (int)MLO_ALU_TILE_SZ); // alu index inside an ALU output plane
// pos inside ALU tile
	int alu_tl1 = (int)((float)alu_out_id/(float)MLO_ALU_VTILE0 + 0.00001f);
	int alu_tl0 = alu_out_id - mul24(alu_tl1, (int)MLO_ALU_VTILE0);

	int o_map_plane = o_pack * MLO_N_OUT_TILES_PERSTACK; // first output maps index per full ALU plane stack
	int o_map_base = alu_out_plane_id*MLO_N_OUT_TILES;  // local output map offset
	int o_map = o_map_plane + o_map_base; // output map index per ALU plane
	int b_index = b_pack * MLO_N_STACKS;

	int wave_id = (int)((float)lcl_id / (float)MLO_N_READ_PROCS + 0.00001f);
	int wave_lcl_id = lcl_id - mul24(wave_id, (int)MLO_N_READ_PROCS);

	int x_grp = x_tile_blk * MLO_IN_TILE0;
	int y_grp = y_tile_blk * MLO_IN_TILE1;

// TO DO: scale
	int x_in_grp = x_grp - MLO_FILTER_PAD0;
	int y_in_grp = y_grp - MLO_FILTER_PAD1;

	int x_in_lcl = alu_tl0 * MLO_OUT_PIX_TILE0;
	int y_in_lcl = alu_tl1 * MLO_OUT_PIX_TILE1;

// base offset to read data from local input data
	int in_stg_off = stack*MLO_IN_LCL_PERSTACK_SZ + (y_in_lcl) * MLO_IN_LCL_WIDTH + x_in_lcl;

    int in_off = b_index * MLO_IN_BATCH_STRIDE;

#if MLO_DIR_FORWARD==1
	int wei_off = mul24(o_map_plane, MLO_N_INPUTS * MLO_FILTER_SZ);
#else
	int wei_off = mul24(o_map_plane,MLO_FILTER_SZ);
#endif

#if MLO_LARGE_MAP == 0
	for(int i = lcl_id; i < MLO_IN_LCL_SZ;  i += MLO_GRP_SZ)
	{
		lcl_indata[i] = 0;
	}
#endif

	for(int i = 0; i < MLO_PVT_ACCUM_DATA_SZ; ++i)
	{
		pvt_accum[i] = 0;
	}

	for(int ic = 0; ic < MLO_N_INPUTS; ic += MLO_N_IN_TILES_PERSTACK, in_off += MLO_IN_CHANNEL_STRIDE*MLO_N_IN_TILES_PERSTACK,
				wei_off += MLO_N_IN_TILES_PERSTACK * MLO_FILTER_SZ
#if MLO_DIR_FORWARD==0
							* MLO_N_OUTPUTS
#endif
	)
	{
		barrier(CLK_LOCAL_MEM_FENCE);

// small map has been read in full continiously into the lDS buffer within padded rect,
// padding has been done on initilization.
// large map calculates padding on the fly and fills it with 0.

#if 1 // all inputs

#if MLO_LARGE_MAP == 1
		int in_lcl_off1 = 0;
		int in_off1 = in_off;
		for(int i_b = 0; i_b < MLO_N_STACKS; ++i_b, in_off1 += MLO_IN_BATCH_STRIDE, in_lcl_off1 += MLO_IN_LCL_PERSTACK_SZ)
		{
			bool vis = true;
#if MLO_BATCH_ALIGNED == 0
			vis &= (b_index + i_b < MLO_BATCH_SZ);
#endif

// over all inputs in stack
			int in_off2 = in_off1;
			int in_lcl_off2 = in_lcl_off1;
			for(int i_c = 0; i_c < MLO_N_IN_TILES_PERSTACK; ++i_c, in_off2 += MLO_IN_CHANNEL_STRIDE, in_lcl_off2 += MLO_IN_LCL_TILE_SZ)
			{
#if MLO_INPUTS_ALIGNED == 0
				vis &= (ic + i_c < MLO_N_INPUTS);
#endif

				int elem_id = lcl_id;
				int lcl_p_stride = MLO_GRP_SZ0;
				int lcl_base = 0;
				int lcl_y = 0;
				int lcl_x = 0;
				int gbl_base = 0;

				readData(elem_id, (MLO_IN_LCL_HEIGHT * MLO_IN_LCL_WIDTH), lcl_p_stride,
						&lcl_indata[in_lcl_off2], lcl_base, MLO_IN_LCL_HEIGHT, MLO_IN_LCL_WIDTH, MLO_IN_LCL_WIDTH, lcl_y, lcl_x,
						&in[in_off2], gbl_base, MLO_IN_HEIGHT, MLO_IN_WIDTH, MLO_IN_STRIDE, y_in_grp, x_in_grp,
						vis,
						true
					 );
			}

		}
#else
		for(int i = wave_id; i < MLO_N_IN_TILES_TOTAL;  i += MLO_N_PROC_WAVES)
		{
		//(MLO_N_STACKS * MLO_N_OUT_TILES_PERSTACK)
			int i_b = (int)((float)i / (float)MLO_N_IN_TILES_PERSTACK + 0.00001f);
			int i_c = i - mul24(i_b, (int)MLO_N_IN_TILES_PERSTACK);

			bool vis = true;

#if MLO_BATCH_ALIGNED == 0
			vis &= (b_index + i_b < MLO_BATCH_SZ);
#endif

#if MLO_INPUTS_ALIGNED == 0
			vis &= (ic + i_c < MLO_N_INPUTS);
#endif
			int in_off2 = in_off + i_b * MLO_IN_BATCH_STRIDE + i_c * MLO_IN_CHANNEL_STRIDE;
			int in_lcl_off2 = i_b * MLO_IN_LCL_PERSTACK_SZ + i_c * MLO_IN_LCL_TILE_SZ;

			int elem_id = wave_lcl_id;
			int lcl_p_stride = MLO_N_READ_PROCS;
			int lcl_base = 0;
			int lcl_y = MLO_FILTER_PAD1;
			int lcl_x = MLO_FILTER_PAD0;
			int gbl_base = 0;

			readData(elem_id, (MLO_IN_HEIGHT * MLO_IN_WIDTH), lcl_p_stride,
						&lcl_indata[in_lcl_off2], lcl_base, MLO_IN_HEIGHT, MLO_IN_WIDTH, MLO_IN_LCL_WIDTH, lcl_y, lcl_x,
						&in[in_off2], gbl_base, MLO_IN_HEIGHT, MLO_IN_WIDTH, MLO_IN_STRIDE, y_grp, x_grp,
						vis,
						true
					 );
		}
#endif

// read inputs and weights
// put weights into LDS

#if 1  // only weights

		for(int i = lcl_id; i < MLO_WEIGHTS_SZ; i += MLO_GRP_SZ)
		{
#if MLO_DIR_FORWARD==1
// here is [tops][bottoms]
			int lcl_o = (int)((float)i / (float)(MLO_N_IN_TILES_PERSTACK * MLO_FILTER_SZ) + 0.00001f);
			int gbl_i = i - mul24(lcl_o, (int)(MLO_N_IN_TILES_PERSTACK * MLO_FILTER_SZ));
			lcl_wei[i] = weights[wei_off + lcl_o * MLO_N_INPUTS * MLO_FILTER_SZ + gbl_i];
#else
// outputs are botoms(inputs))
// inputs are tops(outputs)

			int lcl_o = (int)((float)i/ (float)(MLO_N_OUT_TILES_PERSTACK * MLO_FILTER_SZ) + 0.00001f);
			int gbl_i = i - mul24(lcl_o, (int)(MLO_N_OUT_TILES_PERSTACK * MLO_FILTER_SZ));
			int lcl_c = (int)((float)gbl_i/ (float)MLO_FILTER_SZ + 0.00001f);
			int lcl_i = gbl_i - mul24(lcl_c, (int)MLO_FILTER_SZ);

			int lcl_we_off = mad24(mad24(lcl_c, (int)MLO_N_IN_TILES_PERSTACK, lcl_o), (int)MLO_FILTER_SZ, lcl_i);
			int gbl_we_off = mad24(mad24(lcl_o, (int)MLO_N_OUTPUTS, lcl_c), (int)MLO_FILTER_SZ, wei_off + lcl_i);
			bool within_range = gbl_we_off < (MLO_N_OUTPUTS*MLO_N_INPUTS*MLO_FILTER_SZ);
			gbl_we_off = (within_range) ? gbl_we_off : 0;
			_FLOAT wei = weights[gbl_we_off];
			wei = (within_range) ? wei : 0;
			lcl_wei[lcl_we_off]
				= wei;

#endif

		}

#endif

// over all batch stacks

#endif  // all input

		barrier(CLK_LOCAL_MEM_FENCE);

// convolution
#if MLO_GRP_SZ > MLO_ACTIVE_ALUS
		if (lcl_id < MLO_ACTIVE_ALUS)
#endif
		Conv(o_map_base,
			in_stg_off,
			pvt_in_stage, lcl_indata,
			pvt_wei_stage, lcl_wei,
			pvt_accum
			);

//		barrier(CLK_LOCAL_MEM_FENCE);
	}

#if MLO_GRP_SZ > MLO_ACTIVE_ALUS
	if (lcl_id >= MLO_ACTIVE_ALUS)
	{
		return;
	}
#endif
// write results out
	int x_out_grp = x_grp;
	int y_out_grp = y_grp;
	int x_out_lcl = alu_tl0 * MLO_OUT_PIX_TILE0;
	int y_out_lcl = alu_tl1 * MLO_OUT_PIX_TILE1;

    int out_off = (b_index + stack) * MLO_OUT_BATCH_STRIDE + o_map * MLO_OUT_CHANNEL_STRIDE + (y_out_grp + y_out_lcl) * MLO_OUT_STRIDE + x_out_grp + x_out_lcl;
// over all local stacks
#if MLO_BATCH_ALIGNED == 0
	if (b_index + stack < MLO_BATCH_SZ)
#endif
	{

// over all local outputs
		int out_off1 = out_off;
		for(int o = 0; o < MLO_N_OUT_TILES
						; ++o, out_off1 += MLO_OUT_CHANNEL_STRIDE
						)
		{
// over output tile
			_FLOAT  bias_val = 0;
#if MLO_CONV_BIAS
			bias_val = bias[o_map + o];
#endif
			int out_off2 = out_off1;
			for( int j = 0; j < MLO_OUT_PIX_TILE1; ++j, out_off2 += MLO_OUT_STRIDE)
			{
				for(int i = 0; i < MLO_OUT_PIX_TILE0; ++i)
				{
					if ( true
#if 1 //MLO_OUT_ALIGNED == 0
					&& y_out_lcl + j < MLO_OUT_TILE1 && y_out_grp + y_out_lcl + j < MLO_OUT_HEIGHT &&  x_out_lcl + i < MLO_OUT_TILE0 && x_out_grp + x_out_lcl + i < MLO_OUT_WIDTH
#endif
#if MLO_OUTPUTS_ALIGNED == 0
						&& o_map + o < MLO_N_OUTPUTS
#endif
					)
					{
						out[out_off2 + i] = pvt_accum[o*MLO_OUT_TILE_SZ + j * MLO_OUT_PIX_TILE0 + i] + bias_val;
#if 0
						if ( out_off2 + i == 1 /*y_out_grp + y_out_lcl + j == 2 && x_out_grp + x_out_lcl + i == 0*/)
						{
							printf("K:out: %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d    %f %f %f\n",
								MLO_OUT_TILE1,
								MLO_OUT_TILE0,
								grp_id0,
								lcl_id,
								alu_out_plane_id,
								alu_out_id,
								b_index + stack,
								o,
								o_map,
								out_off,
								out_off1,
								out_off2,
								y_out_grp,
								y_out_lcl,
								x_out_grp,
								x_out_lcl,
								j,
								i,
								pvt_accum[o*MLO_OUT_TILE_SZ + j * MLO_OUT_PIX_TILE0 + i],
								 bias_val,
								out[out_off2 + i]
								);
						}
#endif
					}

				}
			}

		}
	}

}


Implement tone-mapping and gamma correction for traced pixels

// Global parameters that will be set via a template during compilation time.
__constant unsigned int frameW = 512;
__constant unsigned int frameH = 512;
__constant float texelStepX = 1.0 / 512.0;
__constant float texelStepY = 1.0 / 512.0;

// Trace a ray and return the gathered color.
float4 traceRay(float4 rayOrigin, float4 rayDir){
	// For now, just return something so we can test the output
	return fabs(rayDir);
}

// Emit the color of a pixel by tracing a ray through the scene.
__kernel void tracePixel(
		__global float4 *frameBuffer,
		__global float4 *frustrumCorners,
		const float4 eyePos,
		const unsigned int blockY,
		const unsigned int samplesPerPixel,
		const float exposure
){
	// Get pixel coordinates
	unsigned int x = get_global_id(0);
	unsigned int y = get_global_id(1);
	if ( x > frameW || y > frameH ) {
		return;
	}

	// Calculate texel coordinates [0,1] range
	float tx = (float)(x) * texelStepX;
	float ty = (float)(y) * texelStepY;
	float accumScaler = 1.0f / (float)samplesPerPixel;
	float4 accum = (float4)(0,0,0,0);
	for( uint sample=0;sample<samplesPerPixel;sample++){
		// Get ray direction using trilinear interpolation; trace ray and
		// add result to accumulation buffer
		float4 lVec = frustrumCorners[0] * (1 - ty) + frustrumCorners[2] * ty;
		float4 rVec = frustrumCorners[1] * (1 - ty) + frustrumCorners[3] * ty;
		accum += traceRay(eyePos, normalize(lVec * (1 - tx) + rVec * tx));
	}

	//
	// Average samples
	accum *= accumScaler;

	// Apply tone-mapping and gamma correction using:
	// 1 - exp(-hdrColor * exposure)) [tone mapping HDR -> LDR]
	// pow(ldr, 0.45)) [gamma correction]
	frameBuffer[y * frameW + x] = pow(-expm1(-accum*exposure), 0.45f);
}

// Global parameters that will be set via a template during compilation time.
__constant unsigned int frameW = 512;
__constant unsigned int frameH = 512;
__constant float texelStepX = 1.0 / 512.0;
__constant float texelStepY = 1.0 / 512.0;

// Trace a ray and return the gathered color.
float4 traceRay(float4 rayOrigin, float4 rayDir){
	// For now, just return something so we can test the output
	return fabs(rayDir);
}

// Emit the color of a pixel by tracing a ray through the scene.
__kernel void tracePixel(
		__global float4 *frameBuffer,
		__global float4 *frustrumCorners,
		const float4 eyePos,
		const unsigned int blockY,
		const unsigned int samplesPerPixel,
		const float exposure
){
	// Get pixel coordinates
	unsigned int x = get_global_id(0);
	unsigned int y = get_global_id(1);
	if ( x > frameW || y > frameH ) {
		return;
	}

	// Calculate texel coordinates [0,1] range
	float tx = (float)(x) * texelStepX;
	float ty = (float)(y) * texelStepY;
	float accumScaler = 1.0f / (float)samplesPerPixel;
	float4 accum = (float4)(0,0,0,0);
	for( uint sample=0;sample<samplesPerPixel;sample++){
		// Get ray direction using trilinear interpolation; trace ray and
		// add result to accumulation buffer
		float4 lVec = frustrumCorners[0] * (1 - ty) + frustrumCorners[2] * ty;
		float4 rVec = frustrumCorners[1] * (1 - ty) + frustrumCorners[3] * ty;
		accum += traceRay(eyePos, normalize(lVec * (1 - tx) + rVec * tx));
	}

	frameBuffer[y * frameW + x] = accum * accumScaler;
}


simplified Sersic source coefficients

simplified Sersic source coefficients

type = SOURCE;

params
{
    { "x",   POSITION_X },
    { "y",   POSITION_Y },
    { "r",   RADIUS     },
    { "mag", MAGNITUDE  },
    { "n",   PARAMETER, { 0.5f, 8.0f } },
    { "q",   AXIS_RATIO },
    { "pa",  POS_ANGLE  }
};

data
{
    float2 x;   // source position
    mat22 t;    // coordinate transformation matrix
    float log0; // profile constants
    float log1;
    float m;
};

static float brightness(local data* this, float2 x)
{
    float2 y = mv22(this->t, x - this->x);
    return exp(this->log0 - exp(this->log1 + this->m*log(dot(y, y))));
}

static void set(local data* this, float x, float y, float r, float mag, float n, float q, float a)
{
    float b = 1.9992f*n - 0.3271f; // approximation valid for 0.5 < n < 8

    float c = cos(a*DEG2RAD);
    float s = sin(a*DEG2RAD);

    // source position
    this->x = (float2)(x, y);

    // transformation matrix: rotate and scale
    this->t = (mat22)(q*c, q*s, -s, c)/sqrt(q);

    this->log0 = -0.4f*mag*LOG_10 + 2*n*log(b) - LOG_PI - 2*log(r) - log(tgamma(2*n+1));
    this->log1 = log(b) - log(r)/n;
    this->m = 0.5f/n;
}

type = SOURCE;

params
{
    { "x",   POSITION_X },
    { "y",   POSITION_Y },
    { "r",   RADIUS     },
    { "mag", MAGNITUDE  },
    { "n",   PARAMETER, { 0.5f, 8.0f } },
    { "q",   AXIS_RATIO },
    { "pa",  POS_ANGLE  }
};

data
{
    float2 x;   // source position
    mat22 t;    // coordinate transformation matrix
    float log0; // profile constants
    float log1;
    float m;
};

static float brightness(local data* this, float2 x)
{
    float2 y = mv22(this->t, x - this->x);
    return exp(this->log0 - exp(this->log1 + this->m*log(dot(y, y))));
}

static void set(local data* this, float x, float y, float r, float mag, float n, float q, float a)
{
    float b = 1.9992f*n - 0.3271f; // approximation valid for 0.5 < n < 8

    float c = cos(a*DEG2RAD);
    float s = sin(a*DEG2RAD);

    // source position
    this->x = (float2)(x, y);

    // transformation matrix: rotate and scale
    this->t = (mat22)(q*c, q*s, -s, c);

    this->log0 = -0.4f*mag*LOG_10 + 2*n*log(b) - LOG_PI - 2*log(r) - log(tgamma(2*n+1));
    this->log1 = log(b) - (0.5f*log(q) + log(r))/n;
    this->m = 0.5f/n;
}