void string_id_test() { typedef std::map<StringId, std::vector<int> > StringIdMap; StringIdMap map; StringId tjong_id("tjong"); StringId bong_id("bong"); map[StringId("tjong")].push_back(10); map[StringId("bong")].push_back(20); map[StringId("tjong")].push_back(20); BOOST_CHECK(map.size() == 2); BOOST_CHECK(map[tjong_id].size() == 2); BOOST_CHECK(map[bong_id].size() == 1); }
bool EntityManager::RemoveEntitySystem(EntitySystem& s) { ComponentType componentType = s.GetComponentType(); if(!HasEntitySystem(componentType)) { return false; } ComponentType baseType = s.GetBaseType(); s.OnRemoveFromEntityManager(*this); EntitySystemRemovedMessage msg; msg.SetComponentType(componentType); msg.SetComponentTypeString(GetStringFromSID(componentType)); EmitMessage(msg); mEntitySystemStore.erase(mEntitySystemStore.find(componentType)); if(baseType != StringId()) { std::pair<TypeHierarchyMap::iterator, TypeHierarchyMap::iterator> keyRange; keyRange = mTypeHierarchy.equal_range(baseType); TypeHierarchyMap::iterator it = keyRange.first; while(it != keyRange.second) { if(it->second == componentType) { mTypeHierarchy.erase(it); break; } ++it; } } return true; }
void GameStateManager::SetState(StringId newState) { // Leave current state if (stateInstance_) { delete stateInstance_; stateInstance_=0; state_=StringId(0); } // If there's no new state, we're done if (newState.GetString()==0) { return; } // Change current state typedef GameState* (*CreateFunction)(); HashTableIterator<HashTableKey_StringId,CreateFunction> it(gameStates_); CreateFunction createFunction=0; if (it.Find(HashTableKey_StringId(newState))) { createFunction=it.GetCurrent(); } Assert(createFunction,"State not recognized!"); if (!createFunction) { return; } state_=newState; stateInstance_=createFunction(); }
void GameStateManager::ExitCurrentState() { if (stateInstance_) { delete stateInstance_; stateInstance_=0; state_=StringId(0); } }
StringVector::StringId StringVector::encode(double d) { uint32_t page; uint32_t offset; uint8_t *p = (uint8_t *)&d; memcpy(&page, p, sizeof(uint32_t)); p += sizeof(uint32_t); memcpy(&offset, p, sizeof(uint32_t)); return StringId(page, offset); }
bool ComponentPluginManager::AddFactory(ComponentPluginFactory* factory) { ComponentType ctype = dtEntity::SID(factory->GetName()); if(ctype == StringId() || mFactories.find(ctype) != mFactories.end()) { LOG_ERROR("Factory already registered with type " << factory->GetName()); return false; } else { mFactories[ctype] = factory; return true; } }
void install () { if (s_installed) return; s_installed = true; for (int i = 0; i < static_cast<int>(ShipChassisSlotType::SCST_num_types); ++i) { IGNORE_RETURN (s_slotNameTypeMap.insert (std::make_pair (s_slotTypeNames [i], static_cast<ShipChassisSlotType::Type>(i)))); s_slotTypeShortNames [i] = StringId("space/scst_short_n", s_slotTypeNames [i]).localize(); } }
bool EntityManager::AddEntitySystem(EntitySystem& s) { if(HasEntitySystem(s.GetComponentType())) { LOG_ERROR("Entity system already added! Type: " << GetStringFromSID(s.GetComponentType())); return false; } mEntitySystemStore[s.GetComponentType()] = &s; if(s.GetBaseType() != StringId()) { mTypeHierarchy.insert(std::make_pair(s.GetBaseType(), s.GetComponentType())); } s.OnAddedToEntityManager(*this); EntitySystemAddedMessage msg; msg.SetComponentType(s.GetComponentType()); msg.SetComponentTypeString(GetStringFromSID(s.GetComponentType())); EmitMessage(msg); return true; }
Object * RtValue::_toObject()const{ switch(valueType){ case VOID_VALUE: return Void::get(); case BOOL: return Bool::create(value.value_bool); case OBJECT_PTR: return value.value_obj; case UINT32: return Number::create(value.value_uint32); case NUMBER: return Number::create(value.value_number); case IDENTIFIER: return Identifier::create(StringId( value.value_indentifier)); case LOCAL_STRING_IDX: case UNDEFINED: case FUNCTION_CALL_CONTEXT: default: throw std::logic_error("Value can't converted to an object:"+toDbgString()); return nullptr; } }
void ManufactureSchematicImplementation::initializeIngredientSlots() { Locker locker(_this.getReferenceUnsafeStaticCast()); if(draftSchematic == NULL || initialized) return; ingredientSlots.removeAll(); ingredientNames.removeAll(NULL); ingredientTypes.removeAll(NULL); slotOIDs.removeAll(NULL); slotQuantities.removeAll(NULL); slotQualities.removeAll(NULL); slotClean.removeAll(NULL); slotIndexes.removeAll(NULL); craftingValues->clearAll(); assembled = false; completed = false; initialized = true; complexity = draftSchematic->getComplexity(); manufactureLimit = 0; ingredientCounter = draftSchematic->getDraftSlotCount() * 4; for (int i = 0; i < draftSchematic->getDraftSlotCount(); ++i) { Reference<IngredientSlot* > ingredientSlot = NULL; Reference<DraftSlot* > draftSlot = draftSchematic->getDraftSlot(i); ingredientNames.add(StringId(draftSlot->getStringIdFile(), draftSlot->getStringIdName())); ingredientTypes.add(0); slotOIDs.add(Vector<uint64>()); slotQuantities.add(Vector<int>()); slotQualities.add(0); slotClean.add(0xFFFFFFFF); slotIndexes.add(i); switch (draftSlot->getSlotType()) { case IngredientSlot::RESOURCESLOT: ingredientSlot = new ResourceSlot(); ingredientSlot->setOptional(false); ingredientSlot->setIdentical(true); break; case IngredientSlot::IDENTICALSLOT: ingredientSlot = new ComponentSlot(); ingredientSlot->setOptional(false); ingredientSlot->setIdentical(true); break; case IngredientSlot::MIXEDSLOT: ingredientSlot = new ComponentSlot(); ingredientSlot->setOptional(false); ingredientSlot->setIdentical(false); break; case IngredientSlot::OPTIONALIDENTICALSLOT: ingredientSlot = new ComponentSlot(); ingredientSlot->setOptional(true); ingredientSlot->setIdentical(true); break; case IngredientSlot::OPTIONALMIXEDSLOT: ingredientSlot = new ComponentSlot(); ingredientSlot->setOptional(true); ingredientSlot->setIdentical(false); break; default: error("Ingredient Slot script value bad: " + draftSchematic->getDisplayedName()); continue; } ingredientSlot->setContentType(draftSlot->getResourceType()); ingredientSlot->setQuantityNeeded(draftSlot->getQuantity()); ingredientSlot->setSlotName(draftSlot->getStringIdName()); ingredientSlots.add(ingredientSlot.get()); } }
//! (static) ObjRef _loadAndExecute(Runtime & runtime, const std::string & filename) { const StringData file = IO::loadFile(filename); return _eval(runtime,CodeFragment(StringId(filename),file)); }
ScriptObject* TypeDescriber::describeTraits(Traitsp traits, uint32_t flags) { if (!(flags & INCLUDE_TRAITS)) return NULL; AvmCore* core = m_toplevel->core(); GC* gc = core->GetGC(); TraitsBindingsp tb = traits->getTraitsBindings(); TraitsMetadatap tm = traits->getTraitsMetadata(); ScriptObject* o = new_object(); ArrayObject* bases = NULL; ArrayObject* metadata = NULL; ArrayObject* interfaces = NULL; ArrayObject* methods = NULL; ArrayObject* accessors = NULL; ArrayObject* variables = NULL; ScriptObject* constructor = NULL; if (flags & INCLUDE_BASES) { metadata = new_array(); PoolObject* class_mdpool; const uint8_t* class_md = tm->getMetadataPos(class_mdpool); if (class_md) addDescribeMetadata(metadata, class_mdpool, class_md); } if (flags & INCLUDE_BASES) { bases = new_array(); for (Traitsp b = traits->base; b; b = b->base) pushstr(bases, describeClassName(b)); } if (flags & INCLUDE_INTERFACES) { interfaces = new_array(); // our TraitsBindings only includes our own interfaces, not any we might have inherited, // so walk the tree. there might be redundant interfaces listed in the inheritance, // so use a list to remove dupes List<Traitsp> unique(gc); for (Traitsp b = traits; b; b = b->base) { TraitsBindingsp tbi = b->getTraitsBindings(); for (uint32_t i = 0; i < tbi->interfaceCapacity; ++i) { Traitsp ti = tbi->getInterface(i); if (ti && ti->isInterface && unique.indexOf(ti) < 0) { unique.add(ti); pushstr(interfaces, describeClassName(ti)); } } } } // constructor if (flags & INCLUDE_CONSTRUCTOR) { AbstractFunction* initMethod = traits->init; if (initMethod && initMethod->param_count) { constructor = describeParams(initMethod); } } if (flags & (INCLUDE_ACCESSORS | INCLUDE_METHODS | INCLUDE_VARIABLES)) { // recover slot/method metadata and method-declarer information. // make a flattened set of bindings so we don't have to check for overrides as we go. // This is not terribly efficient, but doesn't need to be. MultinameHashtable* mybind = new (gc) MultinameHashtable(); addBindings(mybind, tb, flags); // Don't want interface methods, so post-process and wipe out any // bindings that were added for (uint32_t i = 0; i < tb->interfaceCapacity; ++i) { Traitsp ti = tb->getInterface(i); if (ti && ti->isInterface) { TraitsBindingsp tbi = ti->getTraitsBindings(); for (int32_t index = 0; (index = tbi->next(index)) != 0; ) { Stringp name = tbi->keyAt(index); Namespacep ns = tbi->nsAt(index); mybind->add(name, ns, BIND_NONE); } } } // yuck, replicate buggy behavior in FP9/10 List<Namespacep> nsremoval(gc); if (flags & HIDE_NSURI_METHODS) { for (uint32_t i = 0; i < tb->interfaceCapacity; ++i) { Traitsp ti = tb->getInterface(i); // already did interfaces, don't need to do them again if (ti && !ti->isInterface) { TraitsBindingsp tbi = ti->getTraitsBindings(); for (int32_t index = 0; (index = tbi->next(index)) != 0; ) { Namespacep ns = tbi->nsAt(index); if (ns->getURI()->length() > 0 && nsremoval.indexOf(ns) < 0) nsremoval.add(ns); } } } } for (int32_t index = 0; (index = mybind->next(index)) != 0; ) { Binding binding = mybind->valueAt(index); Stringp name = mybind->keyAt(index); Namespacep ns = mybind->nsAt(index); Stringp nsuri = ns->getURI(); TraitsMetadata::MetadataPtr md1 = NULL; TraitsMetadata::MetadataPtr md2 = NULL; PoolObject* md1pool = NULL; PoolObject* md2pool = NULL; // We only display public members -- exposing private namespaces could compromise security. if (ns->getType() != Namespace::NS_Public) continue; if ((flags & HIDE_NSURI_METHODS) && nsremoval.indexOf(ns) >= 0) continue; ScriptObject* v = new_object(); const BindingKind bk = AvmCore::bindingKind(binding); switch (bk) { case BKIND_CONST: case BKIND_VAR: { if (!(flags & INCLUDE_VARIABLES)) continue; const uint32_t slotID = AvmCore::bindingToSlotId(binding); const KVPair props[] = { { kstrid_access, strAtom(str(bk == BKIND_CONST ? kstrid_readonly : kstrid_readwrite)) }, { kstrid_type, strAtom(describeClassName(tb->getSlotTraits(slotID))) }, }; setpropmulti(v, props, elem_count(props)); if (!variables) variables = new_array(); pushobj(variables, v); md1 = tm->getSlotMetadataPos(slotID, md1pool); break; } case BKIND_METHOD: { if (!(flags & INCLUDE_METHODS)) continue; const uint32_t methodID = AvmCore::bindingToMethodId(binding); const AbstractFunction* af = tb->getMethod(methodID); Traitsp declaringTraits = af->declaringTraits; const KVPair props[] = { { kstrid_declaredBy, strAtom(describeClassName(declaringTraits)) }, { kstrid_returnType, strAtom(describeClassName(af->returnTraits())) }, { kstrid_parameters, objAtom(describeParams(af)) }, }; setpropmulti(v, props, elem_count(props)); if (!methods) methods = new_array(); pushobj(methods, v); md1 = tm->getMethodMetadataPos(methodID, md1pool); break; } case BKIND_GET: case BKIND_SET: case BKIND_GETSET: { if (!(flags & INCLUDE_ACCESSORS)) continue; const uint32_t methodID = AvmCore::hasGetterBinding(binding) ? AvmCore::bindingToGetterId(binding) : AvmCore::bindingToSetterId(binding); const AbstractFunction* af = tb->getMethod(methodID); Traitsp declaringTraits = af->declaringTraits; Traitsp accessorType = AvmCore::hasGetterBinding(binding) ? af->returnTraits() : af->paramTraits(1); static const uint8_t bk2str[8] = { uint8_t(kstrid_emptyString), // BKIND_NONE uint8_t(kstrid_emptyString), // BKIND_METHOD uint8_t(kstrid_emptyString), // BKIND_VAR uint8_t(kstrid_emptyString), // BKIND_CONST uint8_t(kstrid_emptyString), // BKIND_ITRAMP uint8_t(kstrid_readonly), // BKIND_GET uint8_t(kstrid_writeonly), // BKIND_SET uint8_t(kstrid_readwrite) // BKIND_GETSET }; const KVPair props[] = { { kstrid_declaredBy, strAtom(describeClassName(declaringTraits)) }, { kstrid_access, strAtom(str(StringId(bk2str[bk]))) }, { kstrid_type, strAtom(describeClassName(accessorType)) }, }; setpropmulti(v, props, elem_count(props)); if (AvmCore::hasGetterBinding(binding)) md1 = tm->getMethodMetadataPos(AvmCore::bindingToGetterId(binding), md1pool); if (AvmCore::hasSetterBinding(binding)) md2 = tm->getMethodMetadataPos(AvmCore::bindingToSetterId(binding), md2pool); if (!accessors) accessors = new_array(); pushobj(accessors, v); break; } case BKIND_NONE: break; } ArrayObject* vm = NULL; if ((flags & INCLUDE_METADATA) && (md1 || md2)) { vm = new_array(); addDescribeMetadata(vm, md1pool, md1); addDescribeMetadata(vm, md2pool, md2); } const KVPair props[] = { { kstrid_name, strAtom(name) }, { kstrid_uri, strAtom(nsuri->length() == 0 ? NULL : nsuri) }, { kstrid_metadata, objAtom(vm) }, }; setpropmulti(v, props, elem_count(props)); } } const KVPair props[] = { { kstrid_bases, objAtom(bases) }, { kstrid_interfaces, objAtom(interfaces) }, { kstrid_metadata, objAtom(metadata) }, { kstrid_accessors, objAtom(accessors) }, { kstrid_methods, objAtom(methods) }, { kstrid_variables, objAtom(variables) }, { kstrid_constructor, objAtom(constructor) }, }; setpropmulti(o, props, elem_count(props)); return o; }
void HTTP::Update(float deltaTime) { for (int i=0; i<requests_.GetItemCount(); i++) { Request* request=requests_.Get(i); // Process the request depending on its current status switch (request->status) { case Status_Connecting: { if (request->connection && request->connection->IsConnected()) { // Define the template for HTTP Get header const char* headerGet="GET %s HTTP/1.0\r\nHost: %s:%d\r\n\r\n"; const char* headerPost="POST %s HTTP/1.0\r\nHost: %s:%d\r\nContent-Length: %d\r\n\r\n"; const char* header=0; if (request->usingGetMethod) { header=headerGet; } else { header=headerPost; } // Calculate maximum length of request string int maxLength=StrLen(header)+StrLen(request->requestString)+StrLen(request->connection->GetAddress())+10; // Build request string char* requestString=new char[maxLength]; SNPrintF(requestString,maxLength,header,request->requestString,request->connection->GetAddress(),request->connection->GetPort(),request->postData.GetSize()); // Send HTTP request request->connection->SendData(requestString,StrLen(requestString)); if (!request->usingGetMethod) { request->connection->SendData(request->postData.GetPointer(),request->postData.GetSize()); } // Release request string delete[] requestString; // Change request status to wait for result request->status=Status_Pending; } } break; case Status_Pending: { // Are there any data to receive? if (request->connection && request->connection->GetReceivedDataSize()>0) { // Is this the first chunk of data we receive? bool firstChunk=false; if (request->receivedData.GetSize()==0) { firstChunk=true; } // Receive the data (will be added to the end of the buffer) request->connection->GetReceivedData(&request->receivedData); // If this is the first chunk we receive, we need to process the header if (firstChunk) { // Check Status Line char* statusLine=static_cast<char*>(request->receivedData.GetPointer()); // Get header size int headerSize=0; const char* headerEnd=StrStr(statusLine,"\r\n\r\n"); if (headerEnd) { headerEnd+=4; headerSize=(int)(headerEnd-statusLine); } // Extract httpVersion char httpVersion[256]; const char* ptr=StrChr(statusLine,' '); StrNCpy(httpVersion,statusLine,Min((int)(ptr-statusLine),255)); httpVersion[ptr-statusLine]=0; ptr++; // Extract statusCode char statusCode[256]; const char* ptr2=StrChr(ptr,' '); StrNCpy(statusCode,ptr,Min((int)(ptr2-ptr),255)); statusCode[ptr2-ptr]=0; ptr2++; // Extract reasonPhrase char reasonPhrase[256]; const char* ptr3=StrStr(ptr2,"\r\n"); StrNCpy(reasonPhrase,ptr2,Min((int)(ptr3-ptr2),255)); reasonPhrase[ptr3-ptr2]=0; ptr3++; // Extract contentLength char contentLengthStr[256]; StrCpy(contentLengthStr,"0"); const char* ptr4=StrStr(ptr3,"Content-Length: "); if (ptr4) { ptr4+=16; const char* ptr5=StrStr(ptr4,"\r\n"); StrNCpy(contentLengthStr,ptr4,Min((int)(ptr5-ptr4),255)); contentLengthStr[ptr5-ptr4]=0; } char contentTypeStr[256]; StrCpy(contentTypeStr,""); const char* ptr6=StrStr(ptr3,"Content-Type: "); if (ptr6) { ptr6+=14; const char* ptr7=StrStr(ptr6,"\r\n"); StrNCpy(contentTypeStr,ptr6,Min((int)(ptr7-ptr6),255)); contentTypeStr[ptr7-ptr6]=0; } // Check status int status=StringToInt(statusCode); int contentLength=StringToInt(contentLengthStr); StringId contentType=StringId(contentTypeStr); if (status!=200 || contentLength==0 || contentType==StringId("")) { request->status=Status_Failed; } else { request->headerLength=headerSize; request->contentType=contentType; request->contentLength=contentLength; } } // Check for dropped connection if (!request->connection->IsConnected()) { request->status=Status_Failed; } // Check if we've received the whole resource if (request->status!=Status_Failed && request->receivedData.GetSize()==(unsigned int)request->contentLength+request->headerLength) { request->status=Status_Completed; if (request->resource) { delete request->resource; } char* data=static_cast<char*>(request->receivedData.GetPointer()); data+=request->headerLength; StaticBuffer buffer(data,request->contentLength); request->resource=new HTTP_Resource(request->handle,request->contentType,buffer); } } } break; } if (request->status==Status_Connecting || request->status==Status_Pending) { // Increase the elapsed time request->elapsedTime_+=deltaTime; if (request->timeOut_>0.0f && request->elapsedTime_>request->timeOut_) { request->status=Status_TimedOut; } } } }
// TODO(co) Work-in-progress TextureResourceId TextureResourceManager::loadTextureResourceByAssetId(AssetId assetId, IResourceListener* resourceListener, bool reload) { TextureResourceId textureResourceId = getUninitialized<TextureResourceId>(); // Check whether or not the texture resource already exists TextureResource* textureResource = getTextureResourceByAssetId(assetId); // Create the resource instance const Asset* asset = mRendererRuntime.getAssetManager().getAssetByAssetId(assetId); bool load = (reload && nullptr != asset); if (nullptr == textureResource && nullptr != asset) { textureResource = &mTextureResources.addElement(); textureResource->setResourceManager(this); textureResource->setAssetId(assetId); load = true; } if (nullptr != textureResource) { if (nullptr != resourceListener) { textureResource->connectResourceListener(*resourceListener); } textureResourceId = textureResource->getId(); } // Load the resource, if required if (load) { // Prepare the resource loader // -> The totally primitive texture resource loader type detection is sufficient for now const char* filenameExtension = strrchr(&asset->assetFilename[0], '.'); if (nullptr != filenameExtension) { ITextureResourceLoader* textureResourceLoader = static_cast<ITextureResourceLoader*>(acquireResourceLoaderInstance(StringId(filenameExtension + 1))); if (nullptr != textureResourceLoader) { textureResourceLoader->initialize(*asset, *textureResource); // Commit resource streamer asset load request ResourceStreamer::LoadRequest resourceStreamerLoadRequest; resourceStreamerLoadRequest.resource = textureResource; resourceStreamerLoadRequest.resourceLoader = textureResourceLoader; mRendererRuntime.getResourceStreamer().commitLoadRequest(resourceStreamerLoadRequest); } } else { // TODO(co) Error handling } } // Done return textureResourceId; }