Example #1
0
static void AddDeserializerMixin(duk_context* ctx, const String& package, const String& classname)
{
    js_class_get_prototype(ctx, package.CString(), classname.CString());

    duk_push_c_function(ctx, Deserializer_Read, 0);
    duk_set_magic(ctx, -1, (unsigned) VAR_INT);
    duk_put_prop_string(ctx, -2, "readInt");

    duk_push_c_function(ctx, Deserializer_Read, 0);
    duk_set_magic(ctx, -1, (unsigned) IO_MAGIC_STRING);
    duk_put_prop_string(ctx, -2, "readString");

    duk_push_c_function(ctx, Deserializer_Read, 0);
    duk_set_magic(ctx, -1, (unsigned) IO_MAGIC_ZEROSTRING);
    duk_put_prop_string(ctx, -2, "readZeroString");

    duk_push_c_function(ctx, Deserializer_Read, 0);
    duk_set_magic(ctx, -1, (unsigned)IO_MAGIC_BINARY);
    duk_put_prop_string(ctx, -2, "readBinary");

    duk_push_c_function(ctx, Deserializer_GetSize, 0);
    duk_put_prop_string(ctx, -2, "getSize");

    duk_pop(ctx);
}
void JSClassWriter::GenerateNonStaticFunctionsSource(String& source, String& packageName)
{
    source.AppendWithFormat("js_class_get_prototype(ctx, \"%s\", \"%s\");\n", packageName.CString(), klass_->GetName().CString());

    for (unsigned i = 0; i < klass_->functions_.Size(); i++)
    {
        JSBFunction* function = klass_->functions_.At(i);

        if (function->Skip())
            continue;

        if (function->IsConstructor() || function->IsDestructor())
            continue;

        if (function->IsStatic())
            continue;

        if (function->FirstDefaultParameter() != -1)
        {
            source.AppendWithFormat("duk_push_c_function(ctx, jsb_class_%s_%s, DUK_VARARGS);\n", klass_->GetName().CString(), function->GetName().CString());
        }
        else
        {
            source.AppendWithFormat("duk_push_c_function(ctx, jsb_class_%s_%s, %i);\n", klass_->GetName().CString(), function->GetName().CString(), (int)function->GetParameters().Size());
        }

        String scriptName = function->GetName();
        scriptName[0] = tolower(scriptName[0]);
        source.AppendWithFormat("duk_put_prop_string(ctx, -2, \"%s\");\n", scriptName.CString());

    }
    source.Append("duk_pop(ctx);\n");
}
// Called to parse a RCSS number declaration.
bool PropertyParserNumber::ParseValue(Property& property, const String& value, const ParameterMap& ROCKET_UNUSED_PARAMETER(parameters)) const
{
	ROCKET_UNUSED(parameters);

	// Default to a simple number.
	property.unit = Property::NUMBER;

	// Check for a unit declaration at the end of the number.
	size_t unit_pos =  value.Length();
	for (size_t i = 0; i < unit_suffixes.size(); i++)
	{
		const UnitSuffix& unit_suffix = unit_suffixes[i];

		if (value.Length() < unit_suffix.second.Length())
			continue;

		size_t test_unit_pos = value.Length() - unit_suffix.second.Length();
		if (strcasecmp(value.CString() + test_unit_pos, unit_suffix.second.CString()) == 0)
		{
			unit_pos = test_unit_pos;
			property.unit = unit_suffix.first;
			break;
		}
	}

	float float_value;
	String str_value( value.CString(), value.CString() + unit_pos );
	if (sscanf(str_value.CString(), "%f", &float_value) == 1)
	{
		property.value = Variant(float_value);
		return true;
	}

	return false;
}
    static bool jsplugin_get_entry_points(const String& pluginLibrary, atomic_plugin_validate_function* fvalidate,
                                          duk_c_function* finit, String& errorMsg)
    {
        *fvalidate = NULL;
        *finit = NULL;

        // TODO: cache and use SDL_UnloadObject (when no longer needed)
        void* handle = SDL_LoadObject(pluginLibrary.CString());

        if (handle == NULL)
        {
            errorMsg = ToString("Native Plugin: Unable to load %s", pluginLibrary.CString());
            return false;
        }

        *fvalidate = (atomic_plugin_validate_function) SDL_LoadFunction(handle, "atomic_plugin_validate");

        if (!*fvalidate)
        {
            errorMsg = ToString("Native Plugin: Unable to get atomic_plugin_validate entry point in %s", pluginLibrary.CString());
            return false;
        }

        *finit = (duk_c_function) SDL_LoadFunction(handle, "atomic_plugin_init");

        if (!*finit)
        {
            LOGERRORF("Native Plugin: Unable to get atomic_plugin_init entry point in %s", pluginLibrary.CString());
            return false;
        }

        return true;

    }
Example #5
0
void Interpreter::LoadFile(const String& file)
{
    //use the file interface to get the contents of the script
    Rocket::Core::FileInterface* file_interface = Rocket::Core::GetFileInterface();
    Rocket::Core::FileHandle handle = file_interface->Open(file);
    if(handle == 0) {
        lua_pushfstring(_L, "LoadFile: Unable to open file: %s", file.CString());
        Report(_L);
        return;
    }

    size_t size = file_interface->Length(handle);
    if(size == 0) {
        lua_pushfstring(_L, "LoadFile: File is 0 bytes in size: %s", file.CString());
        Report(_L);
        return;
    }
    char* file_contents = new char[size];
    file_interface->Read(file_contents,size,handle);
    file_interface->Close(handle);

    if(luaL_loadbuffer(_L,file_contents,size,file.CString()) != 0)
        Report(_L); 
    else //if there were no errors loading, then the compiled function is on the top of the stack
    {
        if(lua_pcall(_L,0,0,0) != 0)
            Report(_L);
    }

    delete[] file_contents;
}
void ResourceOps::HandleNewFolder(const String& resourcePath, bool reportError)
{
    Editor* editor = GetSubsystem<Editor>();
    FileSystem* fs = GetSubsystem<FileSystem>();

    if (fs->DirExists(resourcePath) || fs->FileExists(resourcePath))
    {
        if (reportError)
        {
            String errorMsg;
            errorMsg.AppendWithFormat("Already exists:\n\n %s", resourcePath.CString());
            editor->PostModalError("New Folder Error", errorMsg);
        }

        return;
    }

    if (!fs->CreateDir(resourcePath))
    {
        if (reportError)
        {
            String errorMsg;
            errorMsg.AppendWithFormat("Could not create:\n\n %s", resourcePath.CString());
            editor->PostModalError("New Folder Error", errorMsg);
        }

        return;
    }

    // file watcher doesn't currently handle subdir
    GetSubsystem<MainFrame>()->GetProjectFrame()->Refresh();

}
Example #7
0
void Log::WriteRaw(const String& message, bool error)
{
    // If not in the main thread, store message for later processing
    if (!Thread::IsMainThread())
    {
        if (logInstance)
        {
            MutexLock lock(logInstance->logMutex_);
            logInstance->threadMessages_.Push(StoredLogMessage(message, LOG_RAW, error));
        }

        return;
    }

    // Prevent recursion during log event
    if (!logInstance || logInstance->inWrite_)
        return;

    logInstance->lastMessage_ = message;

#if defined(__ANDROID__)
    if (logInstance->quiet_)
    {
        if (error)
            __android_log_print(ANDROID_LOG_ERROR, "Urho3D", message.CString());
    }
    else
        __android_log_print(error ? ANDROID_LOG_ERROR : ANDROID_LOG_INFO, "Urho3D", message.CString());
#elif defined(IOS)
    SDL_IOS_LogMessage(message.CString());
#else
    if (logInstance->quiet_)
    {
        // If in quiet mode, still print the error message to the standard error stream
        if (error)
            PrintUnicode(message, true);
    }
    else
        PrintUnicode(message, error);
#endif

    if (logInstance->logFile_)
    {
        logInstance->logFile_->Write(message.CString(), message.Length());
        logInstance->logFile_->Flush();
    }

    logInstance->inWrite_ = true;

    using namespace LogMessage;

    VariantMap& eventData = logInstance->GetEventDataMap();
    eventData[P_MESSAGE] = message;
    eventData[P_LEVEL] = error ? LOG_ERROR : LOG_INFO;
    logInstance->SendEvent(E_LOGMESSAGE, eventData);

    logInstance->inWrite_ = false;
}
void JSPackageWriter::WriteProtoTypeRecursive(String &source, JSBClass* klass,  Vector<JSBClass*>& written)
{
    if (written.Contains(klass))
        return;

    if (klass->GetModule()->GetDotNetModule())
        return;

    PODVector<JSBClass*>& baseClasses = klass->GetBaseClasses();

    Vector<JSBClass*>::Iterator itr = baseClasses.End() - 1 ;

    while (itr != baseClasses.Begin() - 1)
    {
        WriteProtoTypeRecursive(source, (*itr), written);
        itr--;
    }

    JSBClass* base = baseClasses.Size() ? baseClasses[0] : NULL;

    if (!klass->IsNumberArray() && klass->GetPackage() == package_)
    {
        JSBModule* module = klass->GetModule();

        String moduleGuard = module->GetModuleDefineGuard();

        if (moduleGuard.Length())
        {
            source += ToString("\n%s\n", moduleGuard.CString());
        }

        if (module->Requires("3D"))
            source += "\n#ifdef ATOMIC_3D\n";

        String packageName =  klass->GetModule()->GetPackage()->GetName();
        String basePackage =  base ? base->GetModule()->GetPackage()->GetName() : "";

        source.AppendWithFormat("   js_setup_prototype(vm, \"%s\", \"%s\", \"%s\", \"%s\", %s);\n",
                                packageName.CString(), klass->GetName().CString(),
                                base ? basePackage.CString() : "", base ? base->GetName().CString() : "",
                                klass->HasProperties() ? "true" : "false");

        if (module->Requires("3D"))
            source += "#endif\n\n";

        if (moduleGuard.Length())
        {
            source += ToString("\n#endif\n", moduleGuard.CString());
        }

    }

    written.Push(klass);

}
    bool jsplugin_load(JSVM* vm, const String& pluginLibrary)
    {
         String errorMsg;
         atomic_plugin_validate_function validatefunc;
         duk_c_function initfunc;

         duk_context* ctx = vm->GetJSContext();

         LOGINFOF("Loading Native Plugin: %s", pluginLibrary.CString());

         if (!jsplugin_get_entry_points(pluginLibrary, &validatefunc, &initfunc, errorMsg))
         {
             LOGERRORF("%s", errorMsg.CString());
             return false;
         }

         int version = ATOMIC_JSPLUGIN_VERSION;
         if (!validatefunc(version, &gJSVMExports, sizeof(JSVMImports)))
         {
             LOGERRORF("Native Plugin: atomic_plugin_validate failed: %s", pluginLibrary.CString());
             return false;
         }

        // just to verify that we're not doing anything funky with the stack
        int top = duk_get_top(ctx);

        // the import function is a standard duktape c function, neat
        duk_push_c_function(ctx, initfunc, 1);

        // requires exports to be at index 2
        duk_dup(ctx, 2);

        bool success = true;
        if (duk_pcall(ctx, 1) != DUK_EXEC_SUCCESS)
        {
            success = false;
            LOGERRORF("Native Plugin: error calling atomic_plugin_init %s", pluginLibrary.CString());
        }
        else
        {
            if (!duk_is_boolean(ctx, -1) || !duk_to_boolean(ctx, -1))
            {
                success = false;
                LOGERRORF("Native Plugin: error calling atomic_plugin_init, didn't return true %s", pluginLibrary.CString());
            }
        }

        duk_pop(ctx);
        assert(top == duk_get_top(ctx));

        return success;


    }
String PlatformIOS::ParseProvisionAppIdentifierPrefix(const String& provisionFile)
{
#if defined(ATOMIC_PLATFORM_WINDOWS) || defined(ATOMIC_PLATFORM_LINUX)

    return String::EMPTY;

#else

    String pdata = GetMobileProvisionData(provisionFile.CString());

    if (!pdata.Length())
        return String::EMPTY;

    pugi::xml_document doc;

    if (!doc.load(pdata.CString()))
    {
        return String::EMPTY;
    }

    String AppIDName;
    String ApplicationIdentifierPrefix;

    pugi::xml_node dict = doc.document_element().child("dict");

    for (pugi::xml_node key = dict.child("key"); key; key = key.next_sibling("key"))
    {
        String keyName = key.child_value();

        if (keyName == "AppIDName")
        {
            pugi::xml_node value = key.next_sibling();
            if (!strcmp(value.name(), "string"))
                AppIDName = value.child_value();
        }
        else if (keyName == "ApplicationIdentifierPrefix")
        {
            pugi::xml_node array = key.next_sibling();
            if (!strcmp(array.name(), "array"))
            {
                pugi::xml_node value = array.first_child();
                if (!strcmp(value.name(), "string"))
                    ApplicationIdentifierPrefix = value.child_value();
            }

        }
    }

    return ApplicationIdentifierPrefix;

#endif

}
void AEPreferences::Read()
{
    rapidjson::Document document;

    String filepath = GetPreferencesFullPath();

    File jsonFile(context_, filepath);

    if (!jsonFile.IsOpen())
        return;

    String json;
    jsonFile.ReadText(json);

    if (!json.Length())
        return;

    if (document.Parse<0>(json.CString()).HasParseError())
    {
        LOGERRORF("Could not parse JSON data from %s", filepath.CString());
        return;
    }

    Clear();

    const Value::Member* recent_files = document.FindMember("recent_files");
    if (recent_files && recent_files->value.IsArray())
    {
        for (Value::ConstValueIterator itr = recent_files->value.Begin(); itr != recent_files->value.End(); itr++)
        {
             if (!(*itr).IsString())
                 continue;

            String path(itr->GetString());
            recentProjects_.Push(path.CString());
        }
    }

    const Value::Member* android_sdk_path = document.FindMember("android_sdk_path");
    if (android_sdk_path && android_sdk_path->value.IsString())
        androidSDKPath_ = android_sdk_path->value.GetString();

    const Value::Member* jdk_root_path = document.FindMember("jdk_root_path");
    if (jdk_root_path && jdk_root_path->value.IsString())
        jdkRootPath_ = jdk_root_path->value.GetString();

    const Value::Member* ant_path = document.FindMember("ant_path");
    if (ant_path && ant_path->value.IsString())
        antPath_ = ant_path->value.GetString();

    UpdateRecentFiles(false);

}
/// Save account information to a file
void GameEconomicGameClient::SaveConfiguration(Configuration &configuration)
{
    /// Get Resource
    ResourceCache * cache = GetSubsystem<ResourceCache>();
    FileSystem * fileSystem = GetSubsystem<FileSystem>();

    String configFileName;

    /// Set directory and path for network file
    configFileName.Append(fileSystem->GetProgramDir().CString());
    configFileName.Append("");
    configFileName.Append("Configuration.xml");


    /// Check if the account file information exist
    if(fileSystem->FileExists(configFileName.CString()))
    {
        fileSystem->Delete(configFileName.CString());
    }

    cout << "It got here "<<endl;

    File saveFile(context_, configFileName.CString(), FILE_WRITE);

    XMLFile * preferencefileconfig  = new XMLFile(context_);

    XMLElement configElem = preferencefileconfig   -> CreateRoot("Configuration");
    XMLElement GameModeConfigurationElement = configElem.CreateChild("GameModeConfiguration");
    XMLElement VideoConfigurationElement= configElem.CreateChild("VideoConfiguration");

    /// Set true false
    if(configuration.GameModeForceTablet==true)
    {
        GameModeConfigurationElement.SetAttribute("GameModeForceTablet", "true");
    }
    else
    {
        GameModeConfigurationElement.SetAttribute("GameModeForceTablet", "false");
    }

    /// Convert video bloom to float
    String VideoBloomParamValue1String(configuration.VideoBloomParam1);
    String VideoBloomParamValue2String(configuration.VideoBloomParam2);

    /// Copy values testing
    VideoConfigurationElement.SetAttribute("BloomParam1",VideoBloomParamValue1String);
    VideoConfigurationElement.SetAttribute("BloomParam2",VideoBloomParamValue2String);

    preferencefileconfig->Save(saveFile);

    return;
}
void ResourceEditor::SetModified(bool modified)
{
    modified_ = modified;
    if (modified)
    {
        String filename = GetFileNameAndExtension(fullpath_);
        filename += "*";
        button_->SetText(filename.CString());
    }
    else
    {
        String filename = GetFileNameAndExtension(fullpath_);
        button_->SetText(filename.CString());
    }
}
Example #14
0
void Texture::SetParameters(const XMLElement& element)
{
    XMLElement paramElem = element.GetChild();
    while (paramElem)
    {
        String name = paramElem.GetName();

        if (name == "address")
        {
            String coord = paramElem.GetAttributeLower("coord");
            if (coord.Length() >= 1)
            {
                TextureCoordinate coordIndex = (TextureCoordinate)(coord[0] - 'u');
                String mode = paramElem.GetAttributeLower("mode");
                SetAddressMode(coordIndex, (TextureAddressMode)GetStringListIndex(mode.CString(), addressModeNames, ADDRESS_WRAP));
            }
        }

        if (name == "border")
            SetBorderColor(paramElem.GetColor("color"));

        if (name == "filter")
        {
            String mode = paramElem.GetAttributeLower("mode");
            SetFilterMode((TextureFilterMode)GetStringListIndex(mode.CString(), filterModeNames, FILTER_DEFAULT));
        }

        if (name == "mipmap")
            SetNumLevels(paramElem.GetBool("enable") ? 0 : 1);

        if (name == "quality")
        {
            if (paramElem.HasAttribute("low"))
                SetMipsToSkip(QUALITY_LOW, paramElem.GetInt("low"));
            if (paramElem.HasAttribute("med"))
                SetMipsToSkip(QUALITY_MEDIUM, paramElem.GetInt("med"));
            if (paramElem.HasAttribute("medium"))
                SetMipsToSkip(QUALITY_MEDIUM, paramElem.GetInt("medium"));
            if (paramElem.HasAttribute("high"))
                SetMipsToSkip(QUALITY_HIGH, paramElem.GetInt("high"));
        }

        if (name == "srgb")
            SetSRGB(paramElem.GetBool("enable"));

        paramElem = paramElem.GetNext();
    }
}
Example #15
0
void Log::Write(int level, const String& message)
{
    assert(level >= LOG_DEBUG && level < LOG_NONE);

    // Do not log if message level excluded or if currently sending a log event
    if (!logInstance || logInstance->level_ > level || logInstance->inWrite_)
        return;

    String formattedMessage = logLevelPrefixes[level];
    formattedMessage += ": " + message;
    logInstance->lastMessage_ = message;

    if (logInstance->timeStamp_)
        formattedMessage = "[" + Time::GetTimeStamp() + "] " + formattedMessage;

    #if defined(ANDROID)
    int androidLevel = ANDROID_LOG_DEBUG + level;
    __android_log_print(androidLevel, "Urho3D", "%s", message.CString());
    #elif defined(IOS)
    SDL_IOS_LogMessage(message.CString());
    #else
    if (logInstance->quiet_)
    {
        // If in quiet mode, still print the error message to the standard error stream
        if (level == LOG_ERROR)
            PrintUnicodeLine(formattedMessage, true);
    }
    else
        PrintUnicodeLine(formattedMessage, level == LOG_ERROR);
    #endif

    if (logInstance->logFile_)
    {
        logInstance->logFile_->WriteLine(formattedMessage);
        logInstance->logFile_->Flush();
    }

    logInstance->inWrite_ = true;

    using namespace LogMessage;

    VariantMap& eventData = logInstance->GetEventDataMap();
    eventData[P_MESSAGE] = formattedMessage;
    eventData[P_LEVEL] = level;
    logInstance->SendEvent(E_LOGMESSAGE, eventData);

    logInstance->inWrite_ = false;
}
 void OnSignal(const String & param0, const String & param1)
 {
     duk_context* ctx = ctx_;
     duk_push_global_object(ctx);
     duk_get_prop_string(ctx, -1, "_OnSignal");
     duk_remove(ctx, -2);
     duk_push_number(ctx, (size_t)key_);
     duk_push_array(ctx);
     duk_push_string(ctx, param0.CString());
     duk_put_prop_index(ctx, -2, 0);
     duk_push_string(ctx, param1.CString());
     duk_put_prop_index(ctx, -2, 1);
     bool success = duk_pcall(ctx, 2) == 0;
     if (!success) LogError("[JavaScript] OnSignal: " + GetErrorString(ctx));
     duk_pop(ctx);
 }
static duk_ret_t Terrain_EnsureTypeNameWithoutPrefix_Static_String(duk_context* ctx)
{
    String tn = duk_require_string(ctx, 0);
    String ret = Terrain::EnsureTypeNameWithoutPrefix(tn);
    duk_push_string(ctx, ret.CString());
    return 1;
}
Example #18
0
bool ResourceOps::CheckCreate2DLevel(const String& resourcePath, const String& resourceName, bool reportError)
{

    Editor* editor = GetSubsystem<Editor>();
    Project* project = editor->GetProject();

    String fullpath = resourcePath + resourceName;
    if (!resourceName.EndsWith(".tmx"))
        fullpath += ".tmx";

    FileSystem* fs = GetSubsystem<FileSystem>();

    if (fs->FileExists(fullpath))
    {
        if (reportError)
        {
            String errorMsg;
            errorMsg.AppendWithFormat("The level:\n\n%s\n\nalready exists", fullpath.CString());
            editor->PostModalError("Create 2D Level Error", errorMsg);
        }

        return false;
    }

    return true;

}
JSASTStatement* JSASTNode::ParseStatement(const rapidjson::Value &value)
{
    assert(value.IsObject());

    JSASTStatement* statement = NULL;

    const Value::Member* mtype = value.FindMember("type");
    assert(mtype);

    String type = mtype->value.GetString();

    if (type == "ExpressionStatement")
    {
        statement = new JSASTExpressionStatement();
    }
    else if (type == "VariableDeclaration")
    {
        statement = new JSASTVariableDeclaration();
    }
    else if (type == "ReturnStatement")
    {
        statement = new JSASTReturnStatement();
    }
    else if (type == "FunctionDeclaration")
    {
        statement = new JSASTFunctionDeclaration();
    }
    else if (type == "IfStatement")
    {
        statement = new JSASTIfStatement();
    }
    else if (type == "BlockStatement")
    {
        statement = new JSASTBlockStatement();
    }
    else if (type == "EmptyStatement")
    {
        statement = new JSASTBlockStatement();
    }
    else if (type == "ForStatement")
    {
        statement = new JSASTForStatement();
    }
    else if (type == "LabeledStatement")
    {
        statement = new JSASTLabeledStatement();
    }

    if (!statement)
    {
        LOGWARNINGF("Unknown JSASTStatement: %s", type.CString());
    }
    else
    {
        statement->Parse(value);
    }

    return statement;

}
Example #20
0
void Compression::CompressStreamToFile(const BYTE *stream, UINT byteCount, const String &filename)
{
    BYTE *compressedStream = new BYTE[byteCount + 64];

    z_stream zstream;

    zstream.zalloc = Z_NULL;
    zstream.zfree = Z_NULL;
    zstream.opaque = Z_NULL;
	
	zstream.avail_in = byteCount;
	zstream.next_in = const_cast<BYTE*>(stream);

	zstream.data_type = Z_BINARY;

	zstream.avail_out = byteCount + 64;
    zstream.next_out = compressedStream;

	const int Level = 6;
    //Result = deflateInit(&Stream, Level);
	int result = deflateInit2(&zstream, Level, Z_DEFLATED, 15, 8, Z_DEFAULT_STRATEGY);
	PersistentAssert(result == Z_OK, "deflateInit failed");

    result = deflate(&zstream, Z_FINISH);
	PersistentAssert(result == Z_STREAM_END, "deflate failed");

    deflateEnd(&zstream);

    FILE *file = Utility::CheckedFOpen(filename.CString(), "wb");
    Utility::CheckedFWrite(&byteCount, sizeof(UINT32), 1, file);
    Utility::CheckedFWrite(compressedStream, sizeof(BYTE), zstream.total_out, file);
    fclose(file);

    delete[] compressedStream;
}
Example #21
0
void StateManager::CreatePixelShader(CONST DWORD* pFunction, HANDLE Shader)
{
    PShaderMap::iterator Iterator = PShaders.find(Shader);
    if(Iterator == PShaders.end())
    {
        PShader *NewShader = new PShader(pFunction, Shader);
        Assert(NewShader != NULL, "Out of memory in StateManager::CreatePixelShader");
        if(CaptureAllShaders)
        {
            VShader TempShader(pFunction, NULL);
            String AssemblyFilename = String(g_Context->Parameters.ShaderCaptureDirectory) + String("PShader") + String::ZeroPad(String(TempShader.Hash()), 10) + ".txt";
            ofstream DisassemblyFile(AssemblyFilename.CString());
            TempShader.OutputDisassembly(DisassemblyFile);
            /*g_Context->Files.ShaderInfo << String::ZeroPad(String(TempShader.Hash()), 10) << '\t' << TempShader.Instructions.Length() << '\t';
            Vector<UINT> InstructionCounts;
            TempShader.ComputeShaderInstructionCounts(InstructionCounts);
            for(UINT InstructionIndex = 0; InstructionIndex < InstructionCounts.Length(); InstructionIndex++)
            {
                g_Context->Files.ShaderInfo << InstructionCounts[InstructionIndex];
                if(InstructionIndex != InstructionCounts.Length() - 1)
                {
                     g_Context->Files.ShaderInfo << '\t';
                }
            }
            g_Context->Files.ShaderInfo << endl;*/
        }
        PShaders[Shader] = NewShader;
    }
    else
    {
        //g_Context->Files.Assert << "Double-create on same PShader handle\n";
    }
}
Example #22
0
String XMLFile::ToString(const String& indentation) const
{
    VectorBuffer dest;
    XMLWriter writer(dest);
    document_->save(writer, indentation.CString());
    return String((const char*)dest.GetData(), dest.GetSize());
}
Example #23
0
TextureUnit ParseTextureUnitName(String name)
{
    name = name.ToLower().Trimmed();

    TextureUnit unit = (TextureUnit)GetStringListIndex(name.CString(), textureUnitNames, MAX_TEXTURE_UNITS);
    if (unit == MAX_TEXTURE_UNITS)
    {
        // Check also for shorthand names
        if (name == "diff")
            unit = TU_DIFFUSE;
        else if (name == "albedo")
            unit = TU_DIFFUSE;
        else if (name == "norm")
            unit = TU_NORMAL;
        else if (name == "spec")
            unit = TU_SPECULAR;
        else if (name == "env")
            unit = TU_ENVIRONMENT;
        // Finally check for specifying the texture unit directly as a number
        else if (name.Length() < 3)
            unit = (TextureUnit)Clamp(ToInt(name), 0, MAX_TEXTURE_UNITS - 1);
    }

    if (unit == MAX_TEXTURE_UNITS)
        LOGERROR("Unknown texture unit name " + name);

    return unit;
}
Example #24
0
bool Serializer::WriteString(const String& value)
{
    const char* chars = value.CString();
    // Count length to the first zero, because ReadString() does the same
    unsigned length = String::CStringLength(chars);
    return Write(chars, length + 1) == length + 1;
}
void JSResourceEditor::HandleWebMessage(StringHash eventType, VariantMap& eventData)
{
    using namespace WebMessage;

    const String& request = eventData[P_REQUEST].GetString();
    WebMessageHandler* handler = static_cast<WebMessageHandler*>(eventData[P_HANDLER].GetPtr());

    if (request == "change")
    {
        SetModified(true);
    }
    else
    {
        JSONValue jvalue;
        if (JSONFile::ParseJSON(request, jvalue, false))
        {
            String message = jvalue["message"].GetString();
            if (message == "saveCode")
            {
                String code = jvalue["payload"].GetString();
                File file(context_, fullpath_, FILE_WRITE);
                file.Write((void*) code.CString(), code.Length());
                file.Close();
            }
        }
    }

    handler->Success();

}
Example #26
0
bool LuaScript::LoadRawFile(const String& fileName)
{
    PROFILE(LoadRawFile);

    LOGINFO("Finding Lua file on file system: " + fileName);

    ResourceCache* cache = GetSubsystem<ResourceCache>();
    String filePath = cache->GetResourceFileName(fileName);

    if (filePath.Empty())
    {
        LOGINFO("Lua file not found: " + fileName);
        return false;
    }

    filePath = GetNativePath(filePath);

    LOGINFO("Loading Lua file from file system: " + filePath);

    if (luaL_loadfile(luaState_, filePath.CString()))
    {
        const char* message = lua_tostring(luaState_, -1);
        LOGERRORF("Load Lua file failed: %s", message);
        lua_pop(luaState_, 1);
        return false;
    }

    LOGINFO("Lua file loaded: " + filePath);

    return true;
}
Example #27
0
bool JSVM::ExecuteFunction(const String& functionName)
{
    duk_get_global_string(ctx_, functionName.CString());
    if (duk_is_function(ctx_, -1))
    {
        bool ok = true;

        if (duk_pcall(ctx_, 0) != 0)
        {
            ok = false;
            if (duk_is_object(ctx_, -1))
            {
                SendJSErrorEvent();
            }
            else
            {
                assert(0);
            }
                    }

        duk_pop(ctx_);
        return ok;

    }
    else
    {
        duk_pop(ctx_);
    }

    return false;

}
Example #28
0
bool LuaFile::LoadChunk(lua_State* luaState)
{
    if (hasLoaded_)
        return true;

    if (size_ == 0)
        return false;

    if (!luaState)
        return false;

    int top = lua_gettop(luaState);

    // Get file base name
    String name = GetName();
    unsigned extPos = name.FindLast('.');
    if (extPos != String::NPOS)
    {
        name = name.Substring(0, extPos);
    }

    int error = luaL_loadbuffer(luaState, data_, size_, name.CString());
    if (error)
    {
        const char* message = lua_tostring(luaState, -1);
        LOGERROR("Load Buffer failed for " + GetName() + ": " + String(message));
        lua_settop(luaState, top);
        return false;
    }

    LOGINFO("Loaded Lua script " + GetName());
    hasLoaded_ = true;

    return true;
}
Example #29
0
void Client::Login(const String& address, unsigned short port, kNet::SocketTransportLayer protocol)
{
    if (owner_->IsServer())
    {
        LogError("Already running a server, cannot login to a world as a client");
        return;
    }

    reconnect_ = false;
    
    KristalliProtocol *kristalli = owner_->KristalliProtocol();

    if (protocol == kNet::InvalidTransportLayer)
    {
        LogInfo("Client::Login: No protocol specified, using the default value.");
        protocol = kristalli->defaultTransport;
    }
    // Set all login properties we have knowledge of. 
    // Others may have been added before calling this function.
    SetLoginProperty("protocol", String(SocketTransportLayerToString(protocol).c_str()).ToLower());
    SetLoginProperty("address", address);
    SetLoginProperty("port", port);
    SetLoginProperty("client-version", "2.5.4.1");
    SetLoginProperty("client-name", "Name");
    SetLoginProperty("client-organization", "Org");

    kristalli->NetworkMessageReceived.Connect(this, &Client::HandleKristalliMessage);

    kristalli->ConnectionAttemptFailed.Connect(this, &Client::OnConnectionAttemptFailed);

    kristalli->Connect(address.CString(), port, protocol);
    loginstate_ = ConnectionPending;
    client_id_ = 0;
}
Example #30
0
void Pipe::ConnectToPipe(const String &PipeName)
{
    ClosePipe();
    bool Done = false;
    while(!Done)
    {
        _Handle = CreateFile( 
            PipeName.CString(),           // pipe name 
            GENERIC_READ |                // read and write access 
            GENERIC_WRITE, 
            0,                            // no sharing 
            NULL,                         // default security attributes
            OPEN_EXISTING,                // opens existing pipe 
            0,                            // default attributes 
            NULL);                        // no template file
        if(_Handle != INVALID_HANDLE_VALUE)
        {
            Done = true;
        }
        Sleep(100);
    }

    DWORD Mode = PIPE_READMODE_MESSAGE;
    BOOL Success = SetNamedPipeHandleState( 
        _Handle,  // pipe handle 
        &Mode,    // new pipe mode 
        NULL,     // don't set maximum bytes 
        NULL);    // don't set maximum time 
    Assert(Success != FALSE, "SetNamedPipeHandleState failed in Pipe::ConnectToPipe");
}