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

/**
 * \file feedback.c
 * Selection and feedback modes functions.
 */


#include "util/glheader.h"
#include "c99_alloca.h"
#include "context.h"
#include "enums.h"
#include "feedback.h"
#include "macros.h"
#include "mtypes.h"
#include "api_exec_decl.h"
#include "bufferobj.h"

#include "state_tracker/st_cb_feedback.h"

#define FB_3D		0x01
#define FB_4D		0x02
#define FB_COLOR	0x04
#define FB_TEXTURE	0X08



void GLAPIENTRY
_mesa_FeedbackBuffer( GLsizei size, GLenum type, GLfloat *buffer )
{
   GET_CURRENT_CONTEXT(ctx);

   if (ctx->RenderMode==GL_FEEDBACK) {
      _mesa_error( ctx, GL_INVALID_OPERATION, "glFeedbackBuffer" );
      return;
   }
   if (size<0) {
      _mesa_error( ctx, GL_INVALID_VALUE, "glFeedbackBuffer(size<0)" );
      return;
   }
   if (!buffer && size > 0) {
      _mesa_error( ctx, GL_INVALID_VALUE, "glFeedbackBuffer(buffer==NULL)" );
      ctx->Feedback.BufferSize = 0;
      return;
   }

   switch (type) {
      case GL_2D:
	 ctx->Feedback._Mask = 0;
	 break;
      case GL_3D:
	 ctx->Feedback._Mask = FB_3D;
	 break;
      case GL_3D_COLOR:
	 ctx->Feedback._Mask = (FB_3D | FB_COLOR);
	 break;
      case GL_3D_COLOR_TEXTURE:
	 ctx->Feedback._Mask = (FB_3D | FB_COLOR | FB_TEXTURE);
	 break;
      case GL_4D_COLOR_TEXTURE:
	 ctx->Feedback._Mask = (FB_3D | FB_4D | FB_COLOR | FB_TEXTURE);
	 break;
      default:
         _mesa_error( ctx, GL_INVALID_ENUM, "glFeedbackBuffer" );
	 return;
   }

   FLUSH_VERTICES(ctx, _NEW_RENDERMODE, 0); /* Always flush */
   ctx->Feedback.Type = type;
   ctx->Feedback.BufferSize = size;
   ctx->Feedback.Buffer = buffer;
   ctx->Feedback.Count = 0;	              /* Because of this. */
}


void GLAPIENTRY
_mesa_PassThrough( GLfloat token )
{
   GET_CURRENT_CONTEXT(ctx);

   if (ctx->RenderMode==GL_FEEDBACK) {
      FLUSH_VERTICES(ctx, 0, 0);
      _mesa_feedback_token( ctx, (GLfloat) (GLint) GL_PASS_THROUGH_TOKEN );
      _mesa_feedback_token( ctx, token );
   }
}


/**
 * Put a vertex into the feedback buffer.
 */
void
_mesa_feedback_vertex(struct gl_context *ctx,
                      const GLfloat win[4],
                      const GLfloat color[4],
                      const GLfloat texcoord[4])
{
   _mesa_feedback_token( ctx, win[0] );
   _mesa_feedback_token( ctx, win[1] );
   if (ctx->Feedback._Mask & FB_3D) {
      _mesa_feedback_token( ctx, win[2] );
   }
   if (ctx->Feedback._Mask & FB_4D) {
      _mesa_feedback_token( ctx, win[3] );
   }
   if (ctx->Feedback._Mask & FB_COLOR) {
      _mesa_feedback_token( ctx, color[0] );
      _mesa_feedback_token( ctx, color[1] );
      _mesa_feedback_token( ctx, color[2] );
      _mesa_feedback_token( ctx, color[3] );
   }
   if (ctx->Feedback._Mask & FB_TEXTURE) {
      _mesa_feedback_token( ctx, texcoord[0] );
      _mesa_feedback_token( ctx, texcoord[1] );
      _mesa_feedback_token( ctx, texcoord[2] );
      _mesa_feedback_token( ctx, texcoord[3] );
   }
}


/**********************************************************************/
/** \name Selection */
/*@{*/

/**
 * Establish a buffer for selection mode values.
 * 
 * \param size buffer size.
 * \param buffer buffer.
 *
 * \sa glSelectBuffer().
 * 
 * \note this function can't be put in a display list.
 * 
 * Verifies we're not in selection mode, flushes the vertices and initialize
 * the fields in __struct gl_contextRec::Select with the given buffer.
 */
void GLAPIENTRY
_mesa_SelectBuffer( GLsizei size, GLuint *buffer )
{
   GET_CURRENT_CONTEXT(ctx);

   if (size < 0) {
      _mesa_error(ctx, GL_INVALID_VALUE, "glSelectBuffer(size)");
      return;
   }

   if (ctx->RenderMode==GL_SELECT) {
      _mesa_error( ctx, GL_INVALID_OPERATION, "glSelectBuffer" );
      return;			/* KW: added return */
   }

   FLUSH_VERTICES(ctx, _NEW_RENDERMODE, 0);
   ctx->Select.Buffer = buffer;
   ctx->Select.BufferSize = size;
   ctx->Select.BufferCount = 0;
   ctx->Select.HitFlag = GL_FALSE;
   ctx->Select.HitMinZ = 1.0;
   ctx->Select.HitMaxZ = 0.0;
}


/**
 * Write a value of a record into the selection buffer.
 * 
 * \param ctx GL context.
 * \param value value.
 *
 * Verifies there is free space in the buffer to write the value and
 * increments the pointer.
 */
static inline void
write_record(struct gl_context *ctx, GLuint value)
{
   if (ctx->Select.BufferCount < ctx->Select.BufferSize) {
      ctx->Select.Buffer[ctx->Select.BufferCount] = value;
   }
   ctx->Select.BufferCount++;
}


/**
 * Update the hit flag and the maximum and minimum depth values.
 *
 * \param ctx GL context.
 * \param z depth.
 *
 * Sets gl_selection::HitFlag and updates gl_selection::HitMinZ and
 * gl_selection::HitMaxZ.
 */
void
_mesa_update_hitflag(struct gl_context *ctx, GLfloat z)
{
   ctx->Select.HitFlag = GL_TRUE;
   if (z < ctx->Select.HitMinZ) {
      ctx->Select.HitMinZ = z;
   }
   if (z > ctx->Select.HitMaxZ) {
      ctx->Select.HitMaxZ = z;
   }
}

static void
alloc_select_resource(struct gl_context *ctx)
{
   struct gl_selection *s = &ctx->Select;

   if (!ctx->Const.HardwareAcceleratedSelect)
      return;

   if (!ctx->Dispatch.HWSelectModeBeginEnd) {
      ctx->Dispatch.HWSelectModeBeginEnd = _mesa_alloc_dispatch_table(false);
      if (!ctx->Dispatch.HWSelectModeBeginEnd) {
         _mesa_error(ctx, GL_OUT_OF_MEMORY, "Cannot allocate HWSelectModeBeginEnd");
         return;
      }
      vbo_init_dispatch_hw_select_begin_end(ctx);
   }

   if (!s->SaveBuffer) {
      s->SaveBuffer = malloc(NAME_STACK_BUFFER_SIZE);
      if (!s->SaveBuffer) {
         _mesa_error(ctx, GL_OUT_OF_MEMORY, "Cannot allocate name stack save buffer");
         return;
      }
   }

   if (!s->Result) {
      s->Result = _mesa_bufferobj_alloc(ctx, -1);
      if (!s->Result) {
         _mesa_error(ctx, GL_OUT_OF_MEMORY, "Cannot allocate select result buffer");
         return;
      }

      GLuint init_result[MAX_NAME_STACK_RESULT_NUM * 3];
      for (int i = 0; i < MAX_NAME_STACK_RESULT_NUM; i++) {
         init_result[i * 3] = 0;              /* hit */
         init_result[i * 3 + 1] = 0xffffffff; /* minz */
         init_result[i * 3 + 2] = 0;          /* maxz */
      }

      bool success = _mesa_bufferobj_data(ctx,
                                          GL_SHADER_STORAGE_BUFFER,
                                          sizeof(init_result),
                                          init_result,
                                          GL_STATIC_DRAW, 0,
                                          s->Result);
      if (!success) {
         _mesa_reference_buffer_object(ctx, &s->Result, NULL);
         _mesa_error(ctx, GL_OUT_OF_MEMORY, "Cannot init result buffer");
         return;
      }
   }
}

static bool
save_used_name_stack(struct gl_context *ctx)
{
   struct gl_selection *s = &ctx->Select;

   if (!ctx->Const.HardwareAcceleratedSelect)
      return false;

   /* We have two kinds of name stack user:
    *   1. glRasterPos (CPU based) will set HitFlag
    *   2. draw call for GPU will set ResultUsed
    */
   if (!s->ResultUsed && !s->HitFlag)
      return false;

   void *save = (char *)s->SaveBuffer + s->SaveBufferTail;

   /* save meta data */
   uint8_t *metadata = save;
   metadata[0] = s->HitFlag;
   metadata[1] = s->ResultUsed;
   metadata[2] = s->NameStackDepth;
   metadata[3] = 0;

   /* save hit data */
   int index = 1;
   if (s->HitFlag) {
      float *hit = save;
      hit[index++] = s->HitMinZ;
      hit[index++] = s->HitMaxZ;
   }

   /* save name stack */
   memcpy((uint32_t *)save + index, s->NameStack, s->NameStackDepth * sizeof(GLuint));
   index += s->NameStackDepth;

   s->SaveBufferTail += index * sizeof(GLuint);
   s->SavedStackNum++;

   /* if current slot has been used, store result to next slot in result buffer */
   if (s->ResultUsed)
      s->ResultOffset += 3 * sizeof(GLuint);

   /* reset fields */
   s->HitFlag = GL_FALSE;
   s->HitMinZ = 1.0;
   s->HitMaxZ = 0;

   s->ResultUsed = GL_FALSE;

   /* return true if we have no enough space for the next name stack data */
   return s->ResultOffset >= MAX_NAME_STACK_RESULT_NUM * 3 * sizeof(GLuint) ||
      s->SaveBufferTail >= NAME_STACK_BUFFER_SIZE - (MAX_NAME_STACK_DEPTH + 3) * sizeof(GLuint);
}

static void
update_hit_record(struct gl_context *ctx)
{
   struct gl_selection *s = &ctx->Select;

   if (ctx->Const.HardwareAcceleratedSelect) {
      if (!s->SavedStackNum)
         return;

      unsigned size = s->ResultOffset;
      GLuint *result = size ? alloca(size) : NULL;
      _mesa_bufferobj_get_subdata(ctx, 0, size, result, s->Result);

      unsigned index = 0;
      unsigned *save = s->SaveBuffer;
      for (int i = 0; i < s->SavedStackNum; i++) {
         uint8_t *metadata = (uint8_t *)(save++);

         unsigned zmin, zmax;
         bool cpu_hit = !!metadata[0];
         if (cpu_hit) {
            /* map [0, 1] to [0, UINT_MAX]*/
            zmin = (unsigned) ((float)(~0u) * *(float *)(save++));
            zmax = (unsigned) ((float)(~0u) * *(float *)(save++));
         } else {
            zmin = ~0u;
            zmax = 0;
         }

         bool gpu_hit = false;
         if (metadata[1]) {
            gpu_hit = !!result[index];

            if (gpu_hit) {
               zmin = MIN2(zmin, result[index + 1]);
               zmax = MAX2(zmax, result[index + 2]);

               /* reset data */
               result[index]     = 0;          /* hit */
               result[index + 1] = 0xffffffff; /* minz */
               result[index + 2] = 0;          /* maxz */
            }
            index += 3;
         }

         int depth = metadata[2];
         if (cpu_hit || gpu_hit) {
            /* hit */
            write_record(ctx, depth);
            write_record(ctx, zmin);
            write_record(ctx, zmax);

            for (int j = 0; j < depth; j++)
               write_record(ctx, save[j]);
            s->Hits++;
         }
         save += depth;
      }

      /* reset result buffer */
      _mesa_bufferobj_subdata(ctx, 0, size, result, s->Result);

      s->SaveBufferTail = 0;
      s->SavedStackNum = 0;
      s->ResultOffset = 0;
   } else {
      if (!s->HitFlag)
         return;

      /* HitMinZ and HitMaxZ are in [0,1].  Multiply these values by */
      /* 2^32-1 and round to nearest unsigned integer. */
      GLuint zscale = (~0u);
      GLuint zmin = (GLuint) ((GLfloat) zscale * s->HitMinZ);
      GLuint zmax = (GLuint) ((GLfloat) zscale * s->HitMaxZ);

      write_record(ctx, s->NameStackDepth);
      write_record(ctx, zmin);
      write_record(ctx, zmax);
      for (int i = 0; i < s->NameStackDepth; i++)
         write_record(ctx, s->NameStack[i]);

      s->HitFlag = GL_FALSE;
      s->HitMinZ = 1.0;
      s->HitMaxZ = -1.0;

      s->Hits++;
   }
}

static void
reset_name_stack_to_empty(struct gl_context *ctx)
{
   struct gl_selection *s = &ctx->Select;

   s->NameStackDepth = 0;
   s->HitFlag = GL_FALSE;
   s->HitMinZ = 1.0;
   s->HitMaxZ = 0.0;

   if (ctx->Const.HardwareAcceleratedSelect) {
      s->SaveBufferTail = 0;
      s->SavedStackNum = 0;
      s->ResultUsed = GL_FALSE;
      s->ResultOffset = 0;
   }
}

/**
 * Initialize the name stack.
 */
void GLAPIENTRY
_mesa_InitNames( void )
{
   GET_CURRENT_CONTEXT(ctx);

   /* Calls to glInitNames while the render mode is not GL_SELECT are ignored. */
   if (ctx->RenderMode != GL_SELECT)
      return;

   FLUSH_VERTICES(ctx, 0, 0);

   save_used_name_stack(ctx);
   update_hit_record(ctx);

   reset_name_stack_to_empty(ctx);

   ctx->NewState |= _NEW_RENDERMODE;
}


/**
 * Load the top-most name of the name stack.
 *
 * \param name name.
 */
void GLAPIENTRY
_mesa_LoadName( GLuint name )
{
   GET_CURRENT_CONTEXT(ctx);

   if (ctx->RenderMode != GL_SELECT) {
      return;
   }
   if (ctx->Select.NameStackDepth == 0) {
      _mesa_error( ctx, GL_INVALID_OPERATION, "glLoadName" );
      return;
   }

   if (!ctx->Const.HardwareAcceleratedSelect || save_used_name_stack(ctx)) {
      FLUSH_VERTICES(ctx, 0, 0);
      update_hit_record(ctx);
   }

   ctx->Select.NameStack[ctx->Select.NameStackDepth-1] = name;
   ctx->NewState |= _NEW_RENDERMODE;
}


/**
 * Push a name into the name stack.
 *
 * \param name name.
 */
void GLAPIENTRY
_mesa_PushName( GLuint name )
{
   GET_CURRENT_CONTEXT(ctx);

   if (ctx->RenderMode != GL_SELECT) {
      return;
   }

   if (ctx->Select.NameStackDepth >= MAX_NAME_STACK_DEPTH) {
      _mesa_error( ctx, GL_STACK_OVERFLOW, "glPushName" );
      return;
   }

   if (!ctx->Const.HardwareAcceleratedSelect || save_used_name_stack(ctx)) {
      FLUSH_VERTICES(ctx, 0, 0);
      update_hit_record(ctx);
   }

   ctx->Select.NameStack[ctx->Select.NameStackDepth++] = name;
   ctx->NewState |= _NEW_RENDERMODE;
}


/**
 * Pop a name into the name stack.
 */
void GLAPIENTRY
_mesa_PopName( void )
{
   GET_CURRENT_CONTEXT(ctx);

   if (ctx->RenderMode != GL_SELECT) {
      return;
   }

   if (ctx->Select.NameStackDepth == 0) {
      _mesa_error( ctx, GL_STACK_UNDERFLOW, "glPopName" );
      return;
   }

   if (!ctx->Const.HardwareAcceleratedSelect || save_used_name_stack(ctx)) {
      FLUSH_VERTICES(ctx, 0, 0);
      update_hit_record(ctx);
   }

   ctx->Select.NameStackDepth--;
   ctx->NewState |= _NEW_RENDERMODE;
}

/*@}*/


/**********************************************************************/
/** \name Render Mode */
/*@{*/

/**
 * Set rasterization mode.
 *
 * \param mode rasterization mode.
 *
 * \note this function can't be put in a display list.
 *
 * \sa glRenderMode().
 * 
 * Flushes the vertices and do the necessary cleanup according to the previous
 * rasterization mode, such as writing the hit record or resent the select
 * buffer index when exiting the select mode. Updates
 * __struct gl_contextRec::RenderMode and notifies the driver via the
 * dd_function_table::RenderMode callback.
 */
GLint GLAPIENTRY
_mesa_RenderMode( GLenum mode )
{
   GET_CURRENT_CONTEXT(ctx);
   GLint result;
   ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, 0);

   if (MESA_VERBOSE & VERBOSE_API)
      _mesa_debug(ctx, "glRenderMode %s\n", _mesa_enum_to_string(mode));

   FLUSH_VERTICES(ctx, _NEW_RENDERMODE | _NEW_FF_VERT_PROGRAM |
                  _NEW_FF_FRAG_PROGRAM, 0);

   switch (ctx->RenderMode) {
      case GL_RENDER:
	 result = 0;
	 break;
      case GL_SELECT:
	 save_used_name_stack(ctx);
	 update_hit_record(ctx);

	 if (ctx->Select.BufferCount > ctx->Select.BufferSize) {
	    /* overflow */
#ifndef NDEBUG
            _mesa_warning(ctx, "Feedback buffer overflow");
#endif
	    result = -1;
	 }
	 else {
	    result = ctx->Select.Hits;
	 }
	 ctx->Select.BufferCount = 0;
	 ctx->Select.Hits = 0;
	 /* name stack should be in empty state after exiting GL_SELECT mode */
	 reset_name_stack_to_empty(ctx);
	 break;
      case GL_FEEDBACK:
	 if (ctx->Feedback.Count > ctx->Feedback.BufferSize) {
	    /* overflow */
	    result = -1;
	 }
	 else {
	    result = ctx->Feedback.Count;
	 }
	 ctx->Feedback.Count = 0;
	 break;
      default:
	 _mesa_error( ctx, GL_INVALID_ENUM, "glRenderMode" );
	 return 0;
   }

   switch (mode) {
      case GL_RENDER:
         break;
      case GL_SELECT:
	 if (ctx->Select.BufferSize==0) {
	    /* haven't called glSelectBuffer yet */
	    _mesa_error( ctx, GL_INVALID_OPERATION, "glRenderMode" );
	 }
	 alloc_select_resource(ctx);
	 break;
      case GL_FEEDBACK:
	 if (ctx->Feedback.BufferSize==0) {
	    /* haven't called glFeedbackBuffer yet */
	    _mesa_error( ctx, GL_INVALID_OPERATION, "glRenderMode" );
	 }
	 break;
      default:
	 _mesa_error( ctx, GL_INVALID_ENUM, "glRenderMode" );
	 return 0;
   }

   st_RenderMode( ctx, mode );

   /* finally update render mode to new one */
   ctx->RenderMode = mode;

   return result;
}

/*@}*/


/**********************************************************************/
/** \name Initialization */
/*@{*/

/**
 * Initialize context feedback data.
 */
void _mesa_init_feedback( struct gl_context * ctx )
{
   /* Feedback */
   ctx->Feedback.Type = GL_2D;   /* TODO: verify */
   ctx->Feedback.Buffer = NULL;
   ctx->Feedback.BufferSize = 0;
   ctx->Feedback.Count = 0;

   /* Selection/picking */
   ctx->Select.Buffer = NULL;
   ctx->Select.BufferSize = 0;
   ctx->Select.BufferCount = 0;
   ctx->Select.Hits = 0;
   ctx->Select.NameStackDepth = 0;

   /* Miscellaneous */
   ctx->RenderMode = GL_RENDER;
}

void _mesa_free_feedback(struct gl_context * ctx)
{
   struct gl_selection *s = &ctx->Select;

   free(s->SaveBuffer);
   _mesa_reference_buffer_object(ctx, &s->Result, NULL);
}

/*@}*/
