void VVirtualThumbStick::Reset()
{
  m_fXValue = 0.0f;
  m_fYValue = 0.0f;
  m_iLastTouchPointIndex = -1;

  // (Re)position thumb stick
  const VRectanglef finalValidArea = m_spTouchArea->GetArea();

  // Outer ring mask
  const float fInitialX = finalValidArea.m_vMin.x + finalValidArea.GetSizeX() * m_fRelativeInitialX;
  const float fInitialY = finalValidArea.m_vMin.y + finalValidArea.GetSizeY() * m_fRelativeInitialY;

  m_spRingMask->GetTextureSize(m_iRingWidth, m_iRingHeight);
  m_spRingMask->SetPos(
    fInitialX - static_cast<float>(m_iRingWidth / 2), 
    fInitialY - static_cast<float>(m_iRingHeight / 2));  

  // Inner circle mask
  m_iCircleCenterX = static_cast<int>(fInitialX);
  m_iCircleCenterY = static_cast<int>(fInitialY);

  m_spCircleMask->GetTextureSize(m_iCircleWidth, m_iCircleHeight);
  m_spCircleMask->SetPos(
    fInitialX - static_cast<float>(m_iCircleWidth / 2), 
    fInitialY - static_cast<float>(m_iCircleHeight / 2));
}
int VRTLSupport_cl::DistanceToRightAlignment(VisFont_cl * pFont, const char * pText) {

  VASSERT(pFont);

  VRectanglef requiredSpace;
  pFont->GetTextDimension(pText, requiredSpace);

  return (int)-requiredSpace.GetSizeX();
}
void VLogoOverlay::RefreshLayout()
{
  if (m_spLogoOverlay == NULL)
    return;

  float fWidth = 0.0f, fHeight = 0.0f;
  m_spLogoOverlay->GetTargetSize(fWidth, fHeight);

  const VRectanglef screenExtents = GetScreenExtents();
  const float fVerticalBorder = 2.0f;
  const float fHorizontalBorder = 18.0f;

  hkvVec2 vPos;

  // X-Coordinate
  if (m_eAlignment == ALIGN_TOPLEFT || m_eAlignment == ALIGN_BOTTOMLEFT)
  {
    vPos.x = screenExtents.m_vMin.x + fHorizontalBorder;
  }
  else if (m_eAlignment == ALIGN_TOPRIGHT || m_eAlignment == ALIGN_BOTTOMRIGHT)
  {
    vPos.x = screenExtents.m_vMax.x - fWidth - fHorizontalBorder;
  }
  else
  {
    vPos.x = screenExtents.m_vMin.x + (screenExtents.GetSizeX() - fWidth) * 0.5f;
  }

  // Y-Coordinate
  if (m_eAlignment == ALIGN_TOPLEFT || m_eAlignment == ALIGN_TOPRIGHT || m_eAlignment == ALIGN_TOP)
  {
    vPos.y = screenExtents.m_vMin.y + fVerticalBorder;
  }
  else
  {
    vPos.y = screenExtents.m_vMax.y - fHeight - fVerticalBorder;
  }
  
  m_spLogoOverlay->SetPos(vPos.x, vPos.y);
}
wchar_t* VArabicSupport_cl::UniformToContextualLine(VisFont_cl * pArabicFont, const wchar_t * pUniformArabic, bool duplicateSpaces) {

  if(pUniformArabic==NULL) return NULL;

  //length of the current line
	int iLength = VArrayHelper_cl<wchar_t>::Length(pUniformArabic);

  //count spaces
  int iNumSpaces = 0;
  if(duplicateSpaces) 
  {
    for(int i=0;i<iLength;i++) 
    {
      if(pUniformArabic[i]==L' ') iNumSpaces++;
    }
  }

  //allocate the target buffer (original length + number of duplicates space + terminator)
  wchar_t *pContextualArabic = (wchar_t *) vMemAlloc(sizeof(wchar_t)*(iLength+iNumSpaces+1));

  //pre-terminate buffer
  pContextualArabic[iLength+iNumSpaces] = 0;

  wchar_t wcCurLetter = pUniformArabic[0];	//start with the first letter
  wchar_t wcPrevLetter = 0;					//init wcPrevLetter, because the assignment is done at the end of the for loop

  //is the current (first) letter an Arabic letter?
  bool bCurIsArabic = isUniformArabic(pUniformArabic[0]);

  bool bPrevIsArabic = false;	//at the beginning the previous letter is never Arabic
  bool bNextIsArabic;			//calculated inside the loop

  //transform and terminate the target buffer
  for(int i=0;i<iLength;i++) 
  {

    //start at the right side with the first character at index 0 (because Arabic is RTL)
    wcCurLetter = pUniformArabic[i];
    bNextIsArabic = i<(iLength-1) ? isUniformArabic(pUniformArabic[i+1]) : false;

    if(bCurIsArabic) 
    {
      //first uniform letter is 'alif madda: 0x0622 (maps to contextual representation 0xFE81)

      int iIndex = wcCurLetter-0x0622;	//number of iterations
      wchar_t wcContextual = 0xFE81;		//contextual representation of 'alif madda

      //calculate contextual representation of current uniform representation
      //(count up transformation steps) 
      for(int j=0;j<iIndex;j++) {
        if(s_pArabicLetterMap[j]==0) wcContextual +=2;
        else if(s_pArabicLetterMap[j]==1) wcContextual +=4;
        //else skip (-1)
      }

      //now adjust character according to the in-word position

      wchar_t wcCandidate = wcContextual; //we experiment with a candidate character since it's not sure that the candidate exists!

      //end character
      if( bPrevIsArabic && isInnerLetter(wcPrevLetter) && (!bNextIsArabic || isEndLetter(wcCurLetter)) ) {
        wcCandidate+=1;

        //start character
      } else if( bNextIsArabic && (!bPrevIsArabic || isEndLetter(wcPrevLetter)) ) {
        if(s_pArabicLetterMap[iIndex]!=0)
          wcCandidate+=2;

        //inner character
      } else if( i>0 && bPrevIsArabic && bNextIsArabic && isInnerLetter(wcPrevLetter) && isInnerLetter(wcCurLetter) ) {
        if(s_pArabicLetterMap[iIndex]!=0)
          wcCandidate+=3;
      }
      //else isolated (default)

      //candidate check (do we have this character in the font..?)
      VRectanglef requiredSpace = GetCharacterDimension(wcCandidate, pArabicFont);
      if(requiredSpace.GetSizeX()<=0)
      {
        wcCandidate = wcContextual; //restore from backup (because the character is missing)

        //just in case: fall-back to non-contextual
        VRectanglef requiredSpace = GetCharacterDimension(wcCandidate, pArabicFont);
        if(requiredSpace.GetSizeX()<=0)	wcCandidate = wcCurLetter;
      }

      #ifdef HK_DEBUG_SLOW
        requiredSpace = GetCharacterDimension(wcCandidate, pArabicFont);
        VASSERT_MSG(requiredSpace.GetSizeX()>0, "Your text contains a character which is not present in your font!")
      #endif

      //candidate approved:
      pContextualArabic[iLength+iNumSpaces-i-1] = wcCandidate;

    } else {
      //invert directional symbols
      switch(wcCurLetter) {
        case L'(': wcCurLetter = L')'; break;
        case L')': wcCurLetter = L'('; break;
        case L'<': wcCurLetter = L'>'; break;
        case L'>': wcCurLetter = L'<'; break;
        case L'{': wcCurLetter = L'}'; break;
        case L'}': wcCurLetter = L'{'; break;
        case L'[': wcCurLetter = L']'; break;
        case L']': wcCurLetter = L'['; break;
        case L'/': wcCurLetter = L'\\'; break;
        case L'\\': wcCurLetter = L'/'; break;
        case L' ':
          if(duplicateSpaces) {
            pContextualArabic[iLength+iNumSpaces-i-1] = L' ';
            iNumSpaces--;
          }
          break;
        default: break;
      }
      pContextualArabic[iLength+iNumSpaces-i-1] = wcCurLetter;
    }

    //prepare for next loop iteration
    wcPrevLetter = wcCurLetter;

    bPrevIsArabic = bCurIsArabic; 
    bCurIsArabic = bNextIsArabic;

  }

  return pContextualArabic;
}
void VTextState::Paint(VGraphicsInfo *pGraphics, VWindowBase *pParentWnd, VColorRef iColor)
{
  m_iNumTextLines = 0;
  const char *szText = GetText();
  if (!m_spFont || !szText || !szText[0])
    return;

  VSimpleRenderState_t state = VGUIManager::DefaultGUIRenderState();
  if (m_fFontScaling!=1.0f)
    state.SetFlag(RENDERSTATEFLAG_FILTERING);

  VRectanglef v = pParentWnd->GetBoundingBox(); // clipping box of parent control

  if (m_bTextWrap)
  {
    float fMaxWidth = v.GetSizeX()/m_fFontScaling;
    float fLineHeight = m_spFont->GetFontHeight() * m_fRelativeFontHeight * m_fFontScaling;
    hkvVec2 vPos = v.m_vMin;

    const char *szStart = szText;
    VMemoryTempBuffer<512> tmpBuffer;

    while (szStart[0])
    {
      // byte offsets
      int iOffset;
      int iNextOffset;

      // search for next newline
      const char *pCR = strchr(szStart, '\n');

      // compute automatic wrap character index
      int iCharCount = m_spFont->GetCharacterIndexAtPos(szStart, fMaxWidth, -1, false);
      int iWrapOffset = VString::GetUTF8CharacterOffset(szStart, iCharCount);

      if (pCR != NULL && (pCR - szStart) < iCharCount)
      {
        // newline occurs before automatic text wrap
        iOffset = static_cast<int>(pCR - szStart);
        iNextOffset = iOffset + 1;
      }
      else
      {
        // automatic text wrap
        iOffset = iWrapOffset;
        // try to find white space
        if (iOffset > 0)
        {
          while (iOffset > 0 && szStart[iOffset] != 0 && szStart[iOffset] != ' ')
            iOffset--;
          if (iOffset == 0) // no whitespace found? then wrap inside word
            iOffset = iWrapOffset;
        }
        else 
          iOffset = 1;
        iNextOffset = iOffset;
      }

      // put together line
      const int iLineBufferSize = (iOffset+1) * sizeof(char);
      tmpBuffer.EnsureCapacity(iLineBufferSize);
      char *szLineBuffer = static_cast<char*>(tmpBuffer.GetBuffer());

      memcpy(szLineBuffer, szStart, iLineBufferSize);
      szLineBuffer[iOffset] = 0;
      m_iNumTextLines++;

      // draw line
      if (pGraphics)
      {
        hkvVec2 vAlignedPos = m_spFont->GetTextPositionOfs(szLineBuffer, v.GetSize(), 
          m_hAlign, m_vAlign) * m_fFontScaling;
        vAlignedPos.set(vAlignedPos.x + vPos.x, vPos.y); // only consider the x-ofs
        m_spFont->PrintText(&pGraphics->Renderer, vAlignedPos, szLineBuffer, iColor, state, 
          m_fFontScaling, m_pCustomBBox ? m_pCustomBBox : &v);
      }
      vPos.y += fLineHeight;

      szStart = &szStart[iNextOffset];
      while (szStart[0] == ' ')
        szStart++;
    }
    return;
  }

  // recompute the alignment offset
  if (!m_bAlignmentValid)
  {
    m_vCurrentOfs = m_vOfs + m_spFont->GetTextPositionOfs(szText, v.GetSize(),
      m_hAlign,m_vAlign) * m_fFontScaling;
    m_bAlignmentValid = true;
  }

  m_iNumTextLines = 1;
  if (pGraphics)
  {
    m_spFont->PrintText(&pGraphics->Renderer, v.m_vMin+m_vCurrentOfs, szText, 
      iColor, state, m_fFontScaling, m_pCustomBBox ? m_pCustomBBox : &v);
  }
}
void VTextState::Paint(VGraphicsInfo *pGraphics, VWindowBase *pParentWnd, VColorRef iColor)
{
  const char *szText = GetText();
  if (!m_spFont || !szText || !szText[0])
    return;

  VRectanglef vParentRect = pParentWnd->GetClientRect(); // clipping box of parent control

  if(!m_bCachedLinesValid)
  {
    m_lines.Reset();
    m_lineOffsets.Reset();

    float fLineHeight = m_spFont->GetFontHeight() * m_fRelativeFontHeight * m_fFontScaling;

    if(!m_bTextWrap)
    {
      const char* szCurrentLine = szText;
      for (const char* szPtr = szCurrentLine; *szPtr != '\0'; ++szPtr)
      {
        if (*szPtr == '\n')
        {
          VStaticString<512> line;
          line.Set(szCurrentLine, static_cast<int>(szPtr - szCurrentLine));

          m_lines.Add(line.AsChar());
          szCurrentLine = szPtr + 1;
        }
      }

      // Add the last line
      if(*szCurrentLine)
      {
        m_lines.Add(szCurrentLine);
      }
    }
    else
    {
      float fMaxLineWidth = vParentRect.GetSizeX() / m_fFontScaling;

      // Wrap text into individual lines
      {
        const char *szCurrentLine = szText;
        while (*szCurrentLine)
        {
          // byte offsets
          int iByteOffsetAtWrapPosition;
          int iByteOffsetAfterWrapPosition;

          // search for next newline
          const char *pNextNewLine = strchr(szCurrentLine, '\n');

          // compute automatic wrap character index
          int iCharCount = m_spFont->GetCharacterIndexAtPos(szCurrentLine, fMaxLineWidth, -1, false);
          int iWrapOffset = VString::GetUTF8CharacterOffset(szCurrentLine, iCharCount);

          if (pNextNewLine != NULL && (pNextNewLine - szCurrentLine) <= iWrapOffset)
          {
            // newline occurs before automatic text wrap
            iByteOffsetAtWrapPosition = static_cast<int>(pNextNewLine - szCurrentLine);
            iByteOffsetAfterWrapPosition = iByteOffsetAtWrapPosition + 1;
          }
          else if(strlen(szCurrentLine) <= iWrapOffset)
          {
            // End of text occurs before automatic text wrap
            iByteOffsetAtWrapPosition = static_cast<int>(strlen(szCurrentLine));
            iByteOffsetAfterWrapPosition = iByteOffsetAtWrapPosition;
          }
          else
          {
            // automatic text wrap
            iByteOffsetAtWrapPosition = iWrapOffset;
            if (iByteOffsetAtWrapPosition > 0)
            {
              // Go backwards and try to find white space
              while (iByteOffsetAtWrapPosition > 0 && !IsWhiteSpace(szCurrentLine[iByteOffsetAtWrapPosition]))
              {
                iByteOffsetAtWrapPosition--;
              }

              // no whitespace found? then wrap inside word
              if (iByteOffsetAtWrapPosition == 0)
              {
                iByteOffsetAtWrapPosition = iWrapOffset;
              }
              else
              {
                // Find end of next word
                int iEndOfWord = iByteOffsetAtWrapPosition + 1;
                while(szCurrentLine[iEndOfWord] && !IsWhiteSpace(szCurrentLine[iEndOfWord]))
                {
                  iEndOfWord++;
                }

                // If the word does not fit into a line by itself, it will be wrapped anyway, so wrap it early to avoid ragged looking line endings
                VRectanglef nextWordSize;
                m_spFont->GetTextDimension(szCurrentLine + iByteOffsetAtWrapPosition, nextWordSize, iEndOfWord - iByteOffsetAtWrapPosition);
                if(nextWordSize.GetSizeX() > fMaxLineWidth)
                {
                  iByteOffsetAtWrapPosition = iWrapOffset;
                }
              }
            }
            else
            {
              // First character is already wider than the line
              iByteOffsetAtWrapPosition = VString::GetUTF8CharacterOffset(szCurrentLine, 1);
            }
            iByteOffsetAfterWrapPosition = iByteOffsetAtWrapPosition;
          }

          // put together line
          VStaticString<512> line;
          line.Set(szCurrentLine, iByteOffsetAtWrapPosition);

          m_lines.Add(line.AsChar());

          szCurrentLine = &szCurrentLine[iByteOffsetAfterWrapPosition];
          while(*szCurrentLine == ' ')
            szCurrentLine++;
        }
      }
    }

    // Compute offset for each line
    for(int iLineIdx = 0; iLineIdx < m_lines.GetLength(); iLineIdx++)
    {
      hkvVec2 offset = m_vOffset;

      offset.x += m_spFont->GetTextPositionOfs(m_lines[iLineIdx], vParentRect.GetSize(), m_hAlign, m_vAlign, m_fFontScaling).x;
      offset.y += iLineIdx * fLineHeight;

      if (m_vAlign == VisFont_cl::ALIGN_CENTER)
      {
        offset.y += (vParentRect.GetSizeY() - fLineHeight * m_lines.GetSize()) * 0.5f;
      }
      else if (m_vAlign == VisFont_cl::ALIGN_BOTTOM)
      {
        offset.y += (vParentRect.GetSizeY() - fLineHeight * m_lines.GetSize());
      }

      m_lineOffsets.Add(offset);
    }

    m_bCachedLinesValid = true;
  }

  // Render lines
  if (pGraphics)
  {
    VSimpleRenderState_t state = VGUIManager::DefaultGUIRenderState();
    if (m_fFontScaling!=1.0f)
      state.SetFlag(RENDERSTATEFLAG_FILTERING);

    for(int iLineIdx = 0; iLineIdx < m_lines.GetLength(); iLineIdx++)
    {
      m_spFont->PrintText(&pGraphics->Renderer, vParentRect.m_vMin + m_lineOffsets[iLineIdx], m_lines[iLineIdx], iColor, state, 
        m_fFontScaling, m_pCustomBBox ? m_pCustomBBox : &vParentRect);
    }
  }
}