Example #1
0
void Explosion::Set(const Vector3 position, const Color color, const float size)
{
    Effect::Set(position);
    rootNode_->SetScale(size);
    initialMass_ = 3.0f * size;
    rigidBody_->SetMass(initialMass_);
    light_->SetColor(color);
    light_->SetBrightness(initialBrightness_);

    ParticleEffect* particleEffect = particleEmitter_->GetEffect();
    Vector<ColorFrame> colorFrames;
    colorFrames.Push(ColorFrame(Color(0.0f, 0.0f, 0.0f, 0.0f), 0.0f));
    Color mixColor = 0.5f * (color + particleEffect->GetColorFrame(1)->color_);
    colorFrames.Push(ColorFrame(mixColor, 0.1f));
    colorFrames.Push(ColorFrame(mixColor*0.1f, 0.35f));
    colorFrames.Push(ColorFrame(Color(0.0f, 0.0f, 0.0f, 0.0f), 0.0f));
    particleEffect->SetColorFrames(colorFrames);

    sampleSource_->SetGain(Min(0.5f*size, 1.0f));
    sampleSource_->Play(sample_);

    masterControl_->tileMaster_->AddToAffectors(WeakPtr<Node>(rootNode_), WeakPtr<RigidBody>(rigidBody_));

    SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(Explosion, UpdateExplosion));
}
Example #2
0
void BatchQueue::BuildInstances(Vector<Batch>& batches, Vector<Matrix3x4>& instanceTransforms)
{
    Batch* start = nullptr;
    for (auto it = batches.Begin(), end = batches.End(); it != end; ++it)
    {
        Batch* current = &*it;
        if (start && current->type == GEOM_STATIC && current->pass == start->pass && current->geometry == start->geometry &&
            current->lights == start->lights)
        {
            if (start->type == GEOM_INSTANCED)
            {
                instanceTransforms.Push(*current->worldMatrix);
                ++start->instanceCount;
            }
            else
            {
                // Begin new instanced batch
                start->type = GEOM_INSTANCED;
                size_t instanceStart = instanceTransforms.Size();
                instanceTransforms.Push(*start->worldMatrix);
                instanceTransforms.Push(*current->worldMatrix);
                start->instanceStart = instanceStart; // Overwrites non-instance world matrix
                start->instanceCount = 2; // Overwrites sort key / distance
            }
        }
        else
            start = (current->type == GEOM_STATIC) ? current : nullptr;
    }
}
Example #3
0
void HuffmanTree::EncodeSymbol(const char symbol, Vector<char>& code)
{
	bool isEncoded=false;
	Node* node=this->root;

	while(!isEncoded)
	{
		if(this->IsLeaf(node))
		{
			isEncoded=true;
			code.Push('\0');
		}
        else
		{
			if(this->ContainsSymbol(node->left, symbol))
			{
				code.Push('0');
				node=node->left;
			}

			else
			{
				code.Push('1');
				node=node->right;
			}
		}
	}
}
Example #4
0
void PlayCmd::Run()
{
    LOGINFOF("Playing project");

    ToolSystem* tsystem = GetSubsystem<ToolSystem>();
    ToolEnvironment* env = GetSubsystem<ToolCore::ToolEnvironment>();
    Project* project = tsystem->GetProject();
    const String& editorBinary = env->GetEditorBinary();

    Vector<String> paths;
    paths.Push(env->GetCoreDataDir());
    paths.Push(env->GetPlayerDataDir());
    paths.Push(project->GetResourcePath());

    // fixme: this is for loading from cache
    paths.Push(project->GetProjectPath());
    paths.Push(project->GetProjectPath() + "Cache");

    String resourcePaths;
    resourcePaths.Join(paths, "!");

    Vector<String> vargs;

    String args = ToString("--player --project \"%s\"", AddTrailingSlash(project->GetProjectPath()).CString());

    vargs = args.Split(' ');
    //vargs.Insert(0, "--player");

    // TODO: use IPC (maybe before this set log location/access the log and output it, we need access to errors)
    LaunchPlayerProcess(editorBinary, vargs, "");

    Finished();

}
Example #5
0
void Light::OnRaycast(Vector<RaycastResult>& dest, const Ray& ray, float maxDistance)
{
    if (lightType == LIGHT_SPOT)
    {
        float distance = ray.HitDistance(WorldFrustum());
        if (distance <= maxDistance)
        {
            RaycastResult res;
            res.position = ray.origin + distance * ray.direction;
            res.normal = -ray.direction;
            res.distance = distance;
            res.node = this;
            res.subObject = 0;
            dest.Push(res);
        }
    }
    else if (lightType == LIGHT_POINT)
    {
        float distance = ray.HitDistance(WorldSphere());
        if (distance <= maxDistance)
        {
            RaycastResult res;
            res.position = ray.origin + distance * ray.direction;
            res.normal = -ray.direction;
            res.distance = distance;
            res.node = this;
            res.subObject = 0;
            dest.Push(res);
        }
    }
}
void BuildIOS::RunDeploy()
{
    SubprocessSystem* subs = GetSubsystem<SubprocessSystem>();
    ExternalTooling* tooling = GetSubsystem<ExternalTooling>();
    String iosDeploy = tooling->GetToolApplicationPath();
    iosDeploy += "CommandLine/ios-deploy";


    Vector<String> args;

    args.Push("--uninstall");
    args.Push("--bundle");
    args.Push("./AtomicPlayer.app");

    currentBuildPhase_ = Deploy;
    Subprocess* subprocess = subs->Launch(iosDeploy.CString(), args, buildPath_);

    if (!subprocess)
    {
        assert(0);
        // ERROR
        return;
    }

    SubscribeToEvent(subprocess, E_SUBPROCESSCOMPLETE, HANDLER(BuildIOS, HandleEvent));
    SubscribeToEvent(subprocess, E_SUBPROCESSOUTPUT, HANDLER(BuildIOS, HandleEvent));


    UIModalOps* ops = GetSubsystem<UIModalOps>();
    ops->SetProgramOutputSubprocess(subprocess);

    ops->PrintToProgramOutput("\n\n<color #D4FB79>Deploying to iOS Device</color>\n\n");

}
void BuildBase::GetDefaultResourcePaths(Vector<String>& paths)
{
    paths.Clear();

    ToolEnvironment* tenv = GetSubsystem<ToolEnvironment>();

    paths.Push(AddTrailingSlash(tenv->GetCoreDataDir()));
    paths.Push(AddTrailingSlash(tenv->GetPlayerDataDir()));
}
Example #8
0
void CSTypeHelper::GenNativeFunctionParameterSignature(JSBFunction* function, String& sig)
{
    JSBClass* klass = function->GetClass();

    const Vector<JSBFunctionType*>& parameters = function->GetParameters();

    Vector<String> args;

    if (!function->IsConstructor() && !function->IsStatic())
    {
        args.Push(ToString("%s* self", klass->GetNativeName().CString()));
    }

    if (parameters.Size())
    {
        for (unsigned int i = 0; i < parameters.Size(); i++)
        {
            JSBFunctionType* ptype = parameters.At(i);

            // ignore "Context" parameters
            if (ptype->type_->asClassType())
            {
                JSBClassType* classType = ptype->type_->asClassType();
                JSBClass* klass = classType->class_;
                if (klass->GetName() == "Context")
                {
                    continue;
                }

                args.Push(ToString("%s* %s", klass->GetNativeName().CString(), ptype->name_.CString()));
            }
            else
            {
                args.Push(CSTypeHelper::GetNativeTypeString(ptype) + " " + ptype->name_);
            }

        }
    }

    if (function->GetReturnClass() && function->GetReturnClass()->IsNumberArray())
    {
        args.Push(ToString("%s* returnValue", function->GetReturnClass()->GetNativeName().CString()));
    }

    if (function->GetReturnType())
    {
        JSBVectorType* vtype = function->GetReturnType()->type_->asVectorType();

        if (vtype)
        {
            args.Push("ScriptVector* returnValue");
        }
    }

    sig.Join(args, ", ");

}
void PlatformAndroid::PrependAndroidCommandArgs(Vector<String> args)
{
#ifdef ATOMIC_PLATFORM_WINDOWS
    // android is a batch file on windows, so have to run with cmd /c
    args.Push("/c");
    args.Push("\"" + GetAndroidCommand() + "\"");
#endif

}
Example #10
0
bool Model::EndLoad()
{
    Vector<SharedPtr<VertexBuffer> > vbs;
    for (size_t i = 0; i < vbDescs.Size(); ++i)
    {
        const VertexBufferDesc& vbDesc = vbDescs[i];
        SharedPtr<VertexBuffer> vb(new VertexBuffer());

        vb->Define(USAGE_IMMUTABLE, vbDesc.numVertices, vbDesc.vertexElements, true, vbDesc.vertexData.Get());
        vbs.Push(vb);
    }

    Vector<SharedPtr<IndexBuffer> > ibs;
    for (size_t i = 0; i < ibDescs.Size(); ++i)
    {
        const IndexBufferDesc& ibDesc = ibDescs[i];
        SharedPtr<IndexBuffer> ib(new IndexBuffer());

        ib->Define(USAGE_IMMUTABLE, ibDesc.numIndices, ibDesc.indexSize, true, ibDesc.indexData.Get());
        ibs.Push(ib);
    }

    // Set the buffers to each geometry
    geometries.Resize(geomDescs.Size());
    for (size_t i = 0; i < geomDescs.Size(); ++i)
    {
        geometries[i].Resize(geomDescs[i].Size());
        for (size_t j = 0; j < geomDescs[i].Size(); ++j)
        {
            const GeometryDesc& geomDesc = geomDescs[i][j];
            SharedPtr<Geometry> geom(new Geometry());

            geom->lodDistance = geomDesc.lodDistance;
            geom->primitiveType = geomDesc.primitiveType;
            geom->drawStart = geomDesc.drawStart;
            geom->drawCount = geomDesc.drawCount;
            
            if (geomDesc.vbRef < vbs.Size())
                geom->vertexBuffer = vbs[geomDesc.vbRef];
            else
                LOGERROR("Out of range vertex buffer reference in " + Name());

            if (geomDesc.ibRef < ibs.Size())
                geom->indexBuffer = ibs[geomDesc.ibRef];
            else
                LOGERROR("Out of range index buffer reference in " + Name());
            
            geometries[i][j] = geom;
        }
    }

    vbDescs.Clear();
    ibDescs.Clear();
    geomDescs.Clear();

    return true;
}
void CSModuleWriter::WriteIncludes(String& source)
{

    Vector<String>& includes = module_->includes_;
    for (unsigned i = 0; i < includes.Size(); i++)
    {
        if (includes[i].StartsWith("<"))
            source.AppendWithFormat("#include %s\n", includes[i].CString());
        else
            source.AppendWithFormat("#include \"%s\"\n", includes[i].CString());
    }

    Vector<JSBHeader*> allheaders;

    HashMap<StringHash, SharedPtr<JSBEnum> >::Iterator eitr = module_->enums_.Begin();
    while (eitr != module_->enums_.End())
    {
        allheaders.Push(eitr->second_->GetHeader());
        eitr++;
    }

    HashMap<StringHash, SharedPtr<JSBClass> >::Iterator citr = module_->classes_.Begin();
    while (citr != module_->classes_.End())
    {
        allheaders.Push(citr->second_->GetHeader());
        citr++;
    }

    Vector<JSBHeader*> included;

    for (unsigned i = 0; i < allheaders.Size(); i++)
    {
        JSBHeader* header = allheaders.At(i);

        if (included.Contains(header))
            continue;

        String headerPath = GetPath(header->GetFilePath());

        String headerfile = GetFileNameAndExtension(header->GetFilePath());

        JSBind* jsbind = header->GetSubsystem<JSBind>();

        headerPath.Replace(jsbind->GetSourceRootFolder() + "Source/", "");

        source.AppendWithFormat("#include <%s%s>\n", headerPath.CString(), headerfile.CString());

        included.Push(header);
    }

    source += ToString("\n#include \"CSPackage%s.h\"\n", module_->GetPackage()->GetName().CString());

}
bool EditorMode::PlayProject(String addArgs, bool debug)
{
    ToolEnvironment* env = GetSubsystem<ToolEnvironment>();
    ToolSystem* tsystem = GetSubsystem<ToolSystem>();

    const String& editorBinary = env->GetEditorBinary();

    Project* project = tsystem->GetProject();

    if (!project)
        return false;

    Vector<String> paths;
    paths.Push(env->GetCoreDataDir());
    paths.Push(env->GetPlayerDataDir());
    paths.Push(project->GetResourcePath());

    // fixme: this is for loading from cache
    paths.Push(project->GetProjectPath());
    paths.Push(project->GetProjectPath() + "Cache");

    String resourcePaths;
    resourcePaths.Join(paths, "!");

    Vector<String> vargs;

    String args = ToString("--player --project \"%s\"", AddTrailingSlash(project->GetProjectPath()).CString());

    vargs = args.Split(' ');

    if (debug)
        vargs.Insert(0, "--debug");

    if (addArgs.Length() > 0)
        vargs.Insert(0, addArgs.Split(' '));

    String dump;
    dump.Join(vargs, " ");
    LOGINFOF("Launching Broker %s %s", editorBinary.CString(), dump.CString());

    IPC* ipc = GetSubsystem<IPC>();
    playerBroker_ = ipc->SpawnWorker(editorBinary, vargs);

    if (playerBroker_)
    {
        SubscribeToEvent(playerBroker_, E_IPCJSERROR, HANDLER(EditorMode, HandleIPCJSError));
        SubscribeToEvent(playerBroker_, E_IPCWORKEREXIT, HANDLER(EditorMode, HandleIPCWorkerExit));
        SubscribeToEvent(playerBroker_, E_IPCWORKERLOG, HANDLER(EditorMode, HandleIPCWorkerLog));
    }

    return playerBroker_.NotNull();

}
void NavigationMesh::CollectGeometries(Vector<NavigationGeometryInfo>& geometryList)
{
    ATOMIC_PROFILE(CollectNavigationGeometry);

    // Get Navigable components from child nodes, not from whole scene. This makes it possible to partition
    // the scene into several navigation meshes
    PODVector<Navigable*> navigables;
    node_->GetComponents<Navigable>(navigables, true);

    HashSet<Node*> processedNodes;
    for (unsigned i = 0; i < navigables.Size(); ++i)
    {
        if (navigables[i]->IsEnabledEffective())
            CollectGeometries(geometryList, navigables[i]->GetNode(), processedNodes, navigables[i]->IsRecursive());
    }

    // Get offmesh connections
    Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
    PODVector<OffMeshConnection*> connections;
    node_->GetComponents<OffMeshConnection>(connections, true);

    for (unsigned i = 0; i < connections.Size(); ++i)
    {
        OffMeshConnection* connection = connections[i];
        if (connection->IsEnabledEffective() && connection->GetEndPoint())
        {
            const Matrix3x4& transform = connection->GetNode()->GetWorldTransform();

            NavigationGeometryInfo info;
            info.component_ = connection;
            info.boundingBox_ = BoundingBox(Sphere(transform.Translation(), connection->GetRadius())).Transformed(inverse);

            geometryList.Push(info);
        }
    }

    // Get nav area volumes
    PODVector<NavArea*> navAreas;
    node_->GetComponents<NavArea>(navAreas, true);
    areas_.Clear();
    for (unsigned i = 0; i < navAreas.Size(); ++i)
    {
        NavArea* area = navAreas[i];
        if (area->IsEnabledEffective())
        {
            NavigationGeometryInfo info;
            info.component_ = area;
            info.boundingBox_ = area->GetWorldBoundingBox();
            geometryList.Push(info);
            areas_.Push(WeakPtr<NavArea>(area));
        }
    }
}
Vector<AssetPtr> AssetRefListListener::Assets() const
{
    Vector<AssetPtr> assets;
    for (uint i = 0; i < current_.Size(); ++i)
    {
        const AssetReference &ref = current_[i];
        if (!ref.ref.Empty())
            assets.Push(assetAPI_->FindAsset(ref.ref));
        else
            assets.Push(AssetPtr());
    }
    return assets;
}
Example #15
0
template<> void* ToluaToVector<String>(lua_State* L, int narg, void* def)
{
    if (!lua_istable(L, narg))
        return 0;

    static Vector<String> result;
    result.Clear();

    int length = lua_objlen(L, narg);
    for (int i = 1; i <= length; ++i)
    {
        lua_pushinteger(L, i);
        lua_gettable(L, narg);

        if (!lua_isstring(L, -1))
        {
            lua_pop(L, 1);
            return 0;
        }

        String string = tolua_tourho3dstring(L, -1, "");
        result.Push(string);

        lua_pop(L, 1);
    }

    return &result;
}
Example #16
0
/*----------------------------------------------------------------------------------------------
	Set the startup information this window to the promoted entry.
	@param hvo The id of the entry or subentry that has been promoted.
----------------------------------------------------------------------------------------------*/
void CleDeSplitChild::PromoteSetup(HVO hvo)
{
	Assert(hvo);
	// At the moment we are assuming hvo is a CmPossibility (or subclass). At some point this
	// will probably change, which will require additional code.
	Vector<HVO> vhvo;
	Vector<int> vflid;
	// Set up the path to hvo.
	vhvo.Push(hvo);
	// Add owning records, if there are any, until we reach the main record.
	CustViewDaPtr qcvd;
	m_qlpi->GetDataAccess(&qcvd);
	AssertPtr(qcvd);
	RecMainWnd * prmw = dynamic_cast<RecMainWnd *>(MainWindow());
	AssertPtr(prmw);
	HVO hvoRoot = prmw->GetRootObj();
	HVO hvoOwn;
	while (hvo)
	{
		CheckHr(qcvd->get_ObjOwner(hvo, &hvoOwn));
		hvo = hvoOwn;
		if (hvo == hvoRoot || !hvo)
			break;
		vhvo.Insert(0, hvo);
		vflid.Insert(0, kflidCmPossibility_SubPossibilities);
	}
	prmw->SetStartupInfo(vhvo.Begin(), vhvo.Size(), vflid.Begin(), vflid.Size(), 0, 0);
}
Example #17
0
void Octree::CollectNodes(Vector<Pair<OctreeNode*, float> >& result, const Octant* octant, const Ray& ray, unsigned short nodeFlags,
    float maxDistance, unsigned layerMask) const
{
    float octantDist = ray.HitDistance(octant->cullingBox);
    if (octantDist >= maxDistance)
        return;

    const Vector<OctreeNode*>& octantNodes = octant->nodes;
    for (auto it = octantNodes.Begin(); it != octantNodes.End(); ++it)
    {
        OctreeNode* node = *it;
        if ((node->Flags() & nodeFlags) == nodeFlags && (node->LayerMask() & layerMask))
        {
            float distance = ray.HitDistance(node->WorldBoundingBox());
            if (distance < maxDistance)
                result.Push(MakePair(node, distance));
        }
    }

    for (size_t i = 0; i < NUM_OCTANTS; ++i)
    {
        if (octant->children[i])
            CollectNodes(result, octant->children[i], ray, nodeFlags, maxDistance, layerMask);
    }
}
Example #18
0
bool FileSystem::SystemOpen(const String& fileName, const String& mode)
{
    if (allowedPaths_.Empty())
    {
        if (!FileExists(fileName) && !DirExists(fileName))
        {
            LOGERROR("File or directory " + fileName + " not found");
            return false;
        }

        #ifdef WIN32
        bool success = (size_t)ShellExecuteW(0, !mode.Empty() ? WString(mode).CString() : 0,
            GetWideNativePath(fileName).CString(), 0, 0, SW_SHOW) > 32;
        #else
        Vector<String> arguments;
        arguments.Push(fileName);
        bool success = SystemRun(
        #if defined(__APPLE__)
                "/usr/bin/open",
        #else
                "/usr/bin/xdg-open",
        #endif
                arguments) == 0;
        #endif
        if (!success)
            LOGERROR("Failed to open " + fileName + " externally");
        return success;
    }
    else
    {
        LOGERROR("Opening a file externally is not allowed");
        return false;
    }
}
Example #19
0
void InputContext::ReleaseAllKeys()
{
    Vector<Key> keysToRelease;

    // We double buffer the to-be-released keys first to a temporary list, since invoking the trigger
    // function will add new entries to newKeyEvents.

    for(auto iter = heldKeysBuffered.Begin(); iter != heldKeysBuffered.End(); ++iter)
        keysToRelease.Push(iter->first_);

    for(auto iter = newKeyEvents.Begin(); iter != newKeyEvents.End(); ++iter)
        keysToRelease.Push(iter->first_);

    for(auto iter = keysToRelease.Begin(); iter != keysToRelease.End(); ++iter)
        TriggerKeyReleaseEvent(*iter);
}
Example #20
0
/*----------------------------------------------------------------------------------------------
	Fix up the 'next' or 'basedOn' attributes in the styles, now that we have a complete
	list.
	Attribute:
		flid		- attribute to set
		hmhvostu	- map containing the values ofthe attribute
----------------------------------------------------------------------------------------------*/
void WpStylesheet::FixStyleReferenceAttrs(int flid, HashMap<HVO, StrUni> & hmhvostu)
{
	WpDaPtr wpda = dynamic_cast<WpDa *>(m_qsda.Ptr());

	//	Generate a list of all the style names.
	Vector<StrUni> vstuNames;
	int cst;
	CheckHr(m_qsda->get_VecSize(khvoText, kflidStText_Styles, &cst));
	Assert(cst == m_vhcStyles.Size());
	for (int ist = 0; ist < cst; ist++)
	{
		SmartBstr sbstr;
		CheckHr(wpda->get_UnicodeProp(m_vhcStyles[ist].hvo, kflidStStyle_Name, &sbstr));
		vstuNames.Push(StrUni(sbstr.Chars()));
	}

	//	For each style, if it has a value in the map, find the corresponding style
	//	and set the attribute.
	for (int ist = 0; ist < cst; ist++)
	{
		HVO hvo = m_vhcStyles[ist].hvo;
		StrUni stuRef;
		if (hmhvostu.Retrieve(hvo, &stuRef))
		{
			for (int istTmp = 0; istTmp < cst; istTmp++)
			{
				if (vstuNames[istTmp] == stuRef)
				{
					CheckHr(wpda->CacheObjProp(hvo, flid, m_vhcStyles[istTmp].hvo));
					break;
				}
			}
		}
	}
}
Example #21
0
void SceneEditor3D::HandleUpdate(StringHash eventType, VariantMap& eventData)
{
    Vector<Node*> editNodes;
    if (selectedNode_.NotNull())
        editNodes.Push(selectedNode_);
    gizmo3D_->Update(editNodes);
}
void Server::OnDisconnected(ConnectionHandle connection)
{
    Urho3D::MutexLock lock(mutexEvents_);

    ConnectionPtr connectionPtr = server_->get_con_from_hdl(connection);

    // Find existing events and remove them if we got duplicates 
    // that were not synced to main thread yet.
    Vector<SocketEvent*> removeItems;
    for (uint i = 0; i < events_.Size(); ++i)
    {
        // Remove any and all messages from this connection,
        // as it's disconnecting
        SocketEvent *existing = events_[i];
        if (existing->connection == connectionPtr)
            removeItems.Push(existing);
    }
    if (!removeItems.Empty())
    {
        for (uint i = 0; i < removeItems.Size(); ++i)
            events_.Remove(removeItems[i]);
    }

    events_.Push(new SocketEvent(connectionPtr, SocketEvent::Disconnected));
}
bool ff::OptimizeSprites(ISpriteList *pSprites, DXGI_FORMAT format, size_t nMipMapLevels, ISpriteList **ppOptimizedSprites)
{
	assertRetVal(pSprites && ppOptimizedSprites, false);

	// Create the return value
	ComPtr<ISpriteList> pNewSprites;
	assertRetVal(CreateSpriteList(pSprites->GetDevice(), &pNewSprites), false);

	// Cache all the sprites
	Vector<OptimizedSpriteInfo> sprites;
	sprites.Reserve(pSprites->GetCount());

	for (size_t i = 0; i < pSprites->GetCount(); i++)
	{
		OptimizedSpriteInfo sprite(pSprites->Get(i), i);
		sprites.Push(sprite);
	}

	// Sort the sprites by size
	if (!sprites.IsEmpty())
	{
		qsort(sprites.Data(), sprites.Size(), sizeof(OptimizedSpriteInfo), CompareSpriteInfo);
	}

	// Figure out how many textures to create
	Vector<OptimizedTextureInfo> textureInfos;
	Vector<ComPtr<IGraphTexture>> textures;
	Vector<ComPtr<IGraphTexture>> finalTextures;
	Vector<std::shared_ptr<DirectX::ScratchImage>> alphaTextures;

	assertRetVal(ComputeOptimizedSprites(sprites, textureInfos), false);
	assertRetVal(CreateOptimizedTextures(format, pSprites->GetDevice(), textureInfos, textures), false);

	if (!sprites.IsEmpty())
	{
		qsort(sprites.Data(), sprites.Size(), sizeof(OptimizedSpriteInfo), CompareSpriteInfoIndex);
	}

	assertRetVal(CopyOptimizedSprites(sprites, textures), false);
	assertRetVal(ConvertOptimizedTextures(format, nMipMapLevels, textures, finalTextures, alphaTextures), false);

	// Create final sprites
	for (size_t i = 0; i < sprites.Size(); i++)
	{
		OptimizedSpriteInfo &sprite = sprites[i];
		const SpriteData &data = sprite._sprite->GetSpriteData();
		SpriteType type = UpdateSpriteType(sprite, *alphaTextures[sprite._destTexture]);

		assertRetVal(pNewSprites->Add(
			finalTextures[sprite._destTexture],
			data._name,
			sprite._destRect.ToFloat(),
			sprite._srcHandle,
			sprite._srcScale,
			type), false);
	}

	*ppOptimizedSprites = pNewSprites.Detach();
	return true;
}
Example #24
0
void BuildMac::Build(const String& buildPath)
{
    ToolSystem* tsystem = GetSubsystem<ToolSystem>();

    buildPath_ = AddTrailingSlash(buildPath) + GetBuildSubfolder();

    Initialize();

    BuildSystem* buildSystem = GetSubsystem<BuildSystem>();

    FileSystem* fileSystem = GetSubsystem<FileSystem>();
    if (fileSystem->DirExists(buildPath_))
        fileSystem->RemoveDir(buildPath_, true);

    String dataPath = tsystem->GetDataPath();

    String appSrcPath = dataPath + "Deployment/MacOS/AtomicPlayer.app";

    fileSystem->CreateDir(buildPath_);

    buildPath_ += "/AtomicPlayer.app";

    fileSystem->CreateDir(buildPath_);

    fileSystem->CreateDir(buildPath_ + "/Contents");
    fileSystem->CreateDir(buildPath_ + "/Contents/MacOS");
    fileSystem->CreateDir(buildPath_ + "/Contents/Resources");

    String resourcePackagePath = buildPath_ + "/Contents/Resources/AtomicResources.pak";
    GenerateResourcePackage(resourcePackagePath);

    fileSystem->Copy(appSrcPath + "/Contents/Resources/Atomic.icns", buildPath_ + "/Contents/Resources/Atomic.icns");

    fileSystem->Copy(appSrcPath + "/Contents/Info.plist", buildPath_ + "/Contents/Info.plist");
    fileSystem->Copy(appSrcPath + "/Contents/MacOS/AtomicPlayer", buildPath_ + "/Contents/MacOS/AtomicPlayer");

#ifdef ATOMIC_PLATFORM_OSX
    Vector<String> args;
    args.Push("+x");
    args.Push(buildPath_ + "/Contents/MacOS/AtomicPlayer");
    fileSystem->SystemRun("chmod", args);
#endif

    buildPath_ = buildPath + "/Mac-Build";    
    buildSystem->BuildComplete(PLATFORMID_MAC, buildPath_);

}
Example #25
0
Vector<String> String::Split(const char* str, char separator)
{
    Vector<String> ret;
    size_t pos = 0;
    size_t length = CStringLength(str);
    
    while (pos < length)
    {
        if (str[pos] != separator)
            break;
        ++pos;
    }
    
    while (pos < length)
    {
        size_t start = pos;
        
        while (start < length)
        {
            if (str[start] == separator)
                break;
            
            ++start;
        }
        
        if (start == length)
        {
            ret.Push(String(&str[pos]));
            break;
        }
        
        size_t end = start;
        
        while (end < length)
        {
            if (str[end] != separator)
                break;
            
            ++end;
        }
        
        ret.Push(String(&str[pos], start - pos));
        pos = end;
    }
    
    return ret;
}
Example #26
0
// ------------------------- ASTree ------------------------
void ASTree::Print(FILE *stream)const
{
  Vector<char> trunk; // to store and share trunk info
  trunk.Push('\0'); // empty string
  std::printf("%sPathExpr %p\n", trunk.Data(), this->root);
  assert(this->root);
  this->root->Print(trunk);
}
Example #27
0
void Entity::SerializeToBinary(kNet::DataSerializer &dst, bool serializeTemporary, bool serializeLocal, bool serializeChildren) const
{
    dst.Add<u32>(Id());
    dst.Add<u8>(IsReplicated() ? 1 : 0);
    Vector<ComponentPtr> serializable;
    Vector<EntityPtr> serializableChildren;
    for (ComponentMap::ConstIterator i = components_.Begin(); i != components_.End(); ++i)
        if (i->second_->ShouldBeSerialized(serializeTemporary, serializeLocal))
            serializable.Push(i->second_);

    if (serializeChildren)
    {
        foreach(const EntityWeakPtr &childWeak, children_)
        {
            const EntityPtr child = childWeak.Lock();
            if (child && child->ShouldBeSerialized(serializeTemporary, serializeLocal, serializeChildren))
                serializableChildren.Push(child);
        }
    }

    /// \hack Retain binary compatibility with earlier scene format, at the cost of max. 65535 components or child entities
    if (serializable.Size() > 0xffff)
        LogError("Entity::SerializeToBinary: entity contains more than 65535 components, binary save will be erroneous");
    if (serializableChildren.Size() > 0xffff)
        LogError("Entity::SerializeToBinary: entity contains more than 65535 child entities, binary save will be erroneous");

    dst.Add<u32>(serializable.Size() | (serializableChildren.Size() << 16));
    foreach(const ComponentPtr &comp, serializable)
    {
        dst.Add<u32>(comp->TypeId()); ///\todo VLE this!
        dst.AddString(comp->Name().CString());
        dst.Add<u8>(comp->IsReplicated() ? 1 : 0);

        // Write each component to a separate buffer, then write out its size first, so we can skip unknown components
        PODVector<unsigned char> comp_bytes;
        // Assume 64KB max per component for now
        comp_bytes.Resize(64 * 1024);
        kNet::DataSerializer comp_dest((char*)&comp_bytes[0], comp_bytes.Size());
        comp->SerializeToBinary(comp_dest);
        comp_bytes.Resize(static_cast<uint>(comp_dest.BytesFilled()));
        
        dst.Add<u32>(comp_bytes.Size());
        if (comp_bytes.Size())
            dst.AddArray<u8>((const u8*)&comp_bytes[0], comp_bytes.Size());
    }
Example #28
0
Vector<SharedPtr<Connection> > Network::GetClientConnections() const
{
    Vector<SharedPtr<Connection> > ret;
    for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
        i != clientConnections_.End(); ++i)
        ret.Push(i->second_);
    
    return ret;
}
Example #29
0
void Octree::CollectNodes(Vector<OctreeNode*>& result, const Octant* octant) const
{
    result.Push(octant->nodes);

    for (size_t i = 0; i < NUM_OCTANTS; ++i)
    {
        if (octant->children[i])
            CollectNodes(result, octant->children[i]);
    }
}
Example #30
0
void Player::SetupShip()
{
    ship_.node_ = rootNode_->CreateChild("Ship");
    ship_.model_ = ship_.node_->CreateComponent<StaticModel>();
    ship_.model_->SetModel(masterControl_->resources.models.ships.swift);
    ship_.model_->SetMaterial(0, masterControl_->resources.materials.shipSecondary);
    ship_.model_->SetMaterial(1, masterControl_->resources.materials.shipPrimary);

    ParticleEmitter* particleEmitter = ship_.node_->CreateComponent<ParticleEmitter>();
    SharedPtr<ParticleEffect> particleEffect = masterControl_->cache_->GetTempResource<ParticleEffect>("Resources/Particles/Shine.xml");
    Vector<ColorFrame> colorFrames;
    colorFrames.Push(ColorFrame(Color(0.0f, 0.0f, 0.0f, 0.0f), 0.0f));
    colorFrames.Push(ColorFrame(Color(0.42f, 0.7f, 0.23f, 0.23f), 0.2f));
    colorFrames.Push(ColorFrame(Color(0.0f, 0.0f, 0.0f, 0.0f), 0.4f));
    particleEffect->SetColorFrames(colorFrames);
    particleEmitter->SetEffect(particleEffect);

    CreateTails();
}