Пример #1
0
/**
 * Writes errors/information messages to stdout.
 * Gets the InfoLogARB of hObject and messages it.
 * \param hObject - a handle to the object.
 * \param bProgram - if true, hObject is a program object, otherwise it is a shader object.
 * \return true: InfoLogARB non-empty and GLSLPROGRAM_STRICT defined OR only warning, false otherwise
 * \author <a href="mailto:[email protected]">Jens Schneider</a>
 * \date Aug.2004
 */
bool GLSLProgram::WriteInfoLog(const char* shaderdesc, GLuint hObject, bool bProgram) {
  // Check for errors
  GLint iLength;
  if (bProgram)
    glGetProgramiv(hObject,GL_INFO_LOG_LENGTH,&iLength);
  else
    glGetShaderiv(hObject,GL_INFO_LOG_LENGTH,&iLength);

  GLboolean bAtMostWarnings=true;
  if (iLength>1) {
    char *pcLogInfo=new char[iLength];
    if (bProgram) {
      glGetProgramInfoLog(hObject,iLength,&iLength,pcLogInfo);
      bAtMostWarnings=glIsProgram(hObject);
    }
    else {
      glGetShaderInfoLog(hObject,iLength,&iLength,pcLogInfo);
      bAtMostWarnings=glIsShader(hObject);
    }
    if (bAtMostWarnings) {
      WARNING(shaderdesc);
      WARNING(pcLogInfo);
      delete[] pcLogInfo;
      return false;
    } else {
      T_ERROR(shaderdesc);
      T_ERROR(pcLogInfo);
      delete[] pcLogInfo;
#ifdef GLSLPROGRAM_STRICT
      return true;
#endif
    }
  }
  return !bool(bAtMostWarnings==GL_TRUE); // error occured?
}
Пример #2
0
/**
 * Sets an uniform matrix.
 * Matrices are always of type float.
 * \warning uses glGetError();
 * \param name - name of the parameter
 * \param m - a float array containing up to 16 floats for the matrix.
 * \param bTranspose - if true, the matrix will be transposed before uploading.
 * \return void
 * \author <a href="mailto:[email protected]">Jens Schneider</a>
 * \date Mar.2005
 */
void GLSLProgram::SetUniformMatrix(const char *name,const float *m,bool bTranspose) const {
  assert(m_bEnabled);
  CheckGLError();

  GLenum iType;
  GLint iLocation;

  try {
    iLocation = get_uniform_vector(name, m_hProgram, &iType);
  } catch(tuvok::GLError gl) {
    T_ERROR("Error (%d) obtaining uniform %s in '%s' or '%s'.", gl.errno(),
            name, m_sVS.c_str(), m_sFS.c_str());
    return;
  }

  switch (iType) {
    case GL_FLOAT_MAT2:          glUniformMatrix2fv(iLocation,1,bTranspose,m); break;
    case GL_FLOAT_MAT3:          glUniformMatrix3fv(iLocation,1,bTranspose,m); break;
    case GL_FLOAT_MAT4:          glUniformMatrix4fv(iLocation,1,bTranspose,m); break;
    default:
      T_ERROR("Unknown type (%d) for %s.", iType, name);
      break;
  }
#ifdef GLSL_DEBUG
  CheckGLError("SetUniformMatrix(%s,float*,bool)",name);
#endif
}
Пример #3
0
void TZlibAsyncChannel::sendMessage(const VoidCallback& callback,
                                    const VoidCallback& errorCallback,
                                    TMemoryBuffer* message) {
  assert(message);
  DestructorGuard dg(this);

  if (!good()) {
    T_DEBUG_T("zlib channel: attempted to send on non-good channel");
    return errorCallback();
  }

  if (sendRequest_.isSet()) {
    T_ERROR("zlib async channel currently does not support multiple "
            "outstanding send requests");
    return errorCallback();
  }

  try {
    sendRequest_.set(callback, errorCallback, message);
  } catch (const std::exception& ex) {
    T_ERROR("zlib async channel: error initializing send: %s", ex.what());
    return errorCallback();
  }

  sendRequest_.send(channel_.get());
}
Пример #4
0
void TZlibAsyncChannel::recvMessage(const VoidCallback& callback,
                                    const VoidCallback& errorCallback,
                                    TMemoryBuffer* message) {
  assert(message);
  DestructorGuard dg(this);

  if (!good()) {
    T_DEBUG_T("zlib channel: attempted to read on non-good channel");
    return errorCallback();
  }

  if (recvRequest_.isSet()) {
    T_ERROR("zlib async channel is already reading");
    return errorCallback();
  }

  try {
    recvRequest_.set(callback, errorCallback, message);
  } catch (const std::exception& ex) {
    T_ERROR("zlib async channel: error initializing receive: %s", ex.what());
    return errorCallback();
  }

  recvRequest_.recv(channel_.get());
}
Пример #5
0
/**
 * Initializes the class.
 * If GLSLProgram is initialized for the first time, initialize GLEW
 * \param void
 * \return bool
 * \author <a href="mailto:[email protected]">Jens Schneider</a>
 * \date Aug.2004
 * \see m_bGlewInitialized
 */
bool GLSLProgram::Initialize(void) {
  if (!m_bGlewInitialized) {
    GLenum err = glewInit();
    if(err != GLEW_OK) {
      T_ERROR("GLEW initialization failed: %s", glewGetErrorString(err));
    } else {
      m_bGlewInitialized=true;
    }
  }
#ifdef GLSL_DEBUG  // just in case someone wants to handle GLEW himself (by setting the static var to true) but failed to do so properly
  else {
    if (glMultiTexCoord2f==NULL) T_ERROR("GLEW must be initialized. Set GLSLProgram::m_bGlewInitialized = false in GLSLProgram.cpp if you want this class to do it for you");
  }
#endif

  if (!m_bGLChecked) {
    MESSAGE("Initializing OpenGL on a: %s",
            (const char*)glGetString(GL_VENDOR));
    if (atof((const char*)glGetString(GL_VERSION)) >= 2.0) {
      MESSAGE("OpenGL 2.0 supported");
      m_bGLUseARB = false;
    } else { // check for ARB extensions
      if (glewGetExtension("GL_ARB_shader_objects"))
        MESSAGE("ARB_shader_objects supported.");
      else {
        T_ERROR("Neither OpenGL 2.0 nor ARB_shader_objects not supported!");
        return false;
      }
      if (glewGetExtension("GL_ARB_shading_language_100"))
        MESSAGE("ARB_shading_language_100 supported.");
      else {
        MESSAGE("Neither OpenGL 2.0 nor ARB_shading_language_100 not supported!");
        return false;
      }

      glUniform1i  = glUniform1iARB;    glUniform2i  = glUniform2iARB;
      glUniform1iv = glUniform1ivARB;   glUniform2iv = glUniform2ivARB;
      glUniform3i  = glUniform3iARB;    glUniform4i  = glUniform4iARB;
      glUniform3iv = glUniform3ivARB;   glUniform4iv = glUniform4ivARB;

      glUniform1f  = glUniform1fARB;    glUniform2f  = glUniform2fARB;
      glUniform1fv = glUniform1fvARB;   glUniform2fv = glUniform2fvARB;
      glUniform3f  = glUniform3fARB;    glUniform4f  = glUniform4fARB;
      glUniform3fv = glUniform3fvARB;   glUniform4fv = glUniform4fvARB;

      glUniformMatrix2fv = glUniformMatrix2fvARB;
      glUniformMatrix3fv = glUniformMatrix3fvARB;
      glUniformMatrix4fv = glUniformMatrix4fvARB;

      m_bGLUseARB = true;
    }
  }
  return true;
}
Пример #6
0
/**
 * Sets an uniform vector parameter.
 * \warning uses glGetError();
 * \param name - name of the parameter
 * \param x,y,z,w - up to four float components of the vector to set.
 * \return void
 * \author <a href="mailto:[email protected]">Jens Schneider</a>
 * \date Aug.2004
 */
void GLSLProgram::SetUniformVector(const char *name,
                                   float x, float y, float z, float w) const {
  assert(m_bEnabled);
  CheckGLError();

  GLenum iType;
  GLint iLocation;

  try {
    iLocation = get_uniform_vector(name, m_hProgram, &iType);
  } catch(tuvok::GLError gl) {
    T_ERROR("Error (%d) obtaining uniform %s in '%s' or '%s'.", gl.errno(),
            name, m_sVS.c_str(), m_sFS.c_str());
    return;
  }

  switch (iType) {
    case GL_FLOAT:      glUniform1f(iLocation,x); break;
    case GL_FLOAT_VEC2: glUniform2f(iLocation,x,y); break;
    case GL_FLOAT_VEC3: glUniform3f(iLocation,x,y,z); break;
    case GL_FLOAT_VEC4: glUniform4f(iLocation,x,y,z,w); break;

#ifdef GLSL_ALLOW_IMPLICIT_CASTS
    case GL_INT:
    case GL_SAMPLER_1D:
    case GL_SAMPLER_2D:
    case GL_SAMPLER_3D:
    case GL_SAMPLER_CUBE:
    case GL_SAMPLER_1D_SHADOW:
    case GL_SAMPLER_2D_SHADOW:
    case GL_SAMPLER_2D_RECT_ARB:
    case GL_SAMPLER_2D_RECT_SHADOW_ARB:  glUniform1i(iLocation,int(x)); break;

    case GL_INT_VEC2:   glUniform2i(iLocation,int(x),int(y)); break;
    case GL_INT_VEC3:   glUniform3i(iLocation,int(x),int(y),int(z)); break;
    case GL_INT_VEC4:   glUniform4i(iLocation,int(x),int(y),int(z),int(w)); break;
    case GL_BOOL:       glUniform1f(iLocation,x); break;
    case GL_BOOL_VEC2:  glUniform2f(iLocation,x,y); break;
    case GL_BOOL_VEC3:  glUniform3f(iLocation,x,y,z); break;
    case GL_BOOL_VEC4:  glUniform4f(iLocation,x,y,z,w); break;
#endif

    default:
      T_ERROR("Unknown type (%d) for %s.", iType, name);
      break;
  }
#ifdef GLSL_DEBUG
  CheckGLError("SetUniformVector(%s,float,...)",name);
#endif
}
Пример #7
0
void
AsyncClientWorker::run() {
  int loopCount = 0;
  std::list<AsyncRunner *> clients;
  std::list<AsyncRunner *>::iterator it;
  do {
    // Create a new connection
    int n_clients = getConfig()->getAsyncClients();
    // Determine how many operations to perform on this connection

    for (int i = 0; i < n_clients; i++) {
      std::shared_ptr<TAsyncSocket> socket;
      try {
        socket = createSocket();
      } catch (const std::exception& ex) {
        ErrorAction action = handleConnError(ex);
        if (action == EA_CONTINUE || action == EA_NEXT_CONNECTION) {
          // continue the next connection loop
          continue;
        } else if (action == EA_DROP_THREAD) {
          T_ERROR("worker %d exiting after connection error", getID());
          stopWorker();
          return;
        } else if (action == EA_ABORT) {
          T_ERROR("worker %d causing abort after connection error", getID());
          abort();
        } else {
          T_ERROR("worker %d received unknown conn error action %d; aborting",
                  getID(), action);
          abort();
        }
      }
    }

    eb_.loop();

    for (it = clients_.begin(); it != clients_.end(); ++it) {
      AsyncRunner *r = *it;
      r->stop();
      delete r;
    }
    clients_.clear();

  }
  while (MAX_LOOPS == 0 || ++loopCount < MAX_LOOPS);

  stopWorker();
}
Пример #8
0
TvkContext* TvkContext::Create(uint32_t width, uint32_t height,
                               uint8_t color_bits, uint8_t depth_bits,
                               uint8_t stencil_bits, bool double_buffer,
                               bool visible)
{
  TvkContext* ctx;
#ifdef DETECTED_OS_WINDOWS
  ctx = new TvkWGLContext(width, height, color_bits, depth_bits, stencil_bits,
                          double_buffer, visible);
#elif defined(DETECTED_OS_APPLE) && defined(USE_CGL)
  ctx = new TvkCGLContext(width, height, color_bits, depth_bits, stencil_bits,
                          double_buffer, visible);
#elif defined(DETECTED_OS_APPLE)
  ctx = new TvkAGLContext(width, height, color_bits, depth_bits, stencil_bits,
                          double_buffer, visible);
#else
  ctx = new TvkGLXContext(width, height, color_bits, depth_bits, stencil_bits,
                          double_buffer, visible);
#endif
  GLenum glerr = glewInit();
  if(GLEW_OK != glerr) {
    T_ERROR("Error initializing GLEW: %s", glewGetErrorString(glerr));
    throw std::runtime_error("could not initialize GLEW.");
  }
  return ctx;
}
Пример #9
0
bool LuaIOManagerProxy::ExtractImageStack(
    LuaClassInstance ds,
    LuaClassInstance tf1d,
    uint64_t iLODlevel, 
    const std::string& strTargetFilename,
    const std::string& strTempDir,
    bool bAllDirs) const {
  if (mSS->cexecRet<LuaDatasetProxy::DatasetType>(
          ds.fqName() + ".getDSType") != LuaDatasetProxy::UVF) {
    T_ERROR("tuvok.io.exportDataset only accepts UVF.");
    return false;
  }

  // Convert LuaClassInstance -> LuaDatasetProxy -> UVFdataset
  LuaDatasetProxy* dsProxy = ds.getRawPointer<LuaDatasetProxy>(mSS);
  UVFDataset* uvf = dynamic_cast<UVFDataset*>(dsProxy->getDataset());
  assert(uvf != NULL);

  // Now we need to extract the transfer function...
  LuaTransferFun1DProxy* tfProxy = tf1d.getRawPointer<LuaTransferFun1DProxy>(
      mSS);
  TransferFunction1D* pTrans = tfProxy->get1DTransferFunction();
  assert(pTrans != NULL);

  return mIO->ExtractImageStack(
      uvf, pTrans, iLODlevel,
      strTargetFilename,
      strTempDir,
      bAllDirs);
}
Пример #10
0
void TFramedACWriteRequest::writeError(
    size_t bytesWritten,
    const TTransportException& ex) noexcept {
  T_ERROR("TFramedAC: write failed after writing %zu bytes: %s",
          bytesWritten, ex.what());
  invokeErrorCallback();
}
Пример #11
0
static GLint get_uniform_vector(const char *name, GLuint program, GLenum *type)
{
  glGetError();  // flush current error state.

  GLint size;
  GLint location;

  // Get the position for the uniform var.
  if(GLSLProgram::m_bGLUseARB) {
    location=glGetUniformLocationARB(program, name);
  } else {
    location=glGetUniformLocation(program, name);
  }
  GLenum gl_err = glGetError();
  if(gl_err != GL_NO_ERROR || location == -1) {
    throw GL_ERROR(gl_err);
  }

  if (GLSLProgram::m_bGLUseARB) {
    glGetActiveUniformARB(program, location, 0, NULL, &size, type, NULL);
  } else {
    glGetActiveUniform(program, location, 1, &AtiHackLen, &size, type,
                       &AtiHackChar);
  }

  gl_err = glGetError();
  if(gl_err != GL_NO_ERROR) {
    T_ERROR("Error getting type.");
    throw GL_ERROR(gl_err);
  }

  return location;
}
Пример #12
0
int read_base_port(ndxml *xmlroot)
{
	ndxml *xml_sub = ndxml_refsub(xmlroot,"base_port") ;
	if (!xml_sub){
		T_ERROR("read base port error") ;
	}
	return ndxml_getval_int(xml_sub) ;
};
Пример #13
0
void ClientWorker2::performThrowUnexpected(const std::shared_ptr<Client>& client) {
  try {
    client->sync_throwUnexpected(loadgen::RNG::getU32());
    T_ERROR("throwUnexpected() didn't throw any exception");
  } catch (const TApplicationException& error) {
    // expected; do nothing
  }
}
Пример #14
0
void ClientWorker2::performThrowError(const std::shared_ptr<Client>& client) {
  uint32_t code = loadgen::RNG::getU32();
  try {
    client->sync_throwError(code);
    T_ERROR("throwError() didn't throw any exception");
  } catch (const LoadError& error) {
    assert(error.code == code);
  }
}
Пример #15
0
/**
 * Disables the program for rendering.
 * Generates error messages if something went wrong (i.e. program not initialized etc.)
 * \param void
 * \return void
 * \warning uses glGetError()
 * \author <a href="mailto:[email protected]">Jens Schneider</a>
 * \date Aug.2004
 */
void GLSLProgram::Disable(void) {
  if (m_bInitialized) {
    CheckGLError();
    if (m_bGLUseARB)
      glUseProgramObjectARB(0);
    else
      glUseProgram(0);
    if (!CheckGLError("Disable()")) m_bEnabled=false;
  }
  else T_ERROR("No program loaded!");
}
Пример #16
0
void ClientWorker2::performAdd(const std::shared_ptr<Client>& client) {
  boost::uniform_int<int64_t> distribution;
  int64_t a = distribution(loadgen::RNG::getRNG());
  int64_t b = distribution(loadgen::RNG::getRNG());

  int64_t result = client->sync_add(a, b);

  if (result != a + b) {
    T_ERROR("add(%" PRId64 ", %" PRId64 " gave wrong result %" PRId64
            "(expected %" PRId64 ")", a, b, result, a + b);
  }
}
Пример #17
0
/**
 * Sets an uniform vector parameter.
 * \warning uses glGetError();
 * \param name - name of the parameter
 * \param x,y,z,w - up to four bool components of the vector to set.
 * \return void
 * \author <a href="mailto:[email protected]">Jens Schneider</a>
 * \date Mar.2005
 */
void GLSLProgram::SetUniformVector(const char *name,bool x, bool y, bool z, bool w) const {
  assert(m_bEnabled);
  CheckGLError();

  GLenum iType;
  GLint iLocation;

  try {
    iLocation = get_uniform_vector(name, m_hProgram, &iType);
  } catch(tuvok::GLError gl) {
    T_ERROR("Error (%d) obtaining uniform %s in '%s' or '%s'.", gl.errno(),
            name, m_sVS.c_str(), m_sFS.c_str());
    return;
  }

  switch (iType) {
    case GL_BOOL:            glUniform1i(iLocation,(x ? 1 : 0)); break;
    case GL_BOOL_VEC2:          glUniform2i(iLocation,(x ? 1 : 0),(y ? 1 : 0)); break;
    case GL_BOOL_VEC3:          glUniform3i(iLocation,(x ? 1 : 0),(y ? 1 : 0),(z ? 1 : 0)); break;
    case GL_BOOL_VEC4:          glUniform4i(iLocation,(x ? 1 : 0),(y ? 1 : 0),(z ? 1 : 0),(w ? 1 : 0)); break;

#ifdef GLSL_ALLOW_IMPLICIT_CASTS
    case GL_FLOAT:            glUniform1f(iLocation,(x ? 1.0f : 0.0f)); break;
    case GL_FLOAT_VEC2:          glUniform2f(iLocation,(x ? 1.0f : 0.0f),(y ? 1.0f : 0.0f)); break;
    case GL_FLOAT_VEC3:          glUniform3f(iLocation,(x ? 1.0f : 0.0f),(y ? 1.0f : 0.0f),(z ? 1.0f : 0.0f)); break;
    case GL_FLOAT_VEC4:          glUniform4f(iLocation,(x ? 1.0f : 0.0f),(y ? 1.0f : 0.0f),(z ? 1.0f : 0.0f),(w ? 1.0f : 0.0f)); break;
    case GL_INT:            glUniform1i(iLocation,(x ? 1 : 0)); break;
    case GL_INT_VEC2:          glUniform2i(iLocation,(x ? 1 : 0),(y ? 1 : 0)); break;
    case GL_INT_VEC3:          glUniform3i(iLocation,(x ? 1 : 0),(y ? 1 : 0),(z ? 1 : 0)); break;
    case GL_INT_VEC4:          glUniform4i(iLocation,(x ? 1 : 0),(y ? 1 : 0),(z ? 1 : 0),(w ? 1 : 0)); break;
#endif

    default:
      T_ERROR("Unknown type (%d) for %s.", iType, name);
      break;
  }
#ifdef GLSL_DEBUG
  CheckGLError("SetUniformVector(%s,bool,...)",name);
#endif
}
Пример #18
0
bool GLSLProgram::CheckGLError(const char *pcError, const char *pcAdditional) const{
  if (pcError==NULL) {  // Simply check for error, true if an error occured.
    return (glGetError()!=GL_NO_ERROR);
  }
  else {  // print out error
    GLenum iError=glGetError();
    char *pcMessage;
    if (pcAdditional) {
      size_t len=16+strlen(pcError)+(pcAdditional ? strlen(pcAdditional) : 0);
      pcMessage=new char[len];
      sprintf(pcMessage,pcError,pcAdditional);
    }
    else pcMessage=(char*)pcError;

    std::ostringstream msg;
    msg << pcMessage << " - ";
    switch (iError) {
      case GL_NO_ERROR:
        if (pcMessage!=pcError) delete[] pcMessage;
        return false;
        break;
      case GL_INVALID_ENUM:
        msg << "GL_INVALID_ENUM";
        break;
      case GL_INVALID_VALUE:
        msg << "GL_INVALID_VALUE";
        break;
      case GL_INVALID_OPERATION:
        msg << "GL_INVALID_OPERATION";
        break;
      case GL_STACK_OVERFLOW:
        msg << "GL_STACK_OVERFLOW";
        break;
      case GL_STACK_UNDERFLOW:
        msg << "GL_STACK_UNDERFLOW";
        break;
      case GL_OUT_OF_MEMORY:
        msg << "GL_OUT_OF_MEMORY";
        break;
      default:
        msg << "unknown GL_ERROR " << iError;
        break;
    }
    if (pcMessage!=pcError) delete[] pcMessage;

    // display the error.
    T_ERROR("%s", msg.str().c_str());

    return true;
  }
}
Пример #19
0
void ClientWorker2::performOperation(const std::shared_ptr<Client>& client,
                                    uint32_t opType) {
  switch (static_cast<ClientLoadConfig::OperationEnum>(opType)) {
    case ClientLoadConfig::OP_NOOP:
      return performNoop(client);
    case ClientLoadConfig::OP_ONEWAY_NOOP:
      return performOnewayNoop(client);
    case ClientLoadConfig::OP_ASYNC_NOOP:
      return performAsyncNoop(client);
    case ClientLoadConfig::OP_SLEEP:
      return performSleep(client);
    case ClientLoadConfig::OP_ONEWAY_SLEEP:
      return performOnewaySleep(client);
    case ClientLoadConfig::OP_BURN:
      return performBurn(client);
    case ClientLoadConfig::OP_ONEWAY_BURN:
      return performOnewayBurn(client);
    case ClientLoadConfig::OP_BAD_SLEEP:
      return performBadSleep(client);
    case ClientLoadConfig::OP_BAD_BURN:
      return performBadBurn(client);
    case ClientLoadConfig::OP_THROW_ERROR:
      return performThrowError(client);
    case ClientLoadConfig::OP_THROW_UNEXPECTED:
      return performThrowUnexpected(client);
    case ClientLoadConfig::OP_ONEWAY_THROW:
      return performOnewayThrow(client);
    case ClientLoadConfig::OP_SEND:
      return performSend(client);
    case ClientLoadConfig::OP_ONEWAY_SEND:
      return performOnewaySend(client);
    case ClientLoadConfig::OP_RECV:
      return performRecv(client);
    case ClientLoadConfig::OP_SENDRECV:
      return performSendrecv(client);
    case ClientLoadConfig::OP_ECHO:
      return performEcho(client);
    case ClientLoadConfig::OP_ADD:
      return performAdd(client);
    case ClientLoadConfig::NUM_OPS:
      // fall through
      break;
    // no default case, so gcc will warn us if a new op is added
    // and this switch statement is not updated
  }

  T_ERROR("ClientWorker2::performOperation() got unknown operation %" PRIu32,
          opType);
  assert(false);
}
Пример #20
0
bool TFileTransport::isEventCorrupted() {
  // an error is triggered if:
  if ( (maxEventSize_ > 0) &&  (readState_.event_->eventSize_ > maxEventSize_)) {
    // 1. Event size is larger than user-speficied max-event size
    T_ERROR("Read corrupt event. Event size(%u) greater than max event size (%u)",
            readState_.event_->eventSize_, maxEventSize_);
    return true;
  } else if (readState_.event_->eventSize_ > chunkSize_) {
    // 2. Event size is larger than chunk size
    T_ERROR("Read corrupt event. Event size(%u) greater than chunk size (%u)",
               readState_.event_->eventSize_, chunkSize_);
    return true;
  } else if( ((offset_ + readState_.bufferPtr_ - 4)/chunkSize_) !=
             ((offset_ + readState_.bufferPtr_ + readState_.event_->eventSize_ - 1)/chunkSize_) ) {
    // 3. size indicates that event crosses chunk boundary
    T_ERROR("Read corrupt event. Event crosses chunk boundary. Event size:%u  Offset:%lu",
            readState_.event_->eventSize_,
            (offset_ + readState_.bufferPtr_ + 4));

    return true;
  }

  return false;
}
Пример #21
0
bool LuaIOManagerProxy::ExportDataset(LuaClassInstance ds,
                                      uint64_t iLODlevel,
                                      const string& strTargetFilename,
                                      const string& strTempDir) const
{
  if (mSS->cexecRet<LuaDatasetProxy::DatasetType>(
          ds.fqName() + ".getDSType") != LuaDatasetProxy::UVF) {
    T_ERROR("tuvok.io.exportDataset only accepts UVF.");
    return false;
  }

  // Convert LuaClassInstance -> LuaDatasetProxy -> UVFdataset
  LuaDatasetProxy* dsProxy = ds.getRawPointer<LuaDatasetProxy>(mSS);
  UVFDataset* uvf = dynamic_cast<UVFDataset*>(dsProxy->getDataset());
  assert(uvf != NULL);

  return mIO->ExportDataset(uvf, iLODlevel, strTargetFilename, 
                            strTempDir);
}
Пример #22
0
bool TFramedACReadState::readDataAvailable(size_t len) {
  if (bytesRead_ < sizeof(frameSize_)) {
    // We just read bytes into the frame size buffer
    assert(bytesRead_ + len <= sizeof(frameSize_));
    bytesRead_ += len;
    if (bytesRead_ >= sizeof(frameSize_)) {
      // We've finished reading the frame size
      // Convert the frame size to host byte order
      frameSize_ = folly::Endian::big(frameSize_);

      // Check for overly large frame sizes, so that we reject garbage data
      // instead of allocating a huge buffer.
      if (frameSize_ > maxFrameSize_) {
        T_ERROR("TFramedAC::read(): frame size of %d rejected", frameSize_);
        throw TTransportException(TTransportException::CORRUPTED_DATA,
                                  "rejected overly large frame size");
      }

      // The empty frame is complete without body bytes
      if (frameSize_ == 0) {
        return true;
      }
    }
  } else {
    // We just read body bytes
    bytesRead_ += len;
    uint32_t bufBytesRead = bytesRead_ - sizeof(frameSize_);
    assert(bufBytesRead <= frameSize_);
    buffer_->wroteBytes(len);

    if (bufBytesRead >= frameSize_) {
      // We've finished reading the frame.
      return true;
    }
  }

  // We aren't done with the frame yet.
  return false;
}
Пример #23
0
void TZlibAsyncChannel::RecvRequest::recvSuccess() {
  // Uncompress the buffer
  try {
    // Process in 64kb blocks
    const uint32_t kUncompressBlock = 1 << 16;
    while (true) {
      uint8_t* writePtr = callbackBuffer_->getWritePtr(kUncompressBlock);
      uint32_t readBytes = zlibTransport_.read(writePtr, kUncompressBlock);
      if (readBytes <= 0) {
        break;
      } else {
        callbackBuffer_->wroteBytes(readBytes);
      }
    }
  } catch (const std::exception& ex) {
    T_ERROR("zlib channel: error uncompressing data: %s", ex.what());
    recvError();
    return;
  }

  invokeCallback(callback_);
}
Пример #24
0
bool VTKConverter::ConvertToRAW(
    const std::string& strSourceFilename,
    const std::string& /* tempdir */, bool /* user interaction */,
    uint64_t& iHeaderSkip, unsigned& iComponentSize, uint64_t& iComponentCount,
    bool& bConvertEndianness, bool& bSigned, bool& bIsFloat,
    UINT64VECTOR3& vVolumeSize, FLOATVECTOR3& vVolumeAspect,
    std::string& strTitle, std::string& strIntermediateFile,
    bool& bDeleteIntermediateFile
) {
  MESSAGE("Converting %s from VTK...", strSourceFilename.c_str());

  strTitle = "from VTK converter";
  std::ifstream vtk(strSourceFilename.c_str(), std::ios::binary);

  std::string current, junk;
  std::getline(vtk, current); // ignore comment line
  std::getline(vtk, current); // ignore "PsiPhi grid data"
  vtk >> current;
  if(current != "BINARY") {
    T_ERROR("I can only read binary VTK data; this is '%s'", current.c_str());
    return false;
  }
  vtk >> junk >> current;
  if(current != "STRUCTURED_POINTS") {
    T_ERROR("I can only read STRUCTURED_POINTS data; this is '%s'",
            current.c_str());
    return false;
  }
  vVolumeSize = UINT64VECTOR3(0,0,0);
  vtk >> junk >> vVolumeSize[0] >> vVolumeSize[1] >> vVolumeSize[2];
  if(vVolumeSize[0] == 0 || vVolumeSize[1] == 0 || vVolumeSize[2] == 0) {
    T_ERROR("Invalid 0-length volume size!");
    return false;
  }
  // indices are 1-based!! (cell data)
  vVolumeSize[0] -= 1;
  vVolumeSize[1] -= 1;
  vVolumeSize[2] -= 1;
  MESSAGE("VTK volume is %llux%llux%llu", vVolumeSize[0], vVolumeSize[1],
          vVolumeSize[2]);
  vtk >> junk >> junk >> junk >> junk; // ORIGIN blah blah blah
  vtk >> junk >> vVolumeAspect[0] >> vVolumeAspect[1] >> vVolumeAspect[2];
  MESSAGE("aspect: %5.3fx%5.3fx%5.3f", vVolumeAspect[0], vVolumeAspect[1],
          vVolumeAspect[2]);

  // now we now the basics of the data, but we can have multiple fields in the
  // file.  Scan through until we find the first SCALARS.
  scan_for_line(vtk, "SCALARS");
  if(vtk.eof()) {
    T_ERROR("No scalar data in file!");
    return false;
  }
  std::string type, one;
  vtk >> junk >> current >> type >> one;
  assert(junk == "SCALARS"); // if not, then scan_for_line failed.
  strTitle = current + " from VTK converter";
  MESSAGE("Reading field '%s' from the VTK file...", current.c_str());
  assert(one == "1"); // this is always "1" in the files I have...
  BStreamDescriptor bs = vtk_to_tuvok_type(type);
  iComponentSize = bs.width * 8; // bytes to bits
  iComponentCount = bs.components;
  bSigned = bs.is_signed;
  bIsFloat = bs.fp;
  // legacy VTK files are always Big endian, so we need to convert if we're
  // little endian.
  bConvertEndianness = EndianConvert::IsLittleEndian();
  vtk >> junk >> current; // "LOOKUP_TABLE default"

  // gotta get rid of a byte before we figure out where we are.
  char newline;
  vtk.read(&newline, 1);
  // we can just skip to the binary data without creating a new file.  Do that.
  iHeaderSkip = static_cast<uint64_t>(vtk.tellg());
  {
    std::ofstream raw("rawdata-from-vtk.data", std::ios::binary);
    const uint64_t elems = vVolumeSize.volume();
    float cur;
    for(uint64_t i=0; i < elems; ++i) {
      vtk.read(reinterpret_cast<char*>(&cur), sizeof(float));
      raw.write(reinterpret_cast<char*>(&cur), sizeof(float));
    }
    raw.close();
  }

  strIntermediateFile = strSourceFilename;
  bDeleteIntermediateFile = false;

  return true;
}
Пример #25
0
bool AmiraConverter::ConvertToRAW(const std::string& strSourceFilename,
                                    const std::string& strTempDir,
                                    bool,
                                    uint64_t& iHeaderSkip,
                                    unsigned& iComponentSize,
                                    uint64_t& iComponentCount,
                                    bool& bConvertEndianness,
                                    bool& bSigned, bool& bIsFloat,
                                    UINT64VECTOR3& vVolumeSize,
                                    FLOATVECTOR3& vVolumeAspect,
                                    std::string& strTitle,
                                    std::string& strIntermediateFile,
                                    bool& bDeleteIntermediateFile)
{
  strTitle = "from Amira converter";

  std::ifstream amira(strSourceFilename.c_str());
  if(!amira) {
    T_ERROR("Could not open %s!", strSourceFilename.c_str());
    return false;
  }

  iHeaderSkip = 0; // we'll create a new, raw file.
  iComponentSize = 64;
  iComponentCount = 1;
  bConvertEndianness = false;
  bSigned = true;
  bIsFloat = true;
  vVolumeAspect = FLOATVECTOR3(1.0, 1.0, 1.0);
  strIntermediateFile = strTempDir + "/" + "am.iv3d.tmp";
  bDeleteIntermediateFile = true;

  std::string junk;
  std::string version;
  amira >> junk >> junk >> junk >> version; // "# AmiraMesh ASCII 1.0"
  MESSAGE("Reading 'AmiraMesh' file, version %s", version.c_str());

  // "define Lattice    X    Y    Z"
  amira >> junk >> junk >> vVolumeSize[0] >> vVolumeSize[1] >> vVolumeSize[2];
  assert(vVolumeSize[0] > 0);
  assert(vVolumeSize[1] > 0);
  assert(vVolumeSize[2] > 0);

  MESSAGE("%llu-bit %llux%llux%llu data.", iComponentSize,
          vVolumeSize[0], vVolumeSize[1], vVolumeSize[2]);

  // The rest of the header is stuff we don't bother with right now, and then:
  //
  //    Lattice { float Data } = @1
  //
  //    @1
  //      first-elem 2nd-elem ...
  //
  // Presumably they could define multiple "Lattice"s and then use @2, @3,
  // etc., but I don't have any such example data files, so screw it.
  // We're just going to read up until that @1.  Then we'll read up until the
  // next @1.  At that point we can just copy each elem into an output file.
  do { amira >> junk; } while(junk != "@1"); // " ... } = @1"
  do { amira >> junk; } while(junk != "@1"); // "@1\n"

  std::ofstream inter(strIntermediateFile.c_str(),
                      std::ofstream::out | std::ofstream::out);
  if(!inter) {
    T_ERROR("Could not create intermediate file '%s'.",
            strIntermediateFile.c_str());
    bDeleteIntermediateFile = false;
    return false;
  }
  std::copy(std::istream_iterator<double>(amira),
            std::istream_iterator<double>(),
            binary_ostream_iterator(inter));
  return true;
}
Пример #26
0
int read_config(ndxml *xmlroot, const char *name, struct server_config *scfg) 
{
	ndxml *xml_sub,*xml_listen ;
	
	int base_port = read_base_port(xmlroot) ;

	memset(scfg, 0, sizeof(scfg)) ;
	if (0==base_port) {
		return -1;
	}
	
	xml_sub = ndxml_refsub(xmlroot,name) ;
	if (!xml_sub){
		T_ERROR("read base port error") ;
	}

	if(-1== read_instance_info(xml_sub, &scfg->i_cfg)) {
		return -1 ;
	}


	xml_listen = ndxml_refsub(xml_sub,"listen") ;
	if (!xml_listen){
		T_ERROR("read base port error") ;
	}	
	if(-1== read_listen_cfg(xml_listen,  base_port,&scfg->l_cfg) ) {
		return -1 ;
	}
	//

	scfg->reliable_num = 0;
	xml_listen = ndxml_refsub(xml_sub,"reliable_host") ;
	if (xml_listen){
		read_iplist(xml_listen, scfg->reliable_hosts, MAX_RELIABLE_HOST ) ;
		for(int i=0; i<MAX_RELIABLE_HOST; i++) {
			union {
				ndip_t ip ;
				NDUINT8 buf[4] ;
			}readip,ipmask;

			readip.ip = scfg->reliable_hosts[i] ;
			if (readip.ip ==0){
				break ;
			}
			ipmask.ip = 0xffffffff;
			for (int x=0; x<4; x++)	{
				if (0xff== readip.buf[x]){
					ipmask.buf[x] = 0 ;
				}
			}
			scfg->reliable_ipmask[i] = ipmask.ip;
			scfg->reliable_num++;
		}
		//get netmask
	}
	//read connectors
	
	xml_listen = ndxml_refsub(xml_sub,"connectors") ;
	if (xml_listen){
		for (int i=0; i< ND_CONNECT_OTHER_HOSTR_NUM && i<ndxml_num(xml_listen); i++) {
			ndxml *pnode = ndxml_getnodei(xml_listen, i) ;
			
			if(0== read_connect_cfg(pnode,  base_port, &scfg->i_cfg.connectors[i]) ) {
				const char *pname = ndxml_getattr_val(pnode, "name") ;
				if (pname && pname[0]) {
					strncpy(scfg->i_cfg.connectors[i].connector_name, pname,sizeof(scfg->i_cfg.connectors[i].connector_name)) ;
				}
				else {
					pname = ndxml_getname(pnode) ;
					strncpy(scfg->i_cfg.connectors[i].connector_name, pname,sizeof(scfg->i_cfg.connectors[i].connector_name)) ;
				}
			}
		}
	}
	
	return 0 ;
}
Пример #27
0
/**
 * Sets an uniform array.
 * Sets the entire array at once. Single positions can still be set using the other SetUniform*() methods.
 * \warning uses glGetError();
 * \param name - name of the parameter
 * \param a - a bool array containing enough floats to fill the entire uniform array.
 * \return void
 * \author <a href="mailto:[email protected]">Jens Schneider</a>
 * \date Mar.2005
 */
void GLSLProgram::SetUniformArray(const char *name,const bool  *a) const {
  assert(m_bEnabled);
  CheckGLError();

  GLint iSize;
  GLenum iType;
  GLint iLocation;

  if (m_bGLUseARB) {
    iLocation=glGetUniformLocationARB(m_hProgram,name);
  } else {
    iLocation=glGetUniformLocation(m_hProgram,name);
  }

  if (CheckGLError("SetUniformVector(%s,float,...) [getting adress]",name)) {
    return;
  }

  if(iLocation==-1) {
    T_ERROR("Error getting address for %s in '%s' or '%s'.", name,
            m_sVS.c_str(), m_sFS.c_str());
    return;
  }

  if (m_bGLUseARB) {
    glGetActiveUniformARB(m_hProgram,iLocation,0,NULL,&iSize,&iType,NULL);
  } else {
    glGetActiveUniform(m_hProgram,iLocation,1,&AtiHackLen,&iSize,&iType,
                       &AtiHackChar);
  }

  if (CheckGLError("SetUniformVector(%s,float,...) [getting type]",name)) {
    return;
  }

#ifdef GLSL_ALLOW_IMPLICIT_CASTS
  float *fArray;
#endif
  GLint *iArray;
  switch (iType) {
    case GL_BOOL:
      iArray=new GLint[iSize];
      for (int i=0; i<iSize; i++) iArray[i]=(a[i] ? 1 : 0);
      glUniform1iv(iLocation,iSize,iArray);
      delete[] iArray;
      break;
    case GL_BOOL_VEC2:
      iArray=new GLint[2*iSize];
      for (int i=0; i<2*iSize; i++) iArray[i]=(a[i] ? 1 : 0);
      glUniform2iv(iLocation,iSize,iArray);
      delete[] iArray;
      break;
    case GL_BOOL_VEC3:
      iArray=new GLint[3*iSize];
      for (int i=0; i<3*iSize; i++) iArray[i]=(a[i] ? 1 : 0);
      glUniform3iv(iLocation,iSize,iArray);
      delete[] iArray;
      break;
    case GL_BOOL_VEC4:
      iArray=new GLint[4*iSize];
      for (int i=0; i<4*iSize; i++) iArray[i]=(a[i] ? 1 : 0);
      glUniform4iv(iLocation,iSize,iArray);
      delete[] iArray;
      break;

#ifdef GLSL_ALLOW_IMPLICIT_CASTS
    case GL_INT:
      iArray=new GLint[iSize];
      for (int i=0; i<iSize; i++) iArray[i]=(a[i] ? 1 : 0);
      glUniform1iv(iLocation,iSize,iArray);
      delete[] iArray;
      break;
    case GL_INT_VEC2:
      iArray=new GLint[2*iSize];
      for (int i=0; i<2*iSize; i++) iArray[i]=(a[i] ? 1 : 0);
      glUniform2iv(iLocation,iSize,iArray);
      delete[] iArray;
      break;
    case GL_INT_VEC3:
      iArray=new GLint[3*iSize];
      for (int i=0; i<3*iSize; i++) iArray[i]=(a[i] ? 1 : 0);
      glUniform3iv(iLocation,iSize,iArray);
      delete[] iArray;
      break;
    case GL_INT_VEC4:
      iArray=new GLint[4*iSize];
      for (int i=0; i<4*iSize; i++) iArray[i]=(a[i] ? 1 : 0);
      glUniform4iv(iLocation,iSize,iArray);
      delete[] iArray;
      break;
    case GL_FLOAT:
      fArray=new float[iSize];
      for (int i=0; i<iSize; i++) fArray[i]=(a[i] ? 1.0f : 0.0f);
      glUniform1fv(iLocation,iSize,fArray);
      delete[] fArray;
      break;
    case GL_FLOAT_VEC2:
      fArray=new float[2*iSize];
      for (int i=0; i<2*iSize; i++) fArray[i]=(a[i] ? 1.0f : 0.0f);
      glUniform2fv(iLocation,iSize,fArray);
      delete[] fArray;
      break;
    case GL_FLOAT_VEC3:
      fArray=new float[3*iSize];
      for (int i=0; i<3*iSize; i++) fArray[i]=(a[i] ? 1.0f : 0.0f);
      glUniform3fv(iLocation,iSize,fArray);
      delete[] fArray;
      break;
    case GL_FLOAT_VEC4:
      fArray=new float[4*iSize];
      for (int i=0; i<4*iSize; i++) fArray[i]=(a[i] ? 1.0f : 0.0f);
      glUniform4fv(iLocation,iSize,fArray);
      delete[] fArray;
      break;
#endif

    default:
      T_ERROR("Unknown type (%d) for %s.", iType, name);
      break;
  }
#ifdef GLSL_DEBUG
  CheckGLError("SetUniformArray(%s,bool*)",name);
#endif
}
Пример #28
0
/**
 * Loads vertex and fragment shader from disk/memory.
 * Loads any combination of vertex and fragment shader from disk or from a memory position.
 * Generates error/information messages to stdout during loading.
 * If nor successful the handle of the shader will be set to 0.
 * \param VSFile - name of the file containing the vertex shader
 * \param FSFile - name of the file containing the fragment shader
 * \param src - selects the source of vertex and fragment shader. Can be either GLSLPROGRAM_DISK or GLSLPROGRAM_STRING
 * \return void
 * \warning Uses glGetError()
 * \author <a href="mailto:[email protected]">Jens Schneider</a>
 * \date Aug.2004
 * \see GLSLPROGRAM_SOURCE
 */
void GLSLProgram::Load(const char *VSFile, const char *FSFile, GLSLPROGRAM_SOURCE src) {
  CheckGLError();

  // load
  GLuint hVS=0;
  GLuint hFS=0;
  bool bVSSuccess=true;  // fixed function pipeline is always working
  if (VSFile!=NULL) {
    hVS=LoadShader(VSFile,GL_VERTEX_SHADER,src);
    if(hVS != 0) {
      m_sVS = std::string(VSFile); // record program source
    } else {
      bVSSuccess=false;
      if (src==GLSLPROGRAM_DISK) {
        T_ERROR("ERROR IN: %s", VSFile);
      }
      else {
        T_ERROR("---------- ERROR -----------");
        int iPos=0;
        int iLine=1;
        char chLine[32];
        char *chVerbose=new char[strlen(VSFile)+1];
        memcpy(chVerbose,VSFile,strlen(VSFile)+1);
        for (unsigned int i=0; i<strlen(VSFile); i++) {
          if (chVerbose[i]=='\n') {
            chVerbose[i]='\0';
            sprintf(chLine,"(%.4i) ",iLine++);
            T_ERROR("Load %s %s", chLine, &chVerbose[iPos]);
            iPos=i+1;
          }
        }
        delete[] chVerbose;
      }
    }
  }
  bool bFSSuccess=true;  // fixed function pipeline is always working
  if (FSFile!=NULL) {
    hFS=LoadShader(FSFile,GL_FRAGMENT_SHADER,src);
    if(hVS != 0) {
      m_sFS = std::string(FSFile); // record program source
    } else {
      bFSSuccess=false;
      if (src==GLSLPROGRAM_DISK) {
        T_ERROR( "Error in fragment shader: %s", FSFile);
      }
      else {
        T_ERROR("---------- ERROR -----------");
        int iPos=0;
        int iLine=1;
        char chLine[32];
        char *chVerbose=new char[strlen(FSFile)+1];
        memcpy(chVerbose,FSFile,strlen(FSFile)+1);
        for (unsigned int i=0; i<strlen(FSFile); i++) {
          if (chVerbose[i]=='\n') {
            chVerbose[i]='\0';
            sprintf(chLine,"(%.4i) ",iLine++);
            T_ERROR( "Load %s %s",chLine, &chVerbose[iPos]);
            iPos=i+1;
          }
        }
        delete[] chVerbose;
      }
    }
  }

  if (m_bGLUseARB) {
    // attach to shader program
    m_hProgram=glCreateProgramObjectARB();
    if (hVS) glAttachObjectARB(m_hProgram,hVS);
    if (hFS) glAttachObjectARB(m_hProgram,hFS);

    // link the program together
    if (bVSSuccess && bFSSuccess) {
      glLinkProgramARB(m_hProgram);

      // check for errors
      GLint iLinked;
      glGetObjectParameterivARB(m_hProgram,GL_OBJECT_LINK_STATUS_ARB,&iLinked);
      WriteError(m_hProgram);

      // delete temporary objects
      if (hVS) glDeleteObjectARB(hVS);
      if (hFS) glDeleteObjectARB(hFS);

      if (CheckGLError("Load()") || !iLinked) {
        glDeleteObjectARB(m_hProgram);
        m_bInitialized=false;
        return;
      } else {
        m_bInitialized=true;
      }
    } else {
      if (hVS) glDeleteObjectARB(hVS);
      if (hFS) glDeleteObjectARB(hFS);
      glDeleteObjectARB(m_hProgram);
      m_hProgram=0;
      m_bInitialized=false;
      if (!bVSSuccess && !bFSSuccess) T_ERROR("Error in vertex and fragment shaders");
      else if (!bVSSuccess) T_ERROR("Error in vertex shader");
      else if (!bFSSuccess) T_ERROR("Error in fragment shader");
    }
  } else {
    // attach to program object
    m_hProgram=glCreateProgram();
    if (hVS) glAttachShader(m_hProgram,hVS);
    if (hFS) glAttachShader(m_hProgram,hFS);

    // link the program together
    if (bVSSuccess && bFSSuccess) {
      glLinkProgram(m_hProgram);

      // check for errors
      GLint iLinked;
      glGetProgramiv(m_hProgram,GL_LINK_STATUS,&iLinked);

      std::string fileDesc = std::string("VS: ") + std::string(VSFile) +
                             std::string(", FS:") + std::string(FSFile);
      WriteInfoLog(fileDesc.c_str(), m_hProgram, true);

      // flag shaders such that they can be deleted when they get detached
      if (hVS) glDeleteShader(hVS);
      if (hFS) glDeleteShader(hFS);
      if (CheckGLError("Load()") || iLinked!=GLint(GL_TRUE)) {
        glDeleteProgram(m_hProgram);
        m_hProgram=0;
        m_bInitialized=false;
        return;
      }
      else {
        m_bInitialized=true;
      }
    }
    else {
      if (hVS) glDeleteShader(hVS);
      if (hFS) glDeleteShader(hFS);
      glDeleteProgram(m_hProgram);
      m_hProgram=0;
      m_bInitialized=false;
      if (!bVSSuccess && !bFSSuccess) T_ERROR("Error in vertex and fragment shaders");
      else if (!bVSSuccess) T_ERROR("Error in vertex shader");
      else if (!bFSSuccess) T_ERROR("Error in fragment shader");
    }
  }
}
Пример #29
0
/**
 * Loads a vertex or fragment shader.
 * Loads either a vertex or fragment shader and tries to compile it.
 * \param ShaderDesc - name of the file containing the shader
 * \param Type - either GL_VERTEX_SHADER or GL_FRAGMENT_SHADER
 * \param src - defines the source of the shader. Can be either GLSLPROGRAM_DISK or GLSLPROGRAM_STRING.
 * \return a handle to the compiled shader if successful, 0 otherwise
 * \warning uses glGetError()
 * \author <a href="mailto:[email protected]">Jens Schneider</a>
 * \date Mar.2005
 * \see GLSLPROGRAM_SOURCE
 */
GLuint GLSLProgram::LoadShader(const char *ShaderDesc, GLenum Type, GLSLPROGRAM_SOURCE src) {
  // assert right type
  assert(Type==GL_VERTEX_SHADER || Type==GL_FRAGMENT_SHADER);

  CheckGLError();

  unsigned long lFileSize;
  char *pcShader;
  FILE *fptr;

  // Load and compile vertex shader
  switch(src) {
    case GLSLPROGRAM_DISK:
      fptr=fopen(ShaderDesc,"rb");
      if (!fptr) {
        T_ERROR("File %s not found!",ShaderDesc);
        return 0;
      }
      if (fseek(fptr,0,SEEK_END)) {
        fclose(fptr);
        T_ERROR("Error reading file %s.",ShaderDesc);
        return 0;
      }
      lFileSize=ftell(fptr)/sizeof(char);
      fseek(fptr,0,SEEK_SET);
      pcShader=new char[lFileSize+1];
      pcShader[lFileSize]='\0';
      if (lFileSize!=fread(pcShader,sizeof(char),lFileSize,fptr)) {
        fclose(fptr);
        delete[] pcShader;
        T_ERROR("Error reading file %s.",ShaderDesc);
        return 0;
      }
      fclose(fptr);
      break;
    case GLSLPROGRAM_STRING:
      pcShader=(char*)ShaderDesc;
      lFileSize=long(strlen(pcShader));
      break;
    default:
      T_ERROR("Unknown source");
      return 0;
      break;
  }

  GLuint hShader = 0;
  bool bError=false;
  if (m_bGLUseARB) {
    hShader = glCreateShaderObjectARB(Type);
    glShaderSourceARB(hShader,1,(const GLchar**)&pcShader,NULL); // upload null-terminated shader
    glCompileShaderARB(hShader);

    // Check for errors
    if (CheckGLError("LoadProgram()")) {
      glDeleteObjectARB(hShader);
      bError =true;
    }
  } else {
    hShader = glCreateShader(Type);
    glShaderSource(hShader,1,(const char**)&pcShader,NULL);  // upload null-terminated shader
    glCompileShader(hShader);

    // Check for compile status
    GLint iCompiled;
    glGetShaderiv(hShader,GL_COMPILE_STATUS,&iCompiled);

    // Check for errors
    if (WriteInfoLog(ShaderDesc, hShader,false)) {
      glDeleteShader(hShader);
      bError=true;
    }

    if (CheckGLError("LoadProgram()") || iCompiled!=GLint(GL_TRUE)) {
      glDeleteShader(hShader);
      bError=true;
    }
  }

  if (pcShader!=ShaderDesc) delete[] pcShader;

  if (bError) return 0;
  return hShader;
}
Пример #30
0
bool AnalyzeConverter::ConvertToRAW(const std::string& strSourceFilename,
                                    const std::string&,
                                    bool,
                                    uint64_t& iHeaderSkip,
                                    unsigned& iComponentSize,
                                    uint64_t& iComponentCount,
                                    bool& bConvertEndianness,
                                    bool& bSigned, bool& bIsFloat,
                                    UINT64VECTOR3& vVolumeSize,
                                    FLOATVECTOR3& vVolumeAspect,
                                    std::string& strTitle,
                                    std::string& strIntermediateFile,
                                    bool& bDeleteIntermediateFile)
{
  strTitle = "from analyze converter";

  std::ifstream analyze(strSourceFilename.c_str(), std::ios::binary);
  if(!analyze) {
    T_ERROR("Could not open %s!", strSourceFilename.c_str());
    return false;
  }
  struct analyze_hdr hdr;

  analyze.read(reinterpret_cast<char*>(&hdr.hdr_size), 4);
  analyze.read(hdr.data_type, 10);
  analyze.read(hdr.db_name, 18);
  analyze.read(reinterpret_cast<char*>(&hdr.extents), 4);
  analyze.read(reinterpret_cast<char*>(&hdr.session_err), 2);
  analyze.read(&hdr.regular, 1);
  analyze.read(&hdr.hkey_un0, 1);
  short num_dimensions;
  analyze.read(reinterpret_cast<char*>(&num_dimensions), 2);
  if(num_dimensions <= 2) {
    T_ERROR("%dd data; must have at least 3 dimensions!");
    return false;
  }
  for(size_t i=0; i < 7; ++i) {
    analyze.read(reinterpret_cast<char*>(&hdr.dim[i]), 2);
  }
  // 14 bytes of unused garbage.
  analyze.seekg(14, std::ios_base::cur);
  analyze.read(reinterpret_cast<char*>(&hdr.datatype), 2); // DT_xxx ..
  analyze.read(reinterpret_cast<char*>(&hdr.bpp), 2);
  analyze.seekg(2, std::ios_base::cur); // "dim_un0", unused.
  float num_aspect;
  analyze.read(reinterpret_cast<char*>(&num_aspect), 4);
  analyze.read(reinterpret_cast<char*>(&hdr.aspect[0]), 4);
  analyze.read(reinterpret_cast<char*>(&hdr.aspect[1]), 4);
  analyze.read(reinterpret_cast<char*>(&hdr.aspect[2]), 4);
  analyze.seekg(12, std::ios_base::cur); // 4 unused aspect values
  // 'voxel_offset' really is a float that stores a byte offset.  Seriously.
  // Maybe some of the same people that wrote DICOM made Analyze as well.
  analyze.read(reinterpret_cast<char*>(&hdr.voxel_offset), 4);

  // The header size was meant to be used in case the analyze format
  // was extended.  It never was.  Thus the headers are always 348
  // bytes.  This provides a convenient check for endianness; if the
  // size isn't 348, then we need to endian convert everything.
  bConvertEndianness = false;
  if(hdr.hdr_size != 348) {
    MESSAGE("Endianness is wrong, swapping...");
    bConvertEndianness = true;
    hdr.bpp = EndianConvert::Swap<short>(hdr.bpp);
    hdr.dim[0] = EndianConvert::Swap<short>(hdr.dim[0]);
    hdr.dim[1] = EndianConvert::Swap<short>(hdr.dim[1]);
    hdr.dim[2] = EndianConvert::Swap<short>(hdr.dim[2]);
    hdr.aspect[0] = EndianConvert::Swap<float>(hdr.aspect[0]);
    hdr.aspect[1] = EndianConvert::Swap<float>(hdr.aspect[1]);
    hdr.aspect[2] = EndianConvert::Swap<float>(hdr.aspect[2]);
    hdr.voxel_offset = EndianConvert::Swap<float>(hdr.voxel_offset);
    hdr.datatype = EndianConvert::Swap<short>(hdr.datatype);
  }

  iComponentCount = 1; // always, I guess?
  iComponentSize = hdr.bpp;
  vVolumeSize = UINT64VECTOR3(hdr.dim[0], hdr.dim[1], hdr.dim[2]);
  vVolumeAspect = FLOATVECTOR3(hdr.aspect[0], hdr.aspect[1], hdr.aspect[2]);
  MESSAGE("%gx%gx%g aspect ratio", vVolumeAspect[0], vVolumeAspect[1],
          vVolumeAspect[2]);
  MESSAGE("%llu-bit %llux%llux%llu data.", iComponentSize,
          vVolumeSize[0], vVolumeSize[1], vVolumeSize[2]);
  {
    uint64_t bits=0;
    switch(hdr.datatype) {
      case DT_BINARY:        bits =  1;
                             bSigned = false;
                             bIsFloat = false;
                             MESSAGE("binary");
                             break;
      case DT_UNSIGNED_CHAR: bits =  8;
                             bSigned = false;
                             bIsFloat = false;
                             MESSAGE("uchar");
                             break;
      case DT_SIGNED_SHORT:  bits = 16;
                             bSigned = true;
                             bIsFloat = false;
                             MESSAGE("signed short");
                             break;
      case DT_SIGNED_INT:    bits = 32;
                             bSigned = true;
                             bIsFloat = false;
                             MESSAGE("int");
                             break;
      case DT_FLOAT:         bits = 32;
                             bSigned = true;
                             bIsFloat = true;
                             MESSAGE("float");
                             break;
      case DT_COMPLEX:
        T_ERROR("Don't know how to handle complex data.");
        return false;
        break;
      case DT_DOUBLE:        bits = 64;
                             bSigned = true;
                             bIsFloat = true;
                             MESSAGE("double");
                             break;
      default:
        WARNING("Unknown data type.");
        bits = 0;
        break;
    }
    if(iComponentSize != bits) {
      T_ERROR("Bits per pixel and data type disagree!  Broken file?");
      analyze.close();
      return false;
    }
  }

  // If the voxel offset is negative, then there is padding between every slice
  // in the data set.  We would need to write an intermediate file to handle
  // that; instead, we just don't handle it.
  if(hdr.voxel_offset < 0.0) {
    analyze.close();
    T_ERROR("Analyze voxel offset is negative (%g).  Intermediate file "
            "required; this converter is broken.");
    return false;
  }
  iHeaderSkip = static_cast<uint64_t>(hdr.voxel_offset);
  MESSAGE("Skipping %llu bytes.", iHeaderSkip);

  strIntermediateFile = SysTools::RemoveExt(strSourceFilename) + ".img";
  MESSAGE("Using intermediate file %s", strIntermediateFile.c_str());
  bDeleteIntermediateFile = false;

  return true;
}