Example #1
0
/** Read a file. */
char *ReadFile(FILE *fd)
{

   const int BLOCK_SIZE = 1 << 14;  // Start at 16k.

   char *buffer;
   int len, max;
   int ch;

   len = 0;
   max = BLOCK_SIZE;
   buffer = Allocate(max + 1);

   for(;;) {
      ch = fgetc(fd);
      if(JUNLIKELY(ch == EOF || ch == 0)) {
         break;
      }
      buffer[len++] = ch;
      if(JUNLIKELY(len >= max)) {
         max *= 2;
         if(JUNLIKELY(max < 0)) {
            /* File is too big. */
            break;
         }
         buffer = Reallocate(buffer, max + 1);
      }
   }
   buffer[len] = 0;

   return buffer;

}
Example #2
0
//--------------------------------------
static void CPROC ImagePngWrite(png_structp png,
                           png_bytep   data,
                           png_size_t  length)
{
	// add this length, data into the buffer...
   // reallcoate buffer by 4096 until complete.
	//sg_pStream->write(length, data);
	ImagePngRawData *self = (ImagePngRawData *) png->io_ptr;
	if( ((*self->r_size) + length ) > self->alloced )
	{
		if( self->alloced )
		{
			self->alloced += ((length > 2048)?length:0) + 4096;
			(*self->r_data) = (uint8_t*)Reallocate( (*self->r_data), self->alloced );
		}
		else
		{
			self->alloced += 4096;
			(*self->r_size) = 0;
			(*self->r_data) = (uint8_t*)Allocate( self->alloced );
		}
	}
	MemCpy( (*self->r_data)+(*self->r_size), data, length );
   (*self->r_size) = (*self->r_size) + length;
}
Example #3
0
char* Input_Read(Input* input, size_t* size)
{

    // First copy anything that we've buffered.
    char* result = static_cast<char*>( Allocate(input->L, input->size) );
    memcpy(result, input->buffer, input->size);
    *size = input->size;

    input->size = 0;

    // Now keep reading until we get to the end.

    while (1)
    {

        size_t bufferSize;
        const char* buffer = input->reader( input->L, input->userdata, &bufferSize );

        if (buffer == NULL || bufferSize == 0)
        {
            break;
        }

        size_t newSize = *size + bufferSize;
        result = static_cast<char*>( Reallocate(input->L, result, *size, newSize) );

        memcpy(result + *size, buffer, bufferSize);
        *size = newSize;

    }
    return result;

}
Example #4
0
File: parse.c Project: Nehamkin/jwm
/** Read a file. */
char *ReadFile(FILE *fd)
{

   const int BLOCK_SIZE = 1024;  // Start at 1k.

   char *buffer;
   int len, max;

   len = 0;
   max = BLOCK_SIZE;
   buffer = Allocate(max + 1);

   for(;;) {
      const size_t count = fread(&buffer[len], 1, max - len, fd);
      len += count;
      if(len < max) {
         break;
      }
      max *= 2;
      if(JUNLIKELY(max < 0)) {
         /* File is too big. */
         break;
      }
      buffer = Reallocate(buffer, max + 1);
      if(JUNLIKELY(buffer == NULL)) {
         FatalError(_("out of memory"));
      }
   }
   buffer[len] = 0;

   return buffer;

}
Example #5
0
File: lex.c Project: GustavoMOG/JWM
/** Get the value of the current element. */
char *ReadElementValue(const char *line, const char *file, int *lineNumber) {
   char *buffer;
   char ch;
   int len, max;
   int x;

   len = 0;
   max = BLOCK_SIZE;
   buffer = Allocate(max + 1);

   for(x = 0; !IsValueEnd(line[x]); x++) {
      if(line[x] == '&') {
         x += ParseEntity(line + x, &ch, file, *lineNumber) - 1;
         if(ch) {
            buffer[len] = ch;
         } else {
            buffer[len] = line[x];
         }
      } else {
         if(line[x] == '\n') {
            ++*lineNumber;
         }
         buffer[len] = line[x];
      }
      ++len;
      if(len >= max) {
         max += BLOCK_SIZE;
         buffer = Reallocate(buffer, max + 1);
      }
   }
   buffer[len] = 0;
   Trim(buffer);

   return buffer;
}
Example #6
0
static void
StringAdd (String *s, char c)
{
    if (s->len == s->size)
	s->buf = Reallocate (s->buf, (s->size *= 2) + 1);
    s->buf[s->len++] = c;
    s->buf[s->len] = '\0';
}
Example #7
0
StreamMemory::StreamMemory() 
{
	buffer = NULL;
	buffer_ptr = NULL;
	buffer_size = 0;
	buffer_used = 0;
	owns_buffer = true;
	Reallocate(DEFAULT_BUFFER_SIZE);
}
Example #8
0
StreamMemory::StreamMemory(size_t initial_size)
{
	buffer = NULL;
	buffer_ptr = NULL;
	buffer_size = 0;
	buffer_used = 0;
	owns_buffer = true;
	Reallocate(initial_size);
}
Example #9
0
StreamMemory& StreamMemory::operator=( const StreamMemory& copy )
{
	// Copy the buffer and pointer offsets
	Reallocate( ( ( copy.buffer_used + BUFFER_INCREMENTS ) / BUFFER_INCREMENTS ) * BUFFER_INCREMENTS );
	memcpy( buffer, copy.buffer, copy.buffer_used );
	buffer_ptr = buffer + ( copy.buffer_ptr - copy.buffer );
	
	return *this;
}
Example #10
0
void CQuickBuildString::Concatenate(LPCSTR sz, int iLen)
{
	LPSTR szCopyTo = Reallocate(iLen);

	CopyMemory(szCopyTo, sz, iLen);

	szCopyTo[iLen] = 0;

	CheckValid();
}
Example #11
0
File: dfa.c Project: kalngyk/learn
void AddEquiv(Exp L, Exp R) {
   Exp Q; int E;
   if (L == R) return;
   if (L->State > R->State) Q = L, L = R, R = Q;
   for (E = 0; E < Es; E++)
      if (L == ETab[E].L && R == ETab[E].R) return;
   if (Es >= EMax)
      EMax += 8, ETab = Reallocate(ETab, sizeof *ETab * EMax);
   ETab[Es].L = L, ETab[Es].R = R, Es++;
}
Example #12
0
///
/// Добавя нов елемент в динамичен масив
///
void Add(DynamicArray* pArr, int Element)
{
	if(pArr->Used >= pArr->Size)
	{
		size_t NewSize = (pArr->Size == 0 ? 2 : pArr->Size*2);
		
		Reallocate(pArr, NewSize);
	}

	pArr->pData[pArr->Used++] = Element;
}
Example #13
0
///
/// Добавя нов елемент в динамичния масив
///
/// Новият елемент се добавя в края на масива.
///
void DynamicArray::Add(int Element)
{
	if(Length >= AllocatedSize)
	{
		size_t NewSize = (AllocatedSize == 0 ? 2 : AllocatedSize*2);
		
		Reallocate(NewSize);
	}

	pData[Length++] = Element;
}
Example #14
0
void CCollection::AtDelete(int nIndex)
{
    if ( (nIndex>=0) && (nIndex<m_nCount) )
    {
        if (nIndex<m_nCount-1)
            memmove(&m_pItems[nIndex], &m_pItems[nIndex+1], sizeof(void*)*(m_nCount-1-nIndex));
        m_nCount--;
#ifndef KEEP_MEM
        Reallocate();
#endif
    }
}
Example #15
0
size_t StreamMemory::PushFront( const void* _buffer, size_t bytes )
{
	if ( buffer_used + bytes > buffer_size )
		if ( !Reallocate( bytes + BUFFER_INCREMENTS ) )
			return 0;

	memmove( &buffer[ bytes ], &buffer[ 0 ], buffer_used );
	memcpy( buffer, _buffer, bytes );
	buffer_used += bytes;
	buffer_ptr += bytes;
	return bytes;
}
Example #16
0
// Read bytes from the buffer, advancing the internal pointer
size_t StreamMemory::Write( const void *_buffer, size_t bytes ) 
{
	if ( buffer_ptr + bytes > buffer + buffer_size )
		if ( !Reallocate( bytes + BUFFER_INCREMENTS ) )
			return 0;
					
	memcpy( buffer_ptr, _buffer, bytes );

	buffer_ptr += bytes;
	buffer_used = Math::Max( (size_t)(buffer_ptr - buffer), buffer_used );
	
	return bytes;
}
Example #17
0
StreamMemory::StreamMemory(const StreamMemory& copy) : Stream(copy)
{
	buffer = NULL;
	buffer_ptr = NULL;
	buffer_size = 0;
	buffer_used = 0;
	owns_buffer = true;
	
	// Copy the buffer and pointer offsets
	Reallocate( ( ( copy.buffer_used + BUFFER_INCREMENTS ) / BUFFER_INCREMENTS ) * BUFFER_INCREMENTS );
	memcpy( buffer, copy.buffer, copy.buffer_used );
	buffer_ptr = buffer + ( copy.buffer_ptr - copy.buffer );	
}
Example #18
0
void CCollection::AtInsert(int nIndex, void * pItem)
{
    if (nIndex<0 || nIndex>m_nCount)
    {
        //throw "Unacceptable index!";  this does not compile in KDevelop
        int xx = 2;
        xx = 2/(xx-2);
    }
    Reallocate();

    if (nIndex<m_nCount)
        memmove(&m_pItems[nIndex+1], &m_pItems[nIndex], sizeof(void*)*(m_nCount-nIndex));
    m_pItems[nIndex] = pItem;
    m_nCount++;
}
XnStatus XnFrameBufferManager::Init(XnUInt32 nBufferSize)
{
	XnStatus nRetVal = XN_STATUS_OK;

	nRetVal = xnOSCreateCriticalSection(&m_hLock);
	XN_IS_STATUS_OK(nRetVal);

	nRetVal = m_pBufferPool->Init(nBufferSize);
	XN_IS_STATUS_OK(nRetVal);

	nRetVal = Reallocate(nBufferSize);
	XN_IS_STATUS_OK(nRetVal);

	return (XN_STATUS_OK);
}
Example #20
0
File: lex.c Project: KarlGodt/jwm
/** Read the value of an element or attribute. */
char *ReadValue(const char *line,
                const char *file,
                char (*IsEnd)(char),
                unsigned int *offset,
                unsigned int *lineNumber)
{
   char *buffer;
   char ch;
   unsigned int len, max;
   unsigned int x;

   len = 0;
   max = BLOCK_SIZE;
   buffer = Allocate(max + 1);

   for(x = 0; !(IsEnd)(line[x]); x++) {
      if(line[x] == '&') {
         x += ParseEntity(line + x, &ch, file, *lineNumber) - 1;
         if(ch) {
            buffer[len] = ch;
         } else {
            buffer[len] = line[x];
         }
      } else {
         if(line[x] == '\n') {
            *lineNumber += 1;
         }
         buffer[len] = line[x];
      }
      len += 1;
      if(len >= max) {
         max += BLOCK_SIZE;
         buffer = Reallocate(buffer, max + 1);
         if(JUNLIKELY(buffer == NULL)) {
            FatalError(_("out of memory"));
         }
      }
   }
   buffer[len] = 0;
   Trim(buffer);
   *offset = x;

   return buffer;
}
Example #21
0
void CCollection::AtSet(int nIndex, void * pItem, BOOL bFreeOld)
{
    if (nIndex<0 || nIndex>m_nCount)
    {
        //throw "Unacceptable index!";  this does not compile in KDevelop
        int xx = 2;
        xx = 2/(xx-2);
    }

    Reallocate();

    if (nIndex==m_nCount)
        m_nCount++;
    else
        if (bFreeOld)
            FreeItem(m_pItems[nIndex]);

    m_pItems[nIndex] = pItem;
}
XnStatus XnFrameBufferManager::Init(XnUInt32 nBufferSize)
{
    XnStatus nRetVal = XN_STATUS_OK;

    XN_VALIDATE_NEW(m_pBufferPool, XnOniFramePool);
    m_pBufferPool->SetFrameSize(nBufferSize);
    int numFrames = 6; // user, synced frame holder (last+synced), XnSensor frame-sync(last+incoming), working
    if (!m_pBufferPool->Initialize(numFrames))
    {
        return XN_STATUS_ALLOC_FAILED;
    }

    nRetVal = xnOSCreateCriticalSection(&m_hLock);
    XN_IS_STATUS_OK(nRetVal);

    nRetVal = Reallocate(nBufferSize);
    XN_IS_STATUS_OK(nRetVal);

    return (XN_STATUS_OK);
}
Example #23
0
File: lex.c Project: KarlGodt/jwm
/** Tokenize data. */
TokenNode *Tokenize(const char *line, const char *fileName)
{
   AttributeNode *ap;
   TokenNode *current;
   char *temp;
   unsigned int x;
   unsigned int offset;
   unsigned int lineNumber;
   char inElement;
   char found;

   head = NULL;
   current = NULL;
   inElement = 0;
   lineNumber = 1;

   x = 0;
   /* Skip any initial white space. */
   while(IsSpace(line[x], &lineNumber)) {
      x += 1;
   }

   /* Skip any XML stuff. */
   if(!strncmp(line + x, "<?", 2)) {
      while(line[x]) {
         if(line[x] == '\n') {
            lineNumber += 1;
         }
         if(!strncmp(line + x, "?>", 2)) {
            x += 2;
            break;
         }
         x += 1;
      }
   }

   /* Process the XML data. */
   while(line[x]) {

      /* Skip comments and white space. */
      do {

         /* Skip white space. */
         while(IsSpace(line[x], &lineNumber)) {
            x += 1;
         }

         /* Skip comments */
         found = 0;
         if(!strncmp(line + x, "<!--", 4)) {
            while(line[x]) {
               if(line[x] == '\n') {
                  lineNumber += 1;
               }
               if(!strncmp(line + x, "-->", 3)) {
                  x += 3;
                  found = 1;
                  break;
               }
               x += 1;
            }
         }

      } while(found);

      switch(line[x]) {
      case '<':
         x += 1;
         if(line[x] == '/') {

            /* Close tag. */
            x += 1;
            temp = ReadElementName(line + x);
            if(current) {
               if(JLIKELY(temp)) {
                  if(JUNLIKELY(current->type != LookupType(temp, NULL))) {
                     Warning(_("%s[%u]: close tag \"%s\" does not "
                             "match open tag \"%s\""),
                             fileName, lineNumber, temp,
                             GetTokenName(current));
                  }
               } else {
                  Warning(_("%s[%u]: unexpected and invalid close tag"),
                          fileName, lineNumber);
               }
               current = current->parent;
            } else {
               if(temp) {
                  Warning(_("%s[%u]: close tag \"%s\" without open tag"),
                          fileName, lineNumber, temp);
               } else {
                  Warning(_("%s[%u]: invalid close tag"), fileName, lineNumber);
               }
            }
            if(temp) {
               x += strlen(temp);
               Release(temp);
            }

         } else {

            /* Open tag. */
            current = CreateNode(current, fileName, lineNumber);
            temp = ReadElementName(line + x);
            if(JLIKELY(temp)) {
               x += strlen(temp);
               LookupType(temp, current);
               Release(temp);
            } else {
               Warning(_("%s[%u]: invalid open tag"), fileName, lineNumber);
            }

         }
         inElement = 1;
         break;
      case '/':

         /* End of open/close tag. */
         if(inElement) {
            x += 1;
            if(JLIKELY(line[x] == '>' && current)) {
               x += 1;
               current = current->parent;
               inElement = 0;
            } else {
               Warning(_("%s[%u]: invalid tag"), fileName, lineNumber);
            }
         } else {
            goto ReadDefault;
         }

         break;
      case '>':

         /* End of open tag. */
         x += 1;
         inElement = 0;
         break;

      default:
ReadDefault:
         if(inElement) {

            /* In the open tag; read attributes. */
            ap = CreateAttribute(current);
            ap->name = ReadElementName(line + x);
            if(ap->name) {
               x += strlen(ap->name);
               if(line[x] == '=') {
                  x += 1;
               }
               if(line[x] == '\"') {
                  x += 1;
               }
               ap->value = ReadAttributeValue(line + x, fileName,
                                              &offset, &lineNumber);
               x += offset;
               if(line[x] == '\"') {
                  x += 1;
               }
            }

         } else {

            /* In tag body; read text. */
            temp = ReadElementValue(line + x, fileName, &offset, &lineNumber);
            x += offset;
            if(temp) {
               if(current) {
                  if(current->value) {
                     current->value = Reallocate(current->value,
                                                 strlen(current->value) +
                                                 strlen(temp) + 1);
                     strcat(current->value, temp);
                     Release(temp);
                  } else {
                     current->value = temp;
                  }
               } else {
                  if(JUNLIKELY(temp[0])) {
                     Warning(_("%s[%u]: unexpected text: \"%s\""),
                             fileName, lineNumber, temp);
                  }
                  Release(temp);
               }
            }
         }
         break;
      }
   }

   return head;
}
Example #24
0
File: lex.c Project: GustavoMOG/JWM
/** Tokenize a data. */
TokenNode *Tokenize(const char *line, const char *fileName) {

   TokenNode *np;
   AttributeNode *ap;
   char *temp;
   int inElement;
   int x;
   int found;
   int lineNumber;

   head = NULL;
   current = NULL;
   inElement = 0;
   lineNumber = 1;

   x = 0;
   /* Skip any initial white space */
   while(IsSpace(line[x], &lineNumber)) ++x;

   /* Skip any XML stuff */
   if(!strncmp(line + x, "<?", 2)) {
      while(line[x]) {
         if(line[x] == '\n') {
            ++lineNumber;
         }
         if(!strncmp(line + x, "?>", 2)) {
            x += 2;
            break;
         }
         ++x;
      }
   }

   while(line[x]) {

      do {

         while(IsSpace(line[x], &lineNumber)) ++x;

         /* Skip comments */
         found = 0;
         if(!strncmp(line + x, "<!--", 4)) {
            while(line[x]) {
               if(line[x] == '\n') {
                  ++lineNumber;
               }
               if(!strncmp(line + x, "-->", 3)) {
                  x += 3;
                  found = 1;
                  break;
               }
               ++x;
            }
         }
      } while(found);

      switch(line[x]) {
      case '<':
         ++x;
         if(line[x] == '/') {
            ++x;
            temp = ReadElementName(line + x);

            if(current) {

               if(temp) {

                  if(current->type != LookupType(temp, NULL)) {
                     Warning("%s[%d]: close tag \"%s\" does not "
                        "match open tag \"%s\"",
                        fileName, lineNumber, temp,
                        GetTokenName(current));
                  }

               } else {
                  Warning("%s[%d]: unexpected and invalid close tag",
                     fileName, lineNumber);
               }

               current = current->parent;
            } else {
               if(temp) {
                  Warning("%s[%d]: close tag \"%s\" without open "
                     "tag", fileName, lineNumber, temp);
               } else {
                  Warning("%s[%d]: invalid close tag", fileName, lineNumber);
               }
            }

            if(temp) {
               x += strlen(temp);
               Release(temp);
            }

         } else {
            np = current;
            current = NULL;
            np = CreateNode(np, fileName, lineNumber);
            temp = ReadElementName(line + x);
            if(temp) {
               x += strlen(temp);
               LookupType(temp, np);
               Release(temp);
            } else {
               Warning("%s[%d]: invalid open tag", fileName, lineNumber);
            }
         }
         inElement = 1;
         break;
      case '/':
         if(inElement) {
            ++x;
            if(line[x] == '>' && current) {
               ++x;
               current = current->parent;
               inElement = 0;
            } else {
               Warning("%s[%d]: invalid tag", fileName, lineNumber);
            }
         } else {
            goto ReadDefault;
         }
         break;
      case '>':
         ++x;
         inElement = 0;
         break;
      default:
ReadDefault:
         if(inElement) {
            ap = CreateAttribute(current);
            ap->name = ReadElementName(line + x);
            if(ap->name) {
               x += strlen(ap->name);
               if(line[x] == '=') {
                  ++x;
               }
               if(line[x] == '\"') {
                  ++x;
               }
               ap->value = ReadAttributeValue(line + x, fileName,
                  &lineNumber);
               if(ap->value) {
                  x += strlen(ap->value);
               }
               if(line[x] == '\"') {
                  ++x;
               }
            }
         } else {
            temp = ReadElementValue(line + x, fileName, &lineNumber);
            if(temp) {
               x += strlen(temp);
               if(current) {
                  if(current->value) {
                     current->value = Reallocate(current->value,
                        strlen(current->value) + strlen(temp) + 1);
                     strcat(current->value, temp);
                     Release(temp);
                  } else {
                     current->value = temp;
                  }
               } else {
                  if(temp[0]) {
                     Warning("%s[%d]: unexpected text: \"%s\"",
                        fileName, lineNumber, temp);
                  }
                  Release(temp);
               }
            }
         }
         break;
      }
   }

   return head;
}
Example #25
0
int main(int argc, char **argv)
{
  enum { Undefined, Comment, Data } state = Undefined;
  int warn[ARGC];
  char *para[ARGC];
  char line[LINE];
  char prefix[2*LINE];
  char comment[BLOCK], *c = comment;
  Group *anchor = NULL, *cur = NULL;
  int plen = 0;

  if( argc < 2 ) {
    fprintf(stderr, "Usage:  %s para1 para2 ... < infile > outfile\n\n"
      "Reorders data files produced with FormCalc utilities by moving\n"
      "parameter values from the headers into the data columns.  Most\n"
      "plotting utilites can then easily plot the data vs a parameter.\n\n",
      argv[0]);
    exit(1);
  }

  memset(warn, 0, sizeof warn);
  *comment = 0;

  while( fgets(line, sizeof line, stdin) ) {
    int len;

    if( *line == '#' ) {
      char var[128];
      int i, n;

      if( state != Comment ) {
        memset(para, 0, sizeof para);
        *comment = 0;
        c = comment;
        state = Comment;
      }

      n = -1;
      sscanf(line + 1, " %[^= ] =%n", var, &n);
      if( n > 0 ) {
        for( i = 1; i < argc; ++i )
          if( strcmp(var, argv[i]) == 0 ) {
            para[i] = strdup(line + 1 + n);
            goto loop;
          }
        strcpy(c, line);
        c += strlen(c);
      }
      continue;
    }

    if( line[strspn(line, " \t\n")] == 0 ) {
      *comment = 0;
      state = Undefined;
      continue;
    }

    if( state != Data ) {
      Group **parent;

      char *p = prefix;
      if( state == Comment ) {
        int i;
        for( i = 1; i < argc; ++i )
          if( para[i] ) {
            strcpy(p, para[i]);
            p += strlen(p);
            p[-1] = '\t';
            free(para[i]);
          }
          else if( !warn[i] ) {
            fprintf(stderr, "Warning: parameter %s not found\n", argv[i]);
            warn[i] = 1;
          }
      }
      *p = 0;
      plen = p - prefix + 1;

      for( parent = &anchor; (cur = *parent); parent = &cur->next )
        if( strcmp(cur->para, comment) == 0 ) break;
      if( cur == NULL ) {
        Allocate(cur, 1);
        *parent = cur;
        cur->next = NULL;
        cur->para = strdup(comment);
        Allocate(cur->data, BLOCK);
        cur->pos = 0;
        cur->size = BLOCK;
      }

      state = Data;
    }

    len = cur->pos + plen + strlen(line);
    if( len > cur->size ) {
      do cur->size += BLOCK; while( len > cur->size );
      Reallocate(cur->data, cur->size);
    }
    cur->pos += sprintf(cur->data + cur->pos, "%s %s", prefix, line);

loop: ;
  }

  for( cur = anchor; cur; cur = cur->next )
    printf("%s%s\n\n", cur->para, cur->data);

  return 0;
}
Example #26
0
LOGICAL swapChainCreate( struct SwapChain *swapChain,
	VkCommandBuffer commandBuffer,
	uint32_t *width,
	uint32_t *height )
{
	VkSwapchainKHR oldSwapChain = swapChain->swapChain;

	// Get physical device surface properties and formats. This was not
	// covered in previous tutorials. Effectively does what it says it does.
	// We will be using the result of this to determine the number of
	// images we should use for our swap chain and set the appropriate
	// sizes for them.
	uint32_t presentModeCount;
	VkSurfaceCapabilitiesKHR surfaceCapabilities;
	VkExtent2D swapChainExtent = { 0 };// = {};
	VkPresentModeKHR *presentModes;
	if( swapChain->fpGetPhysicalDeviceSurfaceCapabilitiesKHR( swapChain->physicalDevice,
		swapChain->surface,
		&surfaceCapabilities ) != VK_SUCCESS )
		return FALSE;

	// Also not covered in previous tutorials: used to get the available
	// modes for presentation.
	if( swapChain->fpGetPhysicalDeviceSurfacePresentModesKHR( swapChain->physicalDevice,
		swapChain->surface,
		&presentModeCount,
		NULL ) != VK_SUCCESS)
		return FALSE;
	if( presentModeCount == 0 )
		return FALSE;
	presentModes = NewArray( VkPresentModeKHR, presentModeCount );
	if( swapChain->fpGetPhysicalDeviceSurfacePresentModesKHR( swapChain->physicalDevice,
		swapChain->surface,
		&presentModeCount,
		&presentModes[0] ) != VK_SUCCESS )
		return FALSE;

	// When constructing a swap chain we must supply our surface resolution.
	// Like all things in Vulkan there is a structure for representing this

	// The way surface capabilities work is rather confusing but width
	// and height are either both -1 or both not -1. A size of -1 indicates
	// that the surface size is undefined, which means you can set it to
	// effectively any size. If the size however is defined, the swap chain
	// size *MUST* match.
	if( surfaceCapabilities.currentExtent.width == -1 ) {
		swapChainExtent.width = *width;
		swapChainExtent.height = *height;
	}
	else {
		swapChainExtent = surfaceCapabilities.currentExtent;
		*width = surfaceCapabilities.currentExtent.width;
		*height = surfaceCapabilities.currentExtent.height;
	}
	{
		// Prefer mailbox mode if present
		VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR; // always supported
		uint32_t i;
		for( i = 0; i < presentModeCount; i++ ) {
			if( presentModes[i] == VK_PRESENT_MODE_MAILBOX_KHR ) {
				presentMode = VK_PRESENT_MODE_MAILBOX_KHR;
				break;
			}
			if( presentMode != VK_PRESENT_MODE_MAILBOX_KHR
				&&  presentMode != VK_PRESENT_MODE_IMMEDIATE_KHR )
			{
				// The horrible fallback
				presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR;
			}
		}
	{
		// Determine the number of images for our swap chain
		uint32_t desiredImages = surfaceCapabilities.minImageCount + 1;
		if( surfaceCapabilities.maxImageCount > 0
			&& desiredImages > surfaceCapabilities.maxImageCount )
		{
			desiredImages = surfaceCapabilities.maxImageCount;
		}
	{
		// This will be covered in later tutorials
		VkSurfaceTransformFlagsKHR preTransform = surfaceCapabilities.currentTransform;
		if( surfaceCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR )
			preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
	{
	VkSwapchainCreateInfoKHR swapChainCreateInfo;
	// Mandatory fields
	swapChainCreateInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
	swapChainCreateInfo.pNext = NULL;
	swapChainCreateInfo.surface = swapChain->surface;
	swapChainCreateInfo.minImageCount = desiredImages;
	swapChainCreateInfo.imageFormat = swapChain->colorFormat;
	swapChainCreateInfo.imageColorSpace = swapChain->colorSpace;
	swapChainCreateInfo.imageExtent.width = swapChainExtent.width;
	swapChainCreateInfo.imageExtent.height = swapChainExtent.height;

	// This is literally the same as GL_COLOR_ATTACHMENT0
	swapChainCreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
	swapChainCreateInfo.preTransform = (VkSurfaceTransformFlagBitsKHR)preTransform;
	swapChainCreateInfo.imageArrayLayers = 1; // Only one attachment
	swapChainCreateInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; // No sharing
	swapChainCreateInfo.queueFamilyIndexCount = 0; // Covered in later tutorials
	swapChainCreateInfo.pQueueFamilyIndices = NULL; // Covered in later tutorials
	swapChainCreateInfo.presentMode = presentMode;
	swapChainCreateInfo.clipped = TRUE; // If we want clipping outside the extents

										// Alpha on the window surface should be opaque:
										// If it was not we could create transparent regions of our window which
										// would require support from the Window compositor. You can totally do
										// that if you wanted though ;)
	swapChainCreateInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;


	if( swapChain->fpCreateSwapchainKHR( swapChain->device,
		&swapChainCreateInfo,
		NULL,
		&swapChain->swapChain ) != VK_SUCCESS )
		return FALSE;
	}
	}
	}
	}

	// If an existing swap chain is recreated, destroy the old one. This
	// also cleans up all presentable images
	if( oldSwapChain != VK_NULL_HANDLE ) {
		swapChain->fpDestroySwapchainKHR( swapChain->device,
			oldSwapChain,
			NULL );
	}
	{
		// Now get the presentable images from the swap chain
		uint32_t imageCount;
		if( swapChain->fpGetSwapchainImagesKHR( swapChain->device,
			swapChain->swapChain,
			&imageCount,
			NULL ) != VK_SUCCESS )
			goto failed;
		swapChain->images = Reallocate( swapChain->images, sizeof( VkImage) * imageCount );
		if( swapChain->fpGetSwapchainImagesKHR( swapChain->device,
			swapChain->swapChain,
			&imageCount,
			&swapChain->images[0] ) != VK_SUCCESS ) {
		failed:
			swapChain->fpDestroySwapchainKHR( swapChain->device,
				swapChain->swapChain,
				NULL );
			return FALSE;
		}
	// Create the image views for the swap chain. They will all be single
	// layer, 2D images, with no mipmaps.
	// Check the VkImageViewCreateInfo structure to see other views you
	// can potentially create.
	swapChain->buffers = Reallocate( swapChain->buffers, sizeof( struct SwapChainBuffer ) * imageCount );
	{
	uint32_t i;
	for( i = 0; i < imageCount; i++ ) {
		VkImageViewCreateInfo colorAttachmentView;// = {};
		colorAttachmentView.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
		colorAttachmentView.pNext = NULL;
		colorAttachmentView.format = swapChain->colorFormat;
		colorAttachmentView.components.r = VK_COMPONENT_SWIZZLE_R;
		colorAttachmentView.components.g = VK_COMPONENT_SWIZZLE_G;
		colorAttachmentView.components.b = VK_COMPONENT_SWIZZLE_B;
		colorAttachmentView.components.a = VK_COMPONENT_SWIZZLE_A;

		colorAttachmentView.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
		colorAttachmentView.subresourceRange.baseMipLevel = 0;
		colorAttachmentView.subresourceRange.levelCount = 1;
		colorAttachmentView.subresourceRange.baseArrayLayer = 0;
		colorAttachmentView.subresourceRange.layerCount = 1;
		colorAttachmentView.viewType = VK_IMAGE_VIEW_TYPE_2D;
		colorAttachmentView.flags = 0; // mandatory

									   // Wire them up
		swapChain->buffers[i].image = swapChain->images[i];
		// Transform images from the initial (undefined) layer to
		// present layout
		setImageLayout( commandBuffer,
			swapChain->buffers[i].image,
			VK_IMAGE_ASPECT_COLOR_BIT,
			VK_IMAGE_LAYOUT_UNDEFINED,
			VK_IMAGE_LAYOUT_PRESENT_SRC_KHR );
		colorAttachmentView.image = swapChain->buffers[i].image;
		// Create the view
		if( vkCreateImageView( swapChain->device,
			&colorAttachmentView,
			NULL,
			&swapChain->buffers[i].view ) != VK_SUCCESS )
			goto failed;
	}
	}
	}
	return TRUE;
}
Example #27
0
void
DecodingTable::setDecodingTable(uint k, DecodeableSubstr* substrs)
{
	assert (k <= MAXK);

	this->k = k;
	this->bytesStream = 0;

	// Scanning the table and building its compact representation
	uint entries = pow(2, this->k);
	endings = new BitString(entries);

	map<vector<uchar>, uint> tmp;
	map<vector<uchar>, uint>::iterator it;

	// Collecting all different decodeable substrings in the representation
	for (uint i=0; i<entries; i++)
	{
		if (substrs[i].length > 0)
		{
			// Check if the entry has been previously found
			it = tmp.find(substrs[i].substr);

			if (it == tmp.end())
			{
				// New substring
				tmp.insert(pair<vector<uchar>, uint> (substrs[i].substr, i));
			}
			else
			{
				// Although the substring was found, we must
				// check its jumping information because an
				// end-substring can be similar than a regular
				// one and its information must prevail
				if (substrs[it->second].special)
				{
					tmp.erase(substrs[i].substr);
					tmp.insert(pair<vector<uchar>, uint> (substrs[i].substr, i));
				}
			}
		}
	}

	table = new uint[entries];

	size_t reservedStream = entries;
	stream = new uchar[reservedStream];
	stream[bytesStream] = (uchar)0; bytesStream++;

	// Serializing the table
	for (uint i=0; i<entries; i++)
	{
		if (substrs[i].dbits > 0)
		{
			// Checking the available space in the stream 
			// and realloc if required
			while ((bytesStream+substrs[i].dbits+1) > reservedStream)
				reservedStream = Reallocate(&stream, reservedStream);

			if (substrs[i].length > 0)
			{
				// Regular entry
				it = tmp.find(substrs[i].substr);

				if (!substrs[it->second].encoded)
				{
					table[i] = bytesStream;
					substrs[it->second].position = table[i];
					substrs[it->second].encoded = true;

					stream[bytesStream] = encodeInfo(substrs[i].length, substrs[it->second].dbits);
					bytesStream++;

					for (uint j=0; j<substrs[i].length; j++)
						stream[bytesStream+j] = substrs[i].substr[j];
					bytesStream += substrs[i].length;
				}
				else table[i] = substrs[it->second].position;

				if (substrs[it->second].ending) endings->setBit(i);
			}
			else
			{
				// Entry pointing to a decoding subtree
				table[i] = bytesStream;

				stream[bytesStream] = encodeInfo(substrs[i].length, substrs[i].dbits);
				bytesStream++;

				bytesStream += VByte::encode(substrs[i].ptr, stream+bytesStream);
			}
		}
		else table[i] = 0;
	}
}
Example #28
0
bool
AndroidDirectTexture::Reallocate(uint32_t aWidth, uint32_t aHeight) {
  return Reallocate(aWidth, aHeight, mFormat);
}
Example #29
0
File: dfa.c Project: kalngyk/learn
void AddTerm(Symbol X, Exp Q) {
   if (Ts >= TMax)
      TMax += 4, TList = Reallocate(TList, sizeof *TList * TMax);
   TList[Ts].X = X, TList[Ts].Q = Q, Ts++;
}
bool
AndroidDirectTexture::Reallocate(PRUint32 aWidth, PRUint32 aHeight) {
  return Reallocate(aWidth, aHeight, mFormat);
}