bool StateRoom::parsePacket(LockVector<IBuffer *> &vector, LockVector<IBuffer *>::iterator &it) { char packet_type; IBuffer *buffer; std::string msg; buffer = *it; buffer->rewind(); *buffer >> packet_type; if (packet_type == INetworkRelay::CHANGE_ROOM_QUERY_YES || packet_type == INetworkRelay::CHANGE_ROOM_QUERY_NON) { if (packet_type == INetworkRelay::CHANGE_ROOM_QUERY_YES) { return true; } else { *buffer >> msg; throw RTException(msg); } it = vector.erase(it); return true; } else ++it;
int luaGetBuffer(lua_State *l) { const char *name = lua_tostring(l, -4); size_t offset = (size_t)lua_tointeger(l, -3); const char *dataType = lua_tostring(l, -2); Enums::DataType dt = Enums::getType(dataType); int card = Enums::getCardinality(dt); Enums::DataType bdt = Enums::getBasicType(dt); IBuffer *buff = RESOURCEMANAGER->getBuffer(name); if (buff == NULL) { NAU_THROW("Lua getBuffer: invalid buffer: %s", name); return 0; } int size = Enums::getSize(dt); void *arr = malloc(size); size_t count = buff->getData(offset, size , arr); if (size != count) { NAU_THROW("Lua getBuffer: buffer %s offset %d, out of bounds", name, (unsigned int)offset); return 0; } luaGetValues(l, arr, card, bdt); return 0; }
void GLIndexArray::compile() { m_IsCompiled = true; if (0 != m_InternalIndexArray && m_InternalIndexArray->size() != 0) { std::shared_ptr<std::vector<unsigned int>> pArray; if (m_UseAdjacency) { buildAdjacencyList(); pArray = m_AdjIndexArray; } else pArray = m_InternalIndexArray; IBuffer *b = NULL; if (m_GLBuffer == 0) { b = RESOURCEMANAGER->createBuffer(m_Name); b->setStructure(std::vector < Enums::DataType > {Enums::UINT}); m_GLBuffer = b->getPropi(IBuffer::ID); } else { b = RESOURCEMANAGER->getBuffer(m_Name); } b->setData(pArray->size() * sizeof(unsigned int), &(*pArray)[0]); //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_GLBuffer); //glBufferData(GL_ELEMENT_ARRAY_BUFFER, pArray->size() * sizeof(unsigned int), &(*pArray)[0], GL_STATIC_DRAW); //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //b->setPropui(IBuffer::SIZE, pArray->size() * sizeof(unsigned int)); } }
bool GLVertexArray::compile (void) { if (m_IsCompiled) return false; m_IsCompiled = true; for (int i = 0; i < VertexData::MaxAttribs; i++){ if (0 != m_InternalArrays[i] && m_InternalArrays[i]->size() != 0){ std::shared_ptr<std::vector<VertexData::Attr>> &pArray = m_InternalArrays[i]; IBuffer *b = NULL; std::string s = m_Name + ":" + VertexData::Syntax[i]; if (m_GLBuffers[i] == 0) { b = RESOURCEMANAGER->createBuffer(s); b->setStructure(std::vector < Enums::DataType > {Enums::FLOAT, Enums::FLOAT, Enums::FLOAT, Enums::FLOAT}); m_GLBuffers[i] = b->getPropi(IBuffer::ID); } else { b = RESOURCEMANAGER->getBuffer(s); } b->setData(pArray->size() * 4 * sizeof(float), (float*)&(*pArray)[0]); } } return true; }
int luaSetBuffer(lua_State *l) { const char *name = lua_tostring(l, -4); size_t offset = (size_t)lua_tointeger(l, -3); const char *dataType = lua_tostring(l, -2); Enums::DataType dt = Enums::getType(dataType); int card = Enums::getCardinality(dt); Enums::DataType bdt = Enums::getBasicType(dt); int size = Enums::getSize(dt); IBuffer *buff = RESOURCEMANAGER->getBuffer(name); if (buff == NULL) { NAU_THROW("Lua getBuffer: invalid buffer: %s", name); return 0; } void *arr = NULL; float *arrF; int *arrI; unsigned int *arrUI; switch (bdt) { case Enums::FLOAT: arrF = (float *)malloc(sizeof(float) * card); lua_pushnil(l); for (int i = 0; i < card && lua_next(l,-2) != 0; ++i) { arrF[i] = (float)lua_tonumber(l, -1); lua_pop(l, 1); } arr = arrF; break; case Enums::INT: case Enums::BOOL: arrI = (int *)malloc(sizeof(int) * card); lua_pushnil(l); for (int i = 0; i < card && lua_next(l, -2) != 0; ++i) { arrI[i] = (int)lua_tointeger(l, -1); lua_pop(l, 1); } arr = arrI; break; case Enums::UINT : arrUI = (unsigned int *)malloc(sizeof(unsigned int) * card); lua_pushnil(l); for (int i = 0; i < card && lua_next(l, -2) != 0; ++i) { arrUI[i] = (unsigned int)lua_tointeger(l, -1); lua_pop(l, 1); } arr = arrUI; break; } buff->setSubData(offset, size, arr); return 0; }
/* * Return the length of the sound in ms */ uint32 CSimpleSound::getDuration() { IBuffer* buffer = getBuffer(); if ( buffer == NULL ) { return 0; } else { return (uint32)(buffer->getDuration()); } }
void initIons(IBuffer& ions, uint32_t currentStep) { //copy electrons' values to ions EBuffer &e_buffer = Environment<>::get().DataConnector().getData<EBuffer>(EBuffer::FrameType::getName()); ions.deviceCloneFrom(e_buffer); // must be called to overwrite cloned electron momenta, // so even for gamma=1.0 ions.deviceSetDrift(currentStep); if (ION_TEMPERATURE > float_X(0.0)) ions.deviceAddTemperature(ION_TEMPERATURE); }
bool CSampleBank::unload() { vector<IBuffer*> vec; TSampleTable::iterator it; if (!_Loaded) { nlwarning("Trying to unload an already unloaded bank : %s", CStringMapper::unmap(_Name).c_str ()); return true; } // need to wait end of load ? if (!_LoadingDone) return false; //nlinfo("Unloading sample bank %s", CStringMapper::unmap(_Name).c_str()); for (it = _Samples.begin(); it != _Samples.end(); ++it) { IBuffer *buffer = it->second; if (buffer) { const NLMISC::TStringId & bufferName = buffer->getName(); CAudioMixerUser *audioMixer = _SampleBankManager->m_AudioMixer; // Warn the mixer to stop any track playing this buffer. audioMixer->bufferUnloaded(buffer); // Warn the sound banks about this buffer. audioMixer->getSoundBank()->bufferUnloaded(bufferName); // delete it->second = NULL; delete buffer; } } _Loaded = false; _SampleBankManager->m_LoadedSize -= _ByteSize; _ByteSize = 0; return true; }
/// Notify that you are done writing to the locked buffer, so it can be copied over to hardware if needed. Set size to the number of bytes actually written to the buffer. Returns true if ok. bool CStreamSource::unlock(uint size) { nlassert(m_FreeBuffers > 0); CAutoMutex<CMutex> autoMutex(m_BufferMutex); IBuffer *buffer = m_Buffers[m_NextBuffer]; bool result = buffer->unlock(size); if (size > 0) { ++m_NextBuffer; m_NextBuffer %= 3; --m_FreeBuffers; if (hasPhysicalSource()) getPhysicalSource()->submitStreamingBuffer(buffer); m_LastSize = size; } return result; }
void CPlaneCallback::FillMeshData(Engine::Graphics::IMesh *pMesh) { // Declaration SVertexElement elems[4]; elems[0] = SVertexElement(0, ETYPE_FLOAT3, USG_POSITION, 0); elems[1] = SVertexElement(sizeof(float) * 3, ETYPE_FLOAT3, USG_NORMAL, 0); elems[2] = SVertexElement(sizeof(float) * 6, ETYPE_FLOAT2, USG_TEXCOORD, 0); elems[3] = END_DECLARATION(); pMesh->SetVertexDeclaration(elems); pMesh->setPrimitiveType(PT_TRIANGLE_STRIP); float x = m_x * 0.5f; float y = m_y * 0.5f; // Data const int n_verts = 4; struct Vert { float data[8]; }; Vert v[] = { { -x, 0, y, 0, 1, 0, 0, 0 }, { x, 0, y, 0, 1, 0, 1, 0 }, { -x, 0, -y, 0, 1, 0, 0, 1 }, { x, 0, -y, 0, 1, 0, 1, 1 }, }; IBuffer *vb = pMesh->GetVertexBuffer(); vb->Resize(sizeof(Vert) * n_verts); void *pData; vb->Lock(&pData, LOCK_DISCARD); memcpy(pData, v, sizeof(Vert) * n_verts); vb->Unlock(); // Subset IGeometry::TInterval vi(0, n_verts); IGeometry::TInterval ii(0, 0); pMesh->AddSubset(vi, ii); SBoundingVolume bv(VML::Vector3(-x, 0, -y), VML::Vector3(x, 0.001f, y)); pMesh->SetBoundingVolume(bv); }
// // Unlock event. Records the index buffer in the associated handle either by creating // a new index buffer or modifying the existing one. // void StateManager::LockIBuffer(BufferLockData &Data, D3DINDEXBUFFER_DESC &Desc) { IBufferMap::iterator Iterator = IBuffers.find(Data.Handle); if(Iterator == IBuffers.end()) { if(!Data.Create) { g_Context->Files.Assert << "IBuffer lock called before create\n"; } IBuffer *NewBuffer = new IBuffer(Data.Handle); NewBuffer->Update(Data, Desc); IBuffers[Data.Handle] = NewBuffer; } else { if(Data.Create) { //g_Context->Files.Assert << "IBuffer reused\n"; } //Assert(!Data.Create, "Create called twice on IBuffer"); Iterator->second->Update(Data, Desc); } }
void DlgDbgBuffers::setBufferList(){ std::vector<std::string> names; IBuffer *b; wxPGProperty *pid, *appended; std::string indexName, shortName, fullName; pgBuffers->ClearPage(0); bufferSettingsList.clear(); currentBuffer = NO_BUFFER; RESOURCEMANAGER->getBufferNames(&names); for (auto name : names) { fullName = name; shortName = File::GetName(name); if (m_UseShortNames) indexName = shortName; else indexName = fullName; b = RESOURCEMANAGER->getBuffer(name); b->refreshBufferParameters(); std::vector<Enums::DataType> structure = b->getStructure(); bufferSettingsList[indexName] = BufferSettings(); if (structure.size() == 0) bufferSettingsList[indexName].types.push_back(Enums::FLOAT); else bufferSettingsList[indexName].types = b->getStructure(); bufferSettingsList[indexName].lines = 16; bufferSettingsList[indexName].currentPage = 0; bufferSettingsList[indexName].ID = b->getPropi(IBuffer::ID); bufferSettingsList[indexName].size = b->getPropui(IBuffer::SIZE); bufferSettingsList[indexName].bufferPtr = b; bufferSettingsList[indexName].fullName = fullName; bufferSettingsList[indexName].shortName = shortName; int s = 0; for (auto t : bufferSettingsList[indexName].types) { s += Enums::getSize(t); } bufferSettingsList[indexName].lineSize = s; int totalLines = bufferSettingsList[indexName].size / s; if (bufferSettingsList[indexName].size % s != 0) totalLines++; int totalPages = totalLines / (bufferSettingsList[indexName].lines); if (totalLines % bufferSettingsList[indexName].lines != 0) totalPages++; pid = pgBuffers->Append(new wxStringProperty(wxT("" + indexName), wxPG_LABEL,"<composed>")); appended = pgBuffers->AppendIn(pid, new wxIntProperty(wxT("ID"), wxPG_LABEL, bufferSettingsList[indexName].ID)); appended->Enable(false); appended = pgBuffers->AppendIn(pid, new wxIntProperty(wxT("Size (bytes)"), wxPG_LABEL, bufferSettingsList[indexName].size)); appended->Enable(false); appended = pgBuffers->AppendIn(pid, new wxIntProperty(wxT("Total pages"), wxPG_LABEL, totalPages)); appended->Enable(false); appended = pgBuffers->AppendIn(pid, new wxIntProperty(wxT("Total lines"), wxPG_LABEL, totalLines)); appended->Enable(false); appended = pgBuffers->AppendIn(pid, new wxIntProperty(wxT("Components"), wxPG_LABEL, bufferSettingsList[indexName].types.size())); appended->Enable(false); } if (bufferSettingsList.size() > 0) currentBuffer = m_UseShortNames ? File::GetName(names[0]):indexName; pgBuffers->CollapseAll(); }
void DlgDbgBuffers::setVAOList(void) { VAOInfoList list; // ((VAO index, (Element index, Element name)) , vector(Array index, Array Name)) VAOInfo vao; int id, count, enabled; std::string label; pgVAOs->ClearPage(0); //#ifdef GLINTERCEPTDEBUG // gliSetIsGLIActive(false); //#endif // ugly but practical :-) for (int i = 0; i < 65536; ++i) { if ((bool)glIsVertexArray(i)) { vao.first.first = i; glBindVertexArray(i); // get element array buffer name glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &id); if (id) { vao.first.second.first = id; label = RESOURCEMANAGER->getBufferByID(id)->getLabel(); if (m_UseShortNames) name = File::GetName(label); else name = label; vao.first.second.second = name; } else { vao.first.second.first = 0; } vao.second.clear(); // get info for each attrib mapped buffer glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &count); for (int k = 0; k < count; ++k) { glGetVertexAttribiv(k, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &enabled); if (enabled) { glGetVertexAttribiv(k, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, &id); IBuffer *b = RESOURCEMANAGER->getBufferByID(id); if (b) { label = b->getLabel(); if (m_UseShortNames) name = File::GetName(label); else name = label; vao.second.push_back(std::pair<int, std::string>(id, name)); } } } list.push_back(vao); } } //#ifdef GLINTERCEPTDEBUG // gliSetIsGLIActive(true); //#endif for (auto info : list) { wxPGProperty *pid; wxPGProperty *element, *buffers; pid = pgVAOs->Append(new wxPGProperty(wxT("VAO " + std::to_string(info.first.first)), wxPG_LABEL)); // Add index buffer if (info.first.second.first != 0) { element = pgVAOs->AppendIn(pid, new wxPGProperty(wxT("Index Array"), wxPG_LABEL)); pgVAOs->AppendIn(element, new wxStringProperty(wxT("ID " + std::to_string(info.first.second.first)), wxPG_LABEL, wxT(" " + info.first.second.second))); } // Add Vertex Attributes buffers = pgVAOs->AppendIn(pid, new wxPGProperty(wxT("Attribute Arrays"), wxPG_LABEL)); for (auto buf : info.second) { pgVAOs->AppendIn(buffers, new wxStringProperty(wxT("ID " + std::to_string(buf.first)), wxPG_LABEL, wxT(" " + buf.second))); } } pgVAOs->CollapseAll(); }
void PhysicsManager::update() { if (!m_PhysInst) return; m_PhysInst->update(); float *t; std::vector<std::shared_ptr<SceneObject>> so; for (auto s : m_Scenes) { int st = getMaterial(s.second).getPrope(PhysicsMaterial::SCENE_TYPE); switch (st) { case IPhysics::STATIC: break; case IPhysics::RIGID: t = m_PhysInst->getSceneTransform(s.first->getName()); s.first->setTransform(math::mat4(t)); break; case IPhysics::CLOTH: t = m_PhysInst->getSceneTransform(s.first->getName()); s.first->setTransform(math::mat4(t)); s.first->getAllObjects(&so); for (auto &o : so) { o->getRenderable()->getVertexData()->resetCompilationFlag(); o->getRenderable()->getVertexData()->compile(); } break; case IPhysics::CHARACTER: t = m_PhysInst->getSceneTransform(s.first->getName()); s.first->setTransform(math::mat4(t)); break; case IPhysics::PARTICLES: { std::string &sceneName = s.first->getName(); PhysicsMaterial &pm = getMaterial(s.second); int nPart = static_cast<int>(pm.getPropf((FloatProperty)pm.getAttribSet()->getAttributes()["NBPARTICLES"]->getId())); std::string bufferName = pm.getProps((StringProperty)pm.getAttribSet()->getAttributes()["BUFFER"]->getId()); IBuffer * pointsBuffer = RESOURCEMANAGER->getBuffer(bufferName); pointsBuffer->setSubData(0, nPart * 4 * sizeof(float), pm.getBuffer()); RENDERMANAGER->getCurrentPass()->setPropui(Pass::INSTANCE_COUNT, nPart); } break; case IPhysics::DEBUG: { IBuffer * b = RESOURCEMANAGER->getBufferByID(s.first->getSceneObject(0)->getRenderable()->getVertexData()->getBufferID(VertexData::GetAttribIndex(std::string("position")))); std::vector<float> * debugPos = m_PhysInst->getDebug(); b->setData(debugPos->size() * sizeof(float), &debugPos->at(0)); s.first->getAllObjects(&so); for (auto &o : so) { o->getRenderable()->getVertexData()->resetCompilationFlag(); o->getRenderable()->getVertexData()->compile(); } } break; } } for (auto cam : *(m_PhysInst->getCameraPositions())) { Camera * camera = RENDERMANAGER->getCamera(cam.first).get(); vec4 previous = camera->getPropf4(Camera::POSITION); vec4 current = vec4(cam.second[0], cam.second[1], cam.second[2], 1.0f); if (current != previous) camera->setPropf4(Camera::POSITION, current); } }
void CBoxCallback::FillMeshData(Engine::Graphics::IMesh *pMesh) { // Declaration SVertexElement elems[4]; elems[0] = SVertexElement(0, ETYPE_FLOAT3, USG_POSITION, 0); elems[1] = SVertexElement(sizeof(float) * 3, ETYPE_FLOAT3, USG_NORMAL, 0); elems[2] = SVertexElement(sizeof(float) * 6, ETYPE_FLOAT2, USG_TEXCOORD, 0); elems[3] = END_DECLARATION(); pMesh->SetVertexDeclaration(elems); pMesh->setPrimitiveType(PT_INDEXED_TRIANGLE_LIST); // Data const int n_verts = 36; struct Vert { float data[8]; }; Vert v[] = { { mA[0], mB[1], mA[2], 0, 1, 0 , 0, 1 }, { mA[0], mB[1], mB[2], 0, 1, 0 , 0, 0 }, { mB[0], mB[1], mB[2], 0, 1, 0 , 1, 0 }, { mB[0], mB[1], mB[2], 0, 1, 0 , 1, 0 }, { mB[0], mB[1], mA[2], 0, 1, 0 , 1, 1 }, { mA[0], mB[1], mA[2], 0, 1, 0 , 0, 1 }, { mA[0], mA[1], mA[2], 0, 0, -1 , 0, 1 }, { mA[0], mB[1], mA[2], 0, 0, -1 , 0, 0 }, { mB[0], mB[1], mA[2], 0, 0, -1 , 1, 0 }, { mB[0], mB[1], mA[2], 0, 0, -1 , 1, 0 }, { mB[0], mA[1], mA[2], 0, 0, -1 , 1, 1 }, { mA[0], mA[1], mA[2], 0, 0, -1 , 0, 1 }, { mA[0], mA[1], mB[2], -1, 0, 0 , 0, 1 }, { mA[0], mB[1], mB[2], -1, 0, 0 , 0, 0 }, { mA[0], mB[1], mA[2], -1, 0, 0 , 1, 0 }, { mA[0], mB[1], mA[2], -1, 0, 0 , 1, 0 }, { mA[0], mA[1], mA[2], -1, 0, 0 , 1, 1 }, { mA[0], mA[1], mB[2], -1, 0, 0 , 0, 1 }, { mA[0], mB[1], mB[2], 0, 0, 1 , 1, 0 }, { mA[0], mA[1], mB[2], 0, 0, 1 , 1, 1 }, { mB[0], mA[1], mB[2], 0, 0, 1 , 0, 1 }, { mB[0], mA[1], mB[2], 0, 0, 1 , 0, 1 }, { mB[0], mB[1], mB[2], 0, 0, 1 , 0, 0 }, { mA[0], mB[1], mB[2], 0, 0, 1 , 1, 0 }, { mB[0], mA[1], mA[2], 1, 0, 0 , 0, 1 }, { mB[0], mB[1], mA[2], 1, 0, 0 , 0, 0 }, { mB[0], mB[1], mB[2], 1, 0, 0 , 1, 0 }, { mB[0], mB[1], mB[2], 1, 0, 0 , 1, 0 }, { mB[0], mA[1], mB[2], 1, 0, 0 , 1, 1 }, { mB[0], mA[1], mA[2], 1, 0, 0 , 0, 1 }, { mA[0], mA[1], mB[2], 0, -1, 0 , 0, 1 }, { mA[0], mA[1], mA[2], 0, -1, 0 , 0, 0 }, { mB[0], mA[1], mA[2], 0, -1, 0 , 1, 0 }, { mB[0], mA[1], mA[2], 0, -1, 0 , 1, 0 }, { mB[0], mA[1], mB[2], 0, -1, 0 , 1, 1 }, { mA[0], mA[1], mB[2], 0, -1, 0 , 0, 1 }, }; int i[] = { 0,1,2, 3,4,5, 6,7,8, 9,10,11, 12,13,14, 15,16,17, 18,19,20, 21,22,23, 24,25,26, 27,28,29, 30,31,32, 33,34,35, }; IBuffer *vb = pMesh->GetVertexBuffer(); vb->Resize(sizeof(Vert) * n_verts); void *pData; vb->Lock(&pData, LOCK_DISCARD); memcpy(pData, v, sizeof(Vert) * n_verts); vb->Unlock(); IBuffer *ib = pMesh->GetIndexBuffer(); ib->Resize(sizeof(int) * n_verts); ib->Lock(&pData, LOCK_DISCARD); memcpy(pData, i, sizeof(int) * n_verts); ib->Unlock(); // Subset IGeometry::TInterval vi(0, n_verts); IGeometry::TInterval ii(0, n_verts); pMesh->AddSubset(vi, ii); VML::Vector3 vmin(mA[0], mA[1], mA[2]); VML::Vector3 vmax(mB[0], mB[1], mB[2]); SBoundingVolume bv(vmin, vmax); pMesh->SetBoundingVolume(bv); }
void CSphereCallback::FillMeshData(Engine::Graphics::IMesh *pMesh) { // Declaration SVertexElement elems[4]; elems[0] = SVertexElement(0, ETYPE_FLOAT3, USG_POSITION, 0); elems[1] = SVertexElement(sizeof(float) * 3, ETYPE_FLOAT3, USG_NORMAL, 0); elems[2] = SVertexElement(sizeof(float) * 6, ETYPE_FLOAT2, USG_TEXCOORD, 0); elems[3] = END_DECLARATION(); pMesh->SetVertexDeclaration(elems); pMesh->setPrimitiveType(PT_INDEXED_TRIANGLE_LIST); // Data const int n_verts = (mRings + 1) * (mSegments + 1); const int n_indcs = 6 * mRings * (mSegments + 1); void *vertices, *indices; IBuffer* vb = pMesh->GetVertexBuffer(); IBuffer* ib = pMesh->GetIndexBuffer(); vb->Resize(n_verts * sizeof(float) * 8); ib->Resize(n_indcs * sizeof(int)); vb->Lock(&vertices, LOCK_DISCARD); ib->Lock(&indices, LOCK_DISCARD); const float PI = 3.1415926f; float fDeltaRingAngle = (PI / mRings); float fDeltaSegAngle = (2.0f * PI / mSegments); unsigned short wVerticeIndex = 0 ; float* pVertex = (float*)vertices; int* pIndices = (int*)indices; // Generate the group of rings for the sphere for(int ring = 0; ring <= mRings; ring++) { float r0 = mRadius * sinf (ring * fDeltaRingAngle); float y0 = mRadius * cosf (ring * fDeltaRingAngle); // Generate the group of segments for the current ring for(int seg = 0; seg <= mSegments; seg++) { float x0 = r0 * sinf(seg * fDeltaSegAngle); float z0 = r0 * cosf(seg * fDeltaSegAngle); // Position *pVertex++ = x0; *pVertex++ = y0; *pVertex++ = z0; // Normal VML::Vector3 vNormal(x0, y0, z0); vNormal.normalize(); *pVertex++ = vNormal.getX(); *pVertex++ = vNormal.getY(); *pVertex++ = vNormal.getZ(); // Texture coordinates *pVertex++ = 1.0f - (float) seg / (float) mSegments; *pVertex++ = (float) ring / (float) mRings; if (ring != mRings) { // each vertex (except the last) has six indices pointing to it *pIndices++ = wVerticeIndex + mSegments + 1; *pIndices++ = wVerticeIndex; *pIndices++ = wVerticeIndex + mSegments; *pIndices++ = wVerticeIndex + mSegments + 1; *pIndices++ = wVerticeIndex + 1; *pIndices++ = wVerticeIndex; wVerticeIndex ++; } } // end for seg } // end for ring vb->Unlock(); ib->Unlock(); // Subset IGeometry::TInterval vi(0, n_verts); IGeometry::TInterval ii(0, n_indcs); pMesh->AddSubset(vi, ii); SBoundingVolume bv(VML::Vector3(0), mRadius); pMesh->SetBoundingVolume(bv); }
void PassOptixPrime::initOptixPrime() { // Create Context CHK_PRIME(rtpContextCreate(RTP_CONTEXT_TYPE_CUDA, &m_Context)); // Create Vertex Buffer std::shared_ptr<IRenderable> &renderable = RENDERMANAGER->getScene(m_SceneVector[0])->getSceneObject(0)->getRenderable(); int vbo = renderable->getVertexData()->getBufferID(0); int numVert = renderable->getVertexData()->getNumberOfVertices(); //std::shared_ptr<std::vector<VertexAttrib>> &vertex = renderable->getVertexData()->getDataOf(0); size_t size; void * devPtr; int k = cudaGraphicsGLRegisterBuffer(&cgl, vbo, cudaGraphicsRegisterFlagsReadOnly); k = cudaGraphicsMapResources(1, &cgl, 0); k = cudaGraphicsResourceGetMappedPointer((void **)&devPtr, &size, cgl); CHK_PRIME(rtpBufferDescCreate( m_Context, RTP_BUFFER_FORMAT_VERTEX_FLOAT4, RTP_BUFFER_TYPE_CUDA_LINEAR, devPtr, &m_VerticesDesc) ); CHK_PRIME(rtpBufferDescSetRange(m_VerticesDesc, 0, numVert)); // Create Index Buffer std::shared_ptr<IndexData> &ind = renderable->getIndexData(); std::vector<int> v; ind->getIndexDataAsInt(&v); GLuint index; IBuffer *b; b = RESOURCEMANAGER->createBuffer(m_Name); index = b->getPropi(IBuffer::ID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index); glBufferData(GL_ELEMENT_ARRAY_BUFFER, v.size() * sizeof(int), &(v)[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); int numInd = (int)v.size(); void * devPtrInd; k = cudaGraphicsGLRegisterBuffer(&cglInd, index, cudaGraphicsRegisterFlagsReadOnly); k = cudaGraphicsMapResources(1, &cglInd, 0); k = cudaGraphicsResourceGetMappedPointer((void **)&devPtrInd, &size, cglInd); CHK_PRIME(rtpBufferDescCreate( m_Context, RTP_BUFFER_FORMAT_INDICES_INT3, RTP_BUFFER_TYPE_CUDA_LINEAR, devPtrInd, &m_IndicesDesc) ); CHK_PRIME(rtpBufferDescSetRange(m_IndicesDesc, 0, numInd/3)); // Create Model CHK_PRIME(rtpModelCreate(m_Context, &m_Model)); CHK_PRIME(rtpModelSetTriangles(m_Model, m_IndicesDesc, m_VerticesDesc)); int useCallerTris = 0; CHK_PRIME(rtpModelSetBuilderParameter(m_Model, RTP_BUILDER_PARAM_USE_CALLER_TRIANGLES, sizeof(int), &useCallerTris)); CHK_PRIME(rtpModelUpdate(m_Model, 0)); CHK_PRIME(rtpModelFinish(m_Model)); cudaGraphicsUnmapResources(1, &cgl, 0); // Create Rays Buffer int rayBufferID = m_Rays->getPropi(IBuffer::ID); int rayBufferRayCount = m_Rays->getPropui(IBuffer::SIZE) / (8 * sizeof(float)); void * devPtrBuff; k = cudaGraphicsGLRegisterBuffer(&cglBuff, rayBufferID, cudaGraphicsRegisterFlagsReadOnly); k = cudaGraphicsMapResources(1, &cglBuff, 0); k = cudaGraphicsResourceGetMappedPointer((void **)&devPtrBuff, &size, cglBuff); CHK_PRIME(rtpBufferDescCreate( m_Context, RTP_BUFFER_FORMAT_RAY_ORIGIN_TMIN_DIRECTION_TMAX, RTP_BUFFER_TYPE_CUDA_LINEAR, devPtrBuff, &m_RaysDesc) ); CHK_PRIME(rtpBufferDescSetRange(m_RaysDesc, 0, rayBufferRayCount)); // Create Hits Buffer int hitBufferID = m_Hits->getPropi(IBuffer::ID); void * devPtrBuffH; k = cudaGraphicsGLRegisterBuffer(&cglBuffH, hitBufferID, cudaGraphicsRegisterFlagsWriteDiscard); k = cudaGraphicsMapResources(1, &cglBuffH, 0); k = cudaGraphicsResourceGetMappedPointer((void **)&devPtrBuffH, &size, cglBuffH); CHK_PRIME(rtpBufferDescCreate( m_Context, RTP_BUFFER_FORMAT_HIT_T_TRIID_U_V, RTP_BUFFER_TYPE_CUDA_LINEAR, devPtrBuffH, &m_HitsDesc) ); CHK_PRIME(rtpBufferDescSetRange(m_HitsDesc, 0, rayBufferRayCount)); // Prepare query CHK_PRIME(rtpQueryCreate(m_Model, m_QueryType, &m_Query)); CHK_PRIME(rtpQuerySetRays(m_Query, m_RaysDesc)); CHK_PRIME(rtpQuerySetHits(m_Query, m_HitsDesc)); m_Init = true; }
void PhysicsManager::addScene(nau::scene::IScene *aScene, const std::string &matName) { if (!m_PhysInst) return; m_Scenes[aScene] = matName; std::string sn = aScene->getName(); PhysicsMaterial &pm = getMaterial(matName); IPhysics::SceneType type = (IPhysics::SceneType)pm.getPrope(PhysicsMaterial::SCENE_TYPE); IPhysics::SceneShape shape = (IPhysics::SceneShape)pm.getPrope(PhysicsMaterial::SCENE_SHAPE); m_PhysInst->setSceneType(sn, type); float * max = new float[3](); float * min = new float[3](); vec3 maxVec = aScene->getBoundingVolume().getMax(); vec3 minVec = aScene->getBoundingVolume().getMin(); max[0] = maxVec.x; max[1] = maxVec.y; max[2] = maxVec.z; min[0] = minVec.x; min[1] = minVec.y; min[2] = minVec.z; m_PhysInst->setSceneShape(sn, shape, min, max); m_PhysInst->setSceneCondition(sn, (IPhysics::SceneCondition)pm.getPrope(PhysicsMaterial::SCENE_CONDITION)); switch (type) { case IPhysics::PARTICLES: { int maxParticles = static_cast<int>(pm.getPropf((FloatProperty)pm.getAttribSet()->getAttributes()["MAX_PARTICLES"]->getId())); pm.setBuffer((float *)malloc(maxParticles * 4 * sizeof(float))); IBuffer * buff = RESOURCEMANAGER->getBuffer(pm.getProps((StringProperty)pm.getAttribSet()->getAttributes()["BUFFER"]->getId())); buff->setData(maxParticles * 4 * sizeof(float), pm.getBuffer()); m_PhysInst->setScene( sn, matName, maxParticles, pm.getBuffer(), 0, NULL, (float *)aScene->getTransform().getMatrix() ); } break; case IPhysics::DEBUG: m_PhysInst->setScene(sn, matName, 0, NULL, 0, NULL, (float *)aScene->getTransform().getMatrix()); break; default: m_PhysInst->setSceneTransform(sn, (float *)aScene->getTransform().getMatrix()); std::shared_ptr<IRenderable> &r = aScene->getSceneObject(0)->getRenderable(); std::vector<VertexAttrib> *vd = r->getVertexData()->getDataOf(0).get(); m_PhysInst->setScene( sn, matName, static_cast<int> (vd->size()), (float *)&(vd->at(0)), static_cast<int> (r->getIndexData()->getIndexData()->size()), (unsigned int *)&(r->getIndexData()->getIndexData()->at(0)), (float *)aScene->getTransform().getMatrix() ); EVENTMANAGER->addListener("SCENE_TRANSFORM", this); break; } std::map<std::string, std::unique_ptr<Attribute>> &attrs = pm.getAttribSet()->getAttributes(); for (auto &a : attrs) { switch (a.second->getType()) { case Enums::FLOAT: m_PhysInst->applyFloatProperty(sn, a.second->getName(), pm.getPropf((FloatProperty)a.second->getId())); break; case Enums::VEC4: m_PhysInst->applyVec4Property(sn, a.second->getName(), &(pm.getPropf4((Float4Property)a.second->getId()).x)); break; } } m_Built = false; }
void teCompressFile(const teString & from, const teString & to, u32 chunkSize, c8 * chunkInputBuffer, u32 chunkInputBufferSize, c8 * chunkOutputBuffer, u32 chunkOutputBufferSize, u1 highCompression, u1 localPath) { TE_ASSERT(chunkInputBufferSize >= chunkSize); TE_ASSERT(chunkOutputBufferSize >= LZ4_compressBound(chunkSize)); teLZ4CompressionFunction compressionFunction = highCompression ? LZ4_compressHC : LZ4_compress; IBuffer * fileInput = GetFileManager()->OpenFile(from, CFileBuffer::FWM_READ, localPath); if(!fileInput) return; IBuffer * fileOutput = GetFileManager()->OpenFile(to, CFileBuffer::FWM_WRITE, localPath); if(!fileOutput) { TE_SAFE_DROP(fileInput); return; } fileInput->SetStreamMode(true); fileOutput->SetStreamMode(true); fileInput->Lock(BLT_READ); fileInput->SetPosition(0); fileOutput->Lock(BLT_WRITE); fileOutput->SetPosition(0); u32 magicNumber = ARCHIVE_MAGICNUMBER; fileOutput->Write(&magicNumber, ARCHIVE_MAGICNUMBER_SIZE); c8 * inBuffer = chunkInputBuffer; c8 * outBuffer = chunkOutputBuffer; u32 fileSize = 0; while(true) { u32 inSize = teMin(chunkSize, fileInput->GetSize() - fileInput->GetPosition()); fileInput->Read(inBuffer, inSize); fileSize += inSize; if(!inSize) break; u32 outSize = compressionFunction(inBuffer, outBuffer + 4, inSize); *(u32*)outBuffer = outSize; fileOutput->Write(outBuffer, outSize + 4); } fileInput->Unlock(); fileOutput->Unlock(); TE_SAFE_DROP(fileInput); TE_SAFE_DROP(fileOutput); }
void teDecodeFile(const teString & from, const teString & to, u32 chunkSize, c8 * chunkInputBuffer, u32 chunkInputBufferSize, c8 * chunkOutputBuffer, u32 chunkOutputBufferSize, u1 localPath) { TE_ASSERT(chunkInputBufferSize >= LZ4_compressBound(chunkSize)); TE_ASSERT(chunkOutputBufferSize >= chunkSize); IBuffer * fileInput = GetFileManager()->OpenFile(from, CFileBuffer::FWM_READ, localPath); if(!fileInput) return; IBuffer * fileOutput = GetFileManager()->OpenFile(to, CFileBuffer::FWM_WRITE, localPath); if(!fileOutput) { TE_SAFE_DROP(fileInput); return; } fileInput->SetStreamMode(true); fileOutput->SetStreamMode(true); fileInput->Lock(BLT_READ); fileInput->SetPosition(0); u32 magicNumber = u32Max; fileInput->Read(&magicNumber, ARCHIVE_MAGICNUMBER_SIZE); TE_ASSERT(magicNumber == ARCHIVE_MAGICNUMBER); fileOutput->Lock(BLT_WRITE); fileOutput->SetPosition(0); c8 * inBuffer = chunkInputBuffer; c8 * outBuffer = chunkOutputBuffer; while(true) { if((fileInput->GetSize() - fileInput->GetPosition()) < ARCHIVE_MAGICNUMBER_SIZE) break; u32 chunkSizeInFile; fileInput->Read(&chunkSizeInFile, sizeof(u32)); if(chunkSizeInFile == ARCHIVE_MAGICNUMBER) continue; fileInput->Read(inBuffer, chunkSizeInFile); s32 outputSize = LZ4_uncompress_unknownOutputSize(inBuffer, outBuffer, chunkSizeInFile, chunkSize); if(outputSize < 0) { TE_LOG_ERR("lz4 decoding failed, corrupted input\n"); fileInput->Unlock(); fileOutput->Unlock(); TE_SAFE_DROP(fileInput); TE_SAFE_DROP(fileOutput); return; } fileOutput->Write(outBuffer, (u32)outputSize); } fileInput->Unlock(); fileOutput->Unlock(); TE_SAFE_DROP(fileInput); TE_SAFE_DROP(fileOutput); }
void DlgDbgBuffers::setBufferData(){ gridBufferValues->ClearGrid(); if (currentBuffer == NO_BUFFER) { return; } int lines = bufferSettingsList[currentBuffer].lines; int page = bufferSettingsList[currentBuffer].currentPage; int lineSize = bufferSettingsList[currentBuffer].lineSize; int columns = bufferSettingsList[currentBuffer].types.size(); void *bufferValues; int pageSize = lineSize * lines; int pageOffset = page * pageSize; bufferValues = malloc(pageSize); IBuffer *b = bufferSettingsList[currentBuffer].bufferPtr; //#ifdef GLINTERCEPTDEBUG // gliSetIsGLIActive(false); //#endif int dataRead = b->getData(pageOffset, pageSize, bufferValues); //#ifdef GLINTERCEPTDEBUG // gliSetIsGLIActive(true); //#endif setSpinners(lines, columns, page, lineSize, bufferSettingsList[currentBuffer].size); int pointerIndex; std::string value; char rowLabel[32]; int k = gridBufferValues->GetNumberRows(); if (k < lines+1) gridBufferValues->AppendRows(lines+1-k); if (k > lines + 1) gridBufferValues->DeleteRows(lines + 1, k - lines - 1); k = gridBufferValues->GetNumberCols(); if ( k < columns) gridBufferValues->AppendCols(columns-k); pointerIndex = 0; for (int col = 0; col < columns; ++col) { Enums::DataType t = bufferSettingsList[currentBuffer].types[col]; std::string s = DataType[t]; gridBufferValues->SetCellValue(0, col, wxT(""+s)); gridBufferValues->ShowCol(col); } for (int col = columns; col < MAX_COLUMNS; ++col) { gridBufferValues->HideCol(col); } for (int row = 0; row < lines; ++row){ sprintf(rowLabel, "%d", row + page*lines); gridBufferValues->SetRowLabelValue(row + 1, wxString(rowLabel)); for (int col = 0; col < columns; ++col){ if (pointerIndex < dataRead){ void *ptr = (char *)bufferValues + pointerIndex; value = Enums::pointerToString(bufferSettingsList[currentBuffer].types[col], ptr); } else{ value = ""; } gridBufferValues->SetCellValue(row + 1, col, value); pointerIndex += Enums::getSize(bufferSettingsList[currentBuffer].types[col]); } } free(bufferValues); }
int MOFMesh::loadVertexChunk(MOF_CHUNK_HEADER *header,int meshNum) { if(!this->m_file) return RETURN_ERROR; int byteCount; char numElements=0; byteCount = fread(&numElements,1,1,this->m_file); //return RETURN_ERROR; char topology=0; byteCount = fread(&topology,1,1,this->m_file); char windingOrder=0; byteCount = fread(&windingOrder,1,1,this->m_file); //if(header->num<=0) // return RETURN_ERROR; MOFSubmesh *mesh = this->m_meshes[meshNum]; if(windingOrder) mesh->setFrontOrder(true); else mesh->setFrontOrder(false); mesh->setNumVertices(header->num); mesh->setNumElementsVertex(numElements); Vertex *verts = new Vertex[header->num]; //int count=sizeof(header->id)+sizeof(header->num)+sizeof(header->size)+sizeof(numElements); //int readBytes=0; //printf("\nMOF_VERTEX_CHUNK: \n"); //printf(" numVertices: %d(hex: %x)\n numElements %d(hex: %x)\n",header->num,header->num,numElements,numElements); char typeId; for(int i=0; i<header->num; ++i) { for(int j=0; j<numElements; ++j) { byteCount += fread(&typeId,1,1,this->m_file); switch(typeId) { case MOF_VERTEX_POSITION: { float vertVals[3]; byteCount += fread(&vertVals,4,3,this->m_file); /*printf("\nMOF read %d Position: %f %f %f\n",i,vertVals[0], vertVals[1], vertVals[2]);*/ Vector3D position(vertVals); verts[i].position = position; }break; case MOF_VERTEX_NORMAL: { float normVals[3]; byteCount += fread(&normVals,4,3,this->m_file); Vector3D normal(normVals); D3DXVec3Normalize(&normal, &normal); verts[i].normal = normal; /*printf("\nMOF read %d Normals: %f %f %f\n",i,verts[i].normal.x, verts[i].normal.y, verts[i].normal.z);*/ }break; case MOF_VERTEX_TANGENT: { float tangentVals[3]; byteCount += fread(&tangentVals,4,3,this->m_file); Vector3D tangent(tangentVals); D3DXVec3Normalize(&tangent, &tangent); verts[i].tangent = tangent; //printf("\nMOF read %d Tangent: %f %f %f\n",i,verts[i].tangent.x, // verts[i].tangent.y, // verts[i].tangent.z); }break; case MOF_VERTEX_TEX: { float texVals[2]; byteCount += fread(&texVals,4,2,this->m_file); Vector2D tex(texVals); //tex.x = 1-tex.x; tex.y = 1-tex.y; verts[i].texCoord0 = tex; //printf("\nMOF read %d Texture Coords: %f %f\n",i,texVals[0],texVals[1]); }break; case MOF_VERTEX_COLOR: { float colVals[4]; byteCount += fread(&colVals,4*4,1,this->m_file); Color color(colVals); //verts[i].color = color; }break; default: { }; }//end switch }//end for numelements }//end for num //TODO: improve codepaths to avoid multiple SAFE_DELETE stuff IBuffer *vertexBuffer = GLOBALS->getRenderer()->createBuffer(); if(!vertexBuffer) { SAFE_DELETE(vertexBuffer); SAFE_ARRAY_DELETE(verts); return -1; } //mesh.setVertexBuffer(vertexBuffer); if(vertexBuffer->create(verts,sizeof(Vertex),header->num)!=RETURN_OK) { SAFE_DELETE(vertexBuffer); SAFE_ARRAY_DELETE(verts); return -1; } mesh->setVertexBuffer(vertexBuffer); //generate bounding box for the submesh AABB submeshAABB; submeshAABB.loadFromPosition(verts, header->num); mesh->setBoundingBox(submeshAABB); SAFE_ARRAY_DELETE(verts); return byteCount; }
int MOFMesh::loadIndexChunk(MOF_CHUNK_HEADER *header, int meshNum) { //printf("MOF Load Index Chunk\n"); int byteCount=0; MOFSubmesh *mesh = this->m_meshes[meshNum]; mesh->setNumIndices(header->num); //printf("MOF num indices %i\n",header->num); char indexType = 0; byteCount += fread(&indexType,1,1,this->m_file); int *indexData = new int[header->num]; for(int i=0;i<header->num;++i) { int index; int num; //if(indexType==1) num = fread(&index,1,4,this->m_file); //else if(indexType==0) // num = fread(&index,1,2,this->m_file); byteCount +=num; if(num!=4) { SAFE_ARRAY_DELETE(indexData); return RETURN_ERROR; } indexData[i] = index; //printf("MOF index[%i] %i\n",i,index); } IBuffer *indexBuffer = GLOBALS->getRenderer()->createBuffer(); if(!indexBuffer) { SAFE_ARRAY_DELETE(indexData); return -1; } /*if(indexType==0) { printf("16!!\n"); if(indexBuffer->create(indexData,2,header->num,BT_INDEX, FORMAT_R32_UINT)!=RETURN_OK) return -1; } else if(indexType==1) { printf("32!!\n");*/ if(indexBuffer->create(indexData,4,header->num,BT_INDEX)!=RETURN_OK) { SAFE_ARRAY_DELETE(indexData); return -1; } //} mesh->setIndexBuffer(indexBuffer); SAFE_ARRAY_DELETE(indexData); return byteCount; }
void CSampleBank::load(bool async) { // TODO : add async loading support ! CSampleBankManager::TVirtualBankCont::iterator it(_SampleBankManager->m_VirtualBanks.find(_Name)); if (it != _SampleBankManager->m_VirtualBanks.end()) { // this is a virtual sample bank ! nlinfo("Loading virtual sample bank %s", CStringMapper::unmap(_Name).c_str()); const CAudioMixerUser::TBackgroundFlags &flags = _SampleBankManager->m_AudioMixer->getBackgroundFlags(); for (uint i=0; i<it->second.size(); ++i) { if (flags.Flags[it->second[i].Filter]) { CSampleBank *bank = _SampleBankManager->findSampleBank(it->second[i].BankName); if (bank) bank->load(async); } } } //nlinfo("Loading sample bank %s %", CStringMapper::unmap(_Name).c_str(), async?"":"Asynchronously"); vector<string> filenames; // vector<string>::iterator iter; if (_Loaded) { nlwarning("Trying to load an already loaded bank : %s", CStringMapper::unmap(_Name).c_str ()); return; } // Load the sample bank from the builded sample_bank file. string bankName(CStringMapper::unmap(_Name)+".sample_bank"); string filename = CPath::lookup(bankName, false); if (filename.empty()) { nlwarning("Could not find sample bank [%s]", bankName.c_str()); return; } try { CIFile sampleBank(filename); CAudioMixerUser::TSampleBankHeader sbh; sampleBank.serial(sbh); _LoadingDone = false; sint32 seekStart = sampleBank.getPos(); uint8 *data = 0; uint i; for (i=0; i<sbh.Name.size(); ++i) { IBuffer *ibuffer = _SampleBankManager->m_AudioMixer->getSoundDriver()->createBuffer(); nlassert(ibuffer); TStringId nameId = CStringMapper::map(CFile::getFilenameWithoutExtension(sbh.Name[i])); ibuffer->setName(nameId); /* { sint16 *data16 = new sint16[sbh.NbSample[i]]; IBuffer::TADPCMState state; state.PreviousSample = 0; state.StepIndex = 0; uint count =0; for (count=0; count+1024<sbh.NbSample[i]; count+=1024) { IBuffer::decodeADPCM(data+count/2, data16+count, 1024, state); } IBuffer::decodeADPCM(data+count/2, data16+count, sbh.NbSample[i]-count, state); state.PreviousSample = 0; state.StepIndex = 0; sint16 *data16_2 = new sint16[sbh.NbSample[i]]; IBuffer::decodeADPCM(data, data16_2, sbh.NbSample[i], state); for (uint j=0; j<sbh.NbSample[i]; ++j) { if (data16[j] != data16_2[j]) { nlwarning("Sample differ at %u", j); } } _SoundDriver->readRawBuffer(ibuffer, sbh.Name[i], (uint8*)data16, sbh.NbSample[i]*2, Mono16, sbh.Freq[i]); delete [] data16; delete [] data16_2; } */ if (_SampleBankManager->m_AudioMixer->useAPDCM()) { data = (uint8*) realloc(data, sbh.SizeAdpcm[i]); sampleBank.seek(seekStart + sbh.OffsetAdpcm[i], CIFile::begin); sampleBank.serialBuffer(data, sbh.SizeAdpcm[i]); ibuffer->setFormat(IBuffer::FormatDviAdpcm, 1, 16, sbh.Freq[i]); if (!ibuffer->fill(data, sbh.SizeAdpcm[i])) nlwarning("AM: ibuffer->fill returned false with FormatADPCM"); } else { data = (uint8*) realloc(data, sbh.SizeMono16[i]); sampleBank.seek(seekStart + sbh.OffsetMono16[i], CIFile::begin); sampleBank.serialBuffer(data, sbh.SizeMono16[i]); ibuffer->setFormat(IBuffer::FormatPcm, 1, 16, sbh.Freq[i]); if (!ibuffer->fill(data, sbh.SizeMono16[i])) nlwarning("AM: ibuffer->fill returned false with FormatPCM"); } _ByteSize += ibuffer->getSize(); _Samples[nameId] = ibuffer; // Warn the sound bank that the sample are available. CAudioMixerUser::getInstance()->getSoundBank()->bufferLoaded(nameId, ibuffer); } free(data); _SampleBankManager->m_LoadedSize += _ByteSize; } catch(Exception &e) { // loading failed ! nlwarning("Exception %s during loading of sample bank %s", e.what(), filename.c_str()); if (_SampleBankManager->m_AudioMixer->getPackedSheetUpdate()) { nlinfo("Deleting offending sound bank, you need to restart to recreate it!"); CFile::deleteFile(filename); } } _Loaded = true; _LoadingDone = true; ///////////////////////////////////////// OLD Version ////////////////////////////////////// /* std::string list = CPath::lookup(CStringMapper::unmap(_Name)+CAudioMixerUser::SampleBankListExt, false); if (list.empty()) { nlwarning("File %s not found to load sample bank %s", (CStringMapper::unmap(_Name)+CAudioMixerUser::SampleBankListExt).c_str(), CStringMapper::unmap(_Name).c_str()); return; } NLMISC::CIFile sampleBankList(list); sampleBankList.serialCont(filenames); for (iter = filenames.begin(); iter != filenames.end(); iter++) { IBuffer* ibuffer = NULL; try { ibuffer = _SoundDriver->createBuffer(); nlassert(ibuffer); // std::string sampleName(CFile::getFilenameWithoutExtension(*iter)); NLMISC::TStringId sampleName(CStringMapper::map(CFile::getFilenameWithoutExtension(*iter))); if (async) { ibuffer->presetName(sampleName); nldebug("Preloading sample [%s]", CStringMapper::unmap(sampleName).c_str()); } else { std::string fullName = NLMISC::CPath::lookup(*iter, false); if (!fullName.empty()) { NLMISC::CIFile ifile(fullName); uint size = ifile.getFileSize(); uint8 *buffer = new uint8[ifile.getFileSize()]; ifile.serialBuffer(buffer, size); _SoundDriver->readWavBuffer(ibuffer, fullName, buffer, size); _ByteSize += ibuffer->getSize(); delete [] buffer; } } _Samples[sampleName] = ibuffer ; // Warn the sound bank that the sample are available. CSoundBank::instance()->bufferLoaded(sampleName, ibuffer); } catch (ESoundDriver &e) { if (ibuffer != NULL) { delete ibuffer; ibuffer = NULL; } nlwarning("Problem with file '%s': %s", (*iter).c_str(), e.what()); } } _Loaded = true; if (!async) { _LoadingDone = true; // compute the sample bank size. _LoadedSize += _ByteSize; } else { // fill the loading list. TSampleTable::iterator first(_Samples.begin()), last(_Samples.end()); for (; first != last; ++first) { _LoadList.push_back(make_pair(first->second, first->first)); } _SplitLoadDone = false; // send the first files for (uint i=0; i<ASYNC_LOADING_SPLIT && !_LoadList.empty(); ++i) { CAsyncFileManagerSound::getInstance().loadWavFile(_LoadList.front().first, CStringMapper::unmap(_LoadList.front().second)+".wav"); _LoadList.pop_front(); } // add a end loading event... CAsyncFileManagerSound::getInstance().signal(&_SplitLoadDone); // and register for update on the mixer CAudioMixerUser::instance()->registerUpdate(this); } */ }
bool init() { GLenum glewerr; if((glewerr=glewInit()) != GLEW_OK) { LOG("glewinit() failed : ",glewGetErrorString(glewerr),"\n"); return false; } glGetError(); std::cout << "Initializing on "<<glGetString(GL_VENDOR)<<" "<<glGetString(GL_RENDERER)<<" using OpenGL "<<glGetString(GL_VERSION)<<"\n"; LOG("Initializing on ",glGetString(GL_VENDOR)," ",glGetString(GL_RENDERER)," using OpenGL ",glGetString(GL_VERSION),"\n"); glEnable(GL_DEBUG_OUTPUT); glDebugMessageCallback( debugOut, NULL ); glClearDepth(1); openGL.clearDepth(); openGL.getHardwardProperties(); openGL.applyAll(); LOG("\nSupport of bindless_texture: ",glewGetExtension("GL_ARB_bindless_texture")==GL_TRUE); LOG("Support of sparse_texture: ",glewGetExtension("GL_ARB_sparse_texture")==GL_TRUE); texBufferPool = new TextureBufferPool; vertexBufferPool = new VertexBufferPoolType(2 << 20, VertexFormat::VNCT, DrawMode::DYNAMIC); indexBufferPool = new IndexBufferPoolType(8 << 20, DrawMode::DYNAMIC); indexBufferPool->buffer().bind(); textureSampler[TextureMode::NoFilter] = Texture::genTextureSampler(false,false,false,false); textureSampler[TextureMode::Filtered] = Texture::genTextureSampler(true,true,true,false); textureSampler[TextureMode::FilteredNoRepeat] = Texture::genTextureSampler(false,true,true,false); textureSampler[TextureMode::OnlyLinearNoRepeat] = Texture::genTextureSampler(false,true,false,false); textureSampler[TextureMode::DepthMap] = Texture::genTextureSampler(false,true,false,true); ShaderCompiler vDrawQuad(ShaderCompiler::VERTEX_SHADER); vDrawQuad.setSource(drawQuad_vertex); ShaderCompiler pDrawQuad(ShaderCompiler::PIXEL_SHADER); pDrawQuad.setSource(drawQuad_pixel); auto optShader = Shader::combine(vDrawQuad.compile({}), pDrawQuad.compile({})); if(!optShader.hasValue()) { LOG_EXT("DrawQuad Vertex shader error:\n", vDrawQuad.error()); LOG_EXT("DrawQuad Pixel shader error:\n", pDrawQuad.error()); LOG_EXT("DrawQuad Link erorr:", Shader::lastLinkError()); } else drawQuadShader = optShader.value(); ShaderCompiler vDepthPass(ShaderCompiler::VERTEX_SHADER); vDepthPass.setSource(depthPass_vertex); LOG("No gs for DepthPass shader, expect a warning"); optShader = Shader::linkVertexShader(vDepthPass.compile({})); if(!optShader.hasValue()) { LOG_EXT("DepthPass Vertex shader error:\n", vDepthPass.error()); LOG_EXT("DepthPass Link erorr:", Shader::lastLinkError()); } else depthPassShader = optShader.value(); VNCT_Vertex vData[4] = {{vec3(-1,-1,0),vec3(),vec2(0,0),vec3()}, {vec3(-1, 1,0),vec3(),vec2(0,1),vec3()}, {vec3( 1, 1,0),vec3(),vec2(1,1),vec3()}, {vec3( 1,-1,0),vec3(),vec2(1,0),vec3()}}; uint iData[6] = {0,1,2,2,3,0}; VBuffer* tmpVB = vertexBufferPool->alloc(4); IBuffer* tmpIB = indexBufferPool->alloc(6); tmpVB->flush(reinterpret_cast<float*>(vData),0,4); tmpIB->flush(iData,0,6); quadMeshBuffers = new MeshBuffers(tmpVB,tmpIB); glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); if(openGL.hardward(GLState::Hardward::MAJOR_VERSION) > 4 || (openGL.hardward(GLState::Hardward::MAJOR_VERSION)==4 && openGL.hardward(GLState::Hardward::MINOR_VERSION)>=3)) { if(glewGetExtension("GL_ARB_bindless_texture")!=GL_TRUE) { LOG("You don't support GL_ARB_bindless_texture, you can't run TIMEngine sorry."); return false; } return true; } else { LOG("You don't have a sufficient openGL version."); return false; } }
ECode InputStreamReader::Read( /* [out] */ ArrayOf<Char32>* buffer, /* [in] */ Int32 offset, /* [in] */ Int32 count, /* [out] */ Int32* number) { VALIDATE_NOT_NULL(number); *number = -1; VALIDATE_NOT_NULL(buffer); AutoLock lock(mLock); if (!IsOpen()) { Logger::E("InputStreamReader", "InputStreamReader is closed. E_IO_EXCEPTION"); return E_IO_EXCEPTION; } FAIL_RETURN(Arrays::CheckOffsetAndCount(buffer->GetLength(), offset, count)); if (count == 0) { *number = 0; return NOERROR; } AutoPtr<ICharBuffer> out; FAIL_RETURN(CharBuffer::Wrap(buffer, offset, count, (ICharBuffer**)&out)); IBuffer* bout = IBuffer::Probe(out); AutoPtr<ICoderResult> UNDERFLOW, result; CCoderResult::GetUNDERFLOW((ICoderResult**)&UNDERFLOW); result = UNDERFLOW; // bytes.remaining() indicates number of bytes in buffer // when 1-st time entered, it'll be equal to zero Boolean hasRemaining, needInput; IBuffer* bBytes = IBuffer::Probe(mBytes); bBytes->HasRemaining(&hasRemaining); needInput = !hasRemaining; Int32 num = 0, position = 0; while (bout->HasRemaining(&hasRemaining), hasRemaining) { // fill the buffer if needed if (needInput) { mIn->Available(&num); bout->GetPosition(&position); if (num == 0 && position > offset) { // we could return the result without blocking read break; } Int32 capacity, limit, arrayOffset; bBytes->GetCapacity(&capacity); bBytes->GetLimit(&limit); bBytes->GetArrayOffset(&arrayOffset); Int32 desiredByteCount = capacity - limit; Int32 off = arrayOffset + limit; AutoPtr<ArrayOf<Byte> > buf; mBytes->GetArray((ArrayOf<Byte>**)&buf); Int32 actualByteCount; mIn->Read(buf, off, desiredByteCount, &actualByteCount); if (actualByteCount == -1) { mEndOfInput = TRUE; break; } else if (actualByteCount == 0) { break; } bBytes->SetLimit(limit + actualByteCount); needInput = FALSE; } // decode bytes result = NULL; mDecoder->Decode(mBytes, out, FALSE, (ICoderResult**)&result); Boolean isUnderflow; result->IsUnderflow(&isUnderflow); if (isUnderflow) { // compact the buffer if no space left Int32 capacity, limit; bBytes->GetLimit(&limit); bBytes->GetCapacity(&capacity); // compact the buffer if no space left if (limit == capacity) { mBytes->Compact(); bBytes->GetPosition(&position); bBytes->SetLimit(position); bBytes->SetPosition(0); } needInput = TRUE; } else { break; } } if (result.Get() == UNDERFLOW.Get() && mEndOfInput) { result = NULL; mDecoder->Decode(mBytes, out, TRUE, (ICoderResult**)&result); if (result.Get() == UNDERFLOW.Get()) { AutoPtr<ICoderResult> resultFlush; mDecoder->Flush(out, (ICoderResult**)&resultFlush); result = resultFlush; } mDecoder->Reset(); } Boolean isMalformed, isUnmappable; result->IsMalformed(&isMalformed); result->IsUnmappable(&isUnmappable); if (isMalformed || isUnmappable) { return result->ThrowException(); } bout->GetPosition(&position); *number = position - offset == 0 ? -1 : position - offset; return NOERROR; }