<commit_before><commit_msg>Fix typo in last commit<commit_after><|endoftext|>


<commit_before>#include "common.h"
#include "log.h"
#include "util.h"
#include "perftimer.h"
#include "rdb/rdb.h"

extern Logger *TheLogger;
extern bool   TheVerbosity;

static int
usage(const char *prog)
{
	fprintf(stderr, "%s [-get|-set|-del] -path <db_path> -name <db_name>\n", prog);
	fprintf(stderr, "        -key <key> [-value <value>]\n");
	fprintf(stderr, "        [-htsize <hash_table_size>] [-pgsize <page_size>]\n");
	fprintf(stderr, "        [-memusage <%%_of_memory>] [-syncdf <0|1>]\n");
	fprintf(stderr, "        [-syncif <0|1>] [-logpath <log_path>]\n");
	return 1;
}

static int
random_in_range(int seed, int lo, int hi)
{
	if (lo == hi)
		return lo;

	if (seed != 0)
		srand(seed);

	return lo + (rand() % (hi - lo));
}

static void
gen_key_val(char *key, char *val, int len)
{
	int idx;
	char valid_chars[] = {
		'0', '1', '2', '3',
		'4', '5', '6', '7',
		'8', '9', 'a', 'b',
		'c', 'd', 'e', 'f',
		'g', 'h', 'i', 'j',
		'k', 'l', 'm', 'n',
		'o', 'p', 'q', 'r',
		's', 't', 'u', 'v',
		'w', 'x', 'y', 'z'
	};

	for (int i = 0; i < len; i++) {
		idx = random_in_range(0, 0, 36);
		key[i] = valid_chars[idx];
		val[len - i - 1] = toupper(key[i]);
	}

	return;
}

static void
perform_test(Rdb &rdb, int64_t nkeys, int interval)
{
	int retval = E_ok;
	int j = 0;
	char key[32];
	char val[32];
	PerformanceTimer start, end;

	for (int64_t i = 0; i < nkeys; ++i) {
		if (j == 0) {
			start.record();
		}

		gen_key_val(key, val, 32);
		retval = rdb.set(key, 32, val, 32);
		if (retval != E_ok) {
			break;
		}

		++j;
		if (j == interval) {
			end.record();
			fprintf(stdout, "%d,%" PRId64 "\n", j, end - start);
			j = 0;
		}

	}

	if ((retval == E_ok) && (j > 0)) {
		end.record();
		fprintf(stdout, "%d,%" PRId64 "\n", j, end - start);
		fflush(stdout);
		j = 0;
	}

	return;
}

int
main(int argc, const char **argv)
{
	op_t cmd = NIL;
	std::string path;
	std::string name;
	std::string key;
	std::string value;
	std::string logPath;
	int htSize = -1;
	int pgSize = -1;
	RdbOptions dbOpt;
	int vlen;
	char val[MAX_VALUE_LENGTH + 1];
	char prog[MAXPATHLEN + 1];
	bool testing = false;
	int64_t nkeys = 1000;
	int interval = 100;

	GetBaseName(prog, MAXPATHLEN + 1, argv[0], true);

	for (int i = 1; i < argc; ++i) {
		if (strcmp("-get", argv[i]) == 0) {
			cmd = GET;
		} else if (strcmp("-set", argv[i]) == 0) {
			cmd = SET;
		} else if (strcmp("-del", argv[i]) == 0) {
			cmd = DEL;
		} else if (strcmp("-path", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				path = argv[i];
			} else {
				fprintf(stderr, "missing argument to -path\n");
				return usage(prog);
			}
		} else if (strcmp("-name", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				name = argv[i];
			} else {
				fprintf(stderr, "missing argument to -name\n");
				return usage(prog);
			}
		} else if (strcmp("-htsize", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				htSize = atoi(argv[i]);
			} else {
				fprintf(stderr, "missing argument to -htsize\n");
				return usage(prog);
			}
		} else if (strcmp("-pgsize", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				pgSize = atoi(argv[i]);
			} else {
				fprintf(stderr, "missing argument to -pgsize\n");
				return usage(prog);
			}
		} else if (strcmp("-memusage", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				if (dbOpt.setMemoryUsage(atoi(argv[i])) != E_ok) {
					fprintf(stderr, "invalid memory usage (%s)\n",
						argv[i]);
					return 1;
				}
			} else {
				fprintf(stderr, "missing argument to -memusage\n");
				return usage(prog);
			}
		} else if (strcmp("-syncdf", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				if (atoi(argv[i]) == 0) {
					dbOpt.syncDataFile(false);
				} else {
					dbOpt.syncDataFile(true);
				}
			} else {
				fprintf(stderr, "missing argument to -syncdf\n");
				return usage(prog);
			}
		} else if (strcmp("-syncif", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				if (atoi(argv[i]) == 1) {
					dbOpt.syncIndexFile(true);
				} else {
					dbOpt.syncIndexFile(false);
				}
			} else {
				fprintf(stderr, "missing argument to -syncif\n");
				return usage(prog);
			}
		} else if (strcmp("-pgsize", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				pgSize = atoi(argv[i]);
			} else {
				fprintf(stderr, "missing argument to -pgsize\n");
				return usage(prog);
			}
		} else if (strcmp("-key", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				key = argv[i];
			} else {
				fprintf(stderr, "missing argument to -key\n");
				return usage(prog);
			}
		} else if (strcmp("-value", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				value = argv[i];
			} else {
				fprintf(stderr, "missing argument to -value\n");
				return usage(prog);
			}
		} else if (strcmp("-logpath", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				logPath = argv[i];
			} else {
				fprintf(stderr, "missing argument to -logpath\n");
				return usage(prog);
			}
		} else if (strcmp("-test", argv[i]) == 0) {
			testing = true;
		} else if (strcmp("-n", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				nkeys = atoll(argv[i]);
			} else {
				fprintf(stderr, "missing argument to -n\n");
				return usage(prog);
			}
		} else if (strcmp("-i", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				interval = atoi(argv[i]);
			} else {
				fprintf(stderr, "missing argument to -1\n");
				return usage(prog);
			}
		} else if (strcmp("-v", argv[i]) == 0) {
			TheVerbosity = true;
		} else {
			return usage(prog);
		}
	}

	if (!logPath.empty()) {
		TheLogger = new FileLogger(logPath.c_str(), TheVerbosity);
	}

	if (testing) {
		Rdb rdb(path, name, dbOpt);

		if (pgSize != -1)
			rdb.setKeyPageSize(pgSize);

		if (htSize != -1)
			rdb.setHashTableSize(htSize);

		int retval = rdb.open();
		if (retval == E_ok) {

			perform_test(rdb, nkeys, interval);

			rdb.close();
		}

		return retval;
	}

	if (cmd == NIL) {
		fprintf(stderr, "one of [-get|-set|-del] must be specified\n");
		return usage(prog);
	}

	if (path.empty()) {
		fprintf(stderr, "database path not specified\n");
		return usage(prog);
	}

	if (name.empty()) {
		fprintf(stderr, "database name not specified\n");
		return usage(prog);
	}

	if (key.empty()) {
		fprintf(stderr, "key not specified\n");
		return usage(prog);
	}

	if ((cmd == SET) && value.empty()) {
		fprintf(stderr, "value not specified\n");
		return usage(prog);
	}

	Rdb rdb(path, name, dbOpt);

	if (pgSize != -1)
		rdb.setKeyPageSize(pgSize);

	if (htSize != -1)
		rdb.setHashTableSize(htSize);

	int retval = rdb.open();
	if (retval == E_ok) {
		switch (cmd) {
			case GET:
				vlen = MAX_VALUE_LENGTH;
				retval = rdb.get(
						key.c_str(),
						(int)key.size(),
						val,
						&vlen);
				if (retval == E_ok) {
					val[vlen] = '\0';
					fprintf(stdout, "%s\n", val);
				} else if (retval == E_not_found) {
					fprintf(stdout, "%s not found\n", key.c_str());
					retval = E_ok;
				}
				break;

			case SET:
				retval = rdb.set(
						key.c_str(),
						(int)key.size(),
						value.c_str(),
						(int)value.size());
				if (retval == E_ok) {
					fprintf(stdout, "%s is set to %s\n",
						key.c_str(), value.c_str());
				}
				break;

			case DEL:
			default:
				retval = rdb.remove(key.c_str(), (int) key.size());
				if (retval == E_ok) {
					fprintf(stdout, "%s is removed\n",
						key.c_str());
				}
				break;
		}

		rdb.close();
	}

	if (retval != E_ok) {
		fprintf(stderr, "Operation failed with status %d\n", retval);
		retval = 1;
	}

	return retval;
}
<commit_msg>Changed permission.<commit_after>#include "common.h"
#include "log.h"
#include "util.h"
#include "perftimer.h"
#include "rdb/rdb.h"

extern Logger *TheLogger;
extern bool   TheVerbosity;

static int
usage(const char *prog)
{
	fprintf(stderr, "%s [-get|-set|-del] -path <db_path> -name <db_name>\n", prog);
	fprintf(stderr, "        -key <key> [-value <value>]\n");
	fprintf(stderr, "        [-htsize <hash_table_size>] [-pgsize <page_size>]\n");
	fprintf(stderr, "        [-memusage <%%_of_memory>] [-syncdf <0|1>]\n");
	fprintf(stderr, "        [-syncif <0|1>] [-logpath <log_path>]\n");
	return 1;
}

static int
random_in_range(int seed, int lo, int hi)
{
	if (lo == hi)
		return lo;

	if (seed != 0)
		srand(seed);

	return lo + (rand() % (hi - lo));
}

static void
gen_key_val(char *key, char *val, int len)
{
	int idx;
	char valid_chars[] = {
		'0', '1', '2', '3',
		'4', '5', '6', '7',
		'8', '9', 'a', 'b',
		'c', 'd', 'e', 'f',
		'g', 'h', 'i', 'j',
		'k', 'l', 'm', 'n',
		'o', 'p', 'q', 'r',
		's', 't', 'u', 'v',
		'w', 'x', 'y', 'z'
	};

	for (int i = 0; i < len; i++) {
		idx = random_in_range(0, 0, 36);
		key[i] = valid_chars[idx];
		val[len - i - 1] = toupper(key[i]);
	}

	return;
}

static void
perform_test(Rdb &rdb, int64_t nkeys, int interval)
{
	int retval = E_ok;
	int j = 0;
	char key[32];
	char val[32];
	PerformanceTimer start, end;

	for (int64_t i = 0; i < nkeys; ++i) {
		if (j == 0) {
			start.record();
		}

		gen_key_val(key, val, 32);
		retval = rdb.set(key, 32, val, 32);
		if (retval != E_ok) {
			break;
		}

		++j;
		if (j == interval) {
			end.record();
			fprintf(stdout, "%d,%" PRId64 "\n", j, end - start);
			j = 0;
		}

	}

	if ((retval == E_ok) && (j > 0)) {
		end.record();
		fprintf(stdout, "%d,%" PRId64 "\n", j, end - start);
		fflush(stdout);
		j = 0;
	}

	return;
}

int
main(int argc, const char **argv)
{
	op_t cmd = NIL;
	std::string path;
	std::string name;
	std::string key;
	std::string value;
	std::string logPath;
	int htSize = -1;
	int pgSize = -1;
	RdbOptions dbOpt;
	int vlen;
	char val[MAX_VALUE_LENGTH + 1];
	char prog[MAXPATHLEN + 1];
	bool testing = false;
	int64_t nkeys = 1000;
	int interval = 100;

	GetBaseName(prog, MAXPATHLEN + 1, argv[0], true);

	for (int i = 1; i < argc; ++i) {
		if (strcmp("-get", argv[i]) == 0) {
			cmd = GET;
		} else if (strcmp("-set", argv[i]) == 0) {
			cmd = SET;
		} else if (strcmp("-del", argv[i]) == 0) {
			cmd = DEL;
		} else if (strcmp("-path", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				path = argv[i];
			} else {
				fprintf(stderr, "missing argument to -path\n");
				return usage(prog);
			}
		} else if (strcmp("-name", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				name = argv[i];
			} else {
				fprintf(stderr, "missing argument to -name\n");
				return usage(prog);
			}
		} else if (strcmp("-htsize", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				htSize = atoi(argv[i]);
			} else {
				fprintf(stderr, "missing argument to -htsize\n");
				return usage(prog);
			}
		} else if (strcmp("-pgsize", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				pgSize = atoi(argv[i]);
			} else {
				fprintf(stderr, "missing argument to -pgsize\n");
				return usage(prog);
			}
		} else if (strcmp("-memusage", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				if (dbOpt.setMemoryUsage(atoi(argv[i])) != E_ok) {
					fprintf(stderr, "invalid memory usage (%s)\n",
						argv[i]);
					return 1;
				}
			} else {
				fprintf(stderr, "missing argument to -memusage\n");
				return usage(prog);
			}
		} else if (strcmp("-syncdf", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				if (atoi(argv[i]) == 0) {
					dbOpt.syncDataFile(false);
				} else {
					dbOpt.syncDataFile(true);
				}
			} else {
				fprintf(stderr, "missing argument to -syncdf\n");
				return usage(prog);
			}
		} else if (strcmp("-syncif", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				if (atoi(argv[i]) == 1) {
					dbOpt.syncIndexFile(true);
				} else {
					dbOpt.syncIndexFile(false);
				}
			} else {
				fprintf(stderr, "missing argument to -syncif\n");
				return usage(prog);
			}
		} else if (strcmp("-pgsize", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				pgSize = atoi(argv[i]);
			} else {
				fprintf(stderr, "missing argument to -pgsize\n");
				return usage(prog);
			}
		} else if (strcmp("-key", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				key = argv[i];
			} else {
				fprintf(stderr, "missing argument to -key\n");
				return usage(prog);
			}
		} else if (strcmp("-value", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				value = argv[i];
			} else {
				fprintf(stderr, "missing argument to -value\n");
				return usage(prog);
			}
		} else if (strcmp("-logpath", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				logPath = argv[i];
			} else {
				fprintf(stderr, "missing argument to -logpath\n");
				return usage(prog);
			}
		} else if (strcmp("-test", argv[i]) == 0) {
			testing = true;
		} else if (strcmp("-n", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				nkeys = atoll(argv[i]);
			} else {
				fprintf(stderr, "missing argument to -n\n");
				return usage(prog);
			}
		} else if (strcmp("-i", argv[i]) == 0) {
			++i;
			if (argv[i]) {
				interval = atoi(argv[i]);
			} else {
				fprintf(stderr, "missing argument to -1\n");
				return usage(prog);
			}
		} else if (strcmp("-v", argv[i]) == 0) {
			TheVerbosity = true;
		} else {
			return usage(prog);
		}
	}

	if (!logPath.empty()) {
		TheLogger = new FileLogger(logPath.c_str(), TheVerbosity);
	}

	if (testing) {
		Rdb rdb(path, name, dbOpt);

		if (pgSize != -1)
			rdb.setKeyPageSize(pgSize);

		if (htSize != -1)
			rdb.setHashTableSize(htSize);

		int retval = rdb.open();
		if (retval == E_ok) {

			perform_test(rdb, nkeys, interval);

			rdb.close();
		}

		return retval;
	}

	if (cmd == NIL) {
		fprintf(stderr, "one of [-get|-set|-del] must be specified\n");
		return usage(prog);
	}

	if (path.empty()) {
		fprintf(stderr, "database path not specified\n");
		return usage(prog);
	}

	if (name.empty()) {
		fprintf(stderr, "database name not specified\n");
		return usage(prog);
	}

	if (key.empty()) {
		fprintf(stderr, "key not specified\n");
		return usage(prog);
	}

	if ((cmd == SET) && value.empty()) {
		fprintf(stderr, "value not specified\n");
		return usage(prog);
	}

	Rdb rdb(path, name, dbOpt);

	if (pgSize != -1)
		rdb.setKeyPageSize(pgSize);

	if (htSize != -1)
		rdb.setHashTableSize(htSize);

	int retval = rdb.open();
	if (retval == E_ok) {
		switch (cmd) {
			case GET:
				vlen = MAX_VALUE_LENGTH;
				retval = rdb.get(
						key.c_str(),
						(int)key.size(),
						val,
						&vlen);
				if (retval == E_ok) {
					val[vlen] = '\0';
					fprintf(stdout, "%s\n", val);
				} else if (retval == E_not_found) {
					fprintf(stdout, "%s not found\n", key.c_str());
					retval = E_ok;
				}
				break;

			case SET:
				retval = rdb.set(
						key.c_str(),
						(int)key.size(),
						value.c_str(),
						(int)value.size());
				if (retval == E_ok) {
					fprintf(stdout, "%s is set to %s\n",
						key.c_str(), value.c_str());
				}
				break;

			case DEL:
			default:
				retval = rdb.remove(key.c_str(), (int) key.size());
				if (retval == E_ok) {
					fprintf(stdout, "%s is removed\n",
						key.c_str());
				}
				break;
		}

		rdb.close();
	}

	if (retval != E_ok) {
		fprintf(stderr, "Operation failed with status %d\n", retval);
		retval = 1;
	}

	return retval;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <tools/AutomatedTestSuite.h>

#include "SynthMark.h"
#include "synth/IncludeMeOnce.h"
#include "synth/Synthesizer.h"
#include "tools/ClockRampHarness.h"
#include "tools/JitterMarkHarness.h"
#include "tools/ITestHarness.h"
#include "tools/LatencyMarkHarness.h"
#include "tools/TimingAnalyzer.h"
#include "tools/UtilizationMarkHarness.h"
#include "tools/UtilizationSeriesHarness.h"
#include "tools/VirtualAudioSink.h"
#include "tools/VoiceMarkHarness.h"

constexpr char kDefaultTestCode         = 'v';
constexpr int  kDefaultSeconds          = 10;
constexpr int  kDefaultFramesPerBurst   = 96; // 2 msec at 48000 Hz
constexpr int  kDefaultNumVoices        = 8;
constexpr int  kDefaultNoteOnDelay      = 0;
constexpr int  kDefaultPercentCpu       = 50;

void usage(const char *name) {
    printf("SynthMark version %d.%d\n", SYNTHMARK_MAJOR_VERSION, SYNTHMARK_MINOR_VERSION);
    printf("%s -t{test} -n{numVoices} -d{noteOnDelay} -p{percentCPU} -r{sampleRate}"
           " -s{seconds} -b{burstSize} -c{cpuAffinity}\n", name);
    printf("    -t{test}, v=voice, l=latency, j=jitter, u=utilization"
           ", s=series_util, c=clock_ramp, default is %c\n",
           kDefaultTestCode);
    printf("    -n{numVoices} to render, default = %d\n", kDefaultNumVoices);
    printf("    -N{numVoices} to render for toggling high load, LatencyMark only\n");
    printf("    -m{voicesMode} algorithm to choose the number of voices in the range\n"
           "      [-n, -N]. This value can be 'l' for a linear increment, 'r' for a\n"
           "      random choice, or 's' to switch between -n and -N. default = s\n");
    printf("    -d{noteOnDelay} seconds to delay the first NoteOn, default = %d\n",
           kDefaultNoteOnDelay);
    printf("    -p{percentCPU} target load, default = %d\n", kDefaultPercentCpu);
    printf("    -r{sampleRate} should be typical, 44100, 48000, etc. default is %d\n",
           kSynthmarkSampleRate);
    printf("    -s{seconds} to run the test, latencyMark may take longer, default is %d\n",
           kDefaultSeconds);
    printf("    -b{burstSize} frames read by virtual hardware at one time, default = %d\n",
           kDefaultFramesPerBurst);
    printf("    -c{cpuAffinity} index of CPU to run on, default = UNSPECIFIED\n");
    printf("    -a{enable} 0 for normal thread, 1 for audio callback, default = 1\n");
}

#define TEXT_ERROR "ERROR: "

int main(int argc, char **argv)
{
    int32_t percentCpu = kDefaultPercentCpu;
    int32_t sampleRate = kSynthmarkSampleRate;
    int32_t framesPerBurst = kDefaultFramesPerBurst;
    int32_t numSeconds = kDefaultSeconds;
    int32_t numVoices = kDefaultNumVoices;
    int32_t numVoicesHigh = 0;
    int32_t numSecondsDelayNoteOn = kDefaultNoteOnDelay;
    int32_t cpuAffinity = SYNTHMARK_CPU_UNSPECIFIED;
    bool    useAudioThread = true;
    VoicesMode voicesMode = VOICES_UNDEFINED;
    char testCode = kDefaultTestCode;

    ITestHarness *harness = nullptr;

    SynthMarkResult result;
    VirtualAudioSink audioSink;

    printf("# SynthMark V%d.%d\n", SYNTHMARK_MAJOR_VERSION, SYNTHMARK_MINOR_VERSION);

    // Parse command line arguments.
    for (int iarg = 1; iarg < argc; iarg++) {
        char * arg = argv[iarg];
        if (arg[0] == '-') {
            switch(arg[1]) {
                case 'a':
                    useAudioThread = (atoi(&arg[2]) != 0);
                    break;
                case 'c':
                    cpuAffinity = atoi(&arg[2]);
                    break;
                case 'p':
                    percentCpu = atoi(&arg[2]);
                    break;
                case 'n':
                    numVoices = atoi(&arg[2]); // TODO check for invalid input like -nz
                    break;
                case 'N':
                    numVoicesHigh = atoi(&arg[2]);
                    break;
                case 'd':
                    numSecondsDelayNoteOn = atoi(&arg[2]);
                    break;
                case 'r':
                    sampleRate = atoi(&arg[2]);
                    break;
                case 'm':
                    switch (arg[2]) {
                        case 'r':
                            voicesMode = VOICES_RANDOM;
                            break;
                        case 'l':
                            voicesMode = VOICES_LINEAR_LOOP;
                            break;
                        case 's':
                        default:
                            voicesMode = VOICES_SWITCH;
                            break;
                    }
                    break;
                case 's':
                    numSeconds = atoi(&arg[2]);
                    break;
                case 'b':
                    framesPerBurst = atoi(&arg[2]);
                    break;
                case 't':
                    testCode = arg[2];
                    break;
                case 'h': // help
                case '?': // help
                    usage(argv[0]);
                    return 0;
                default:
                    printf(TEXT_ERROR "Unrecognized switch: %s\n", arg);
                    usage(argv[0]);
                    return 1;
            }
        } else {
            printf(TEXT_ERROR "Unrecognized argument: %s\n", arg);
            usage(argv[0]);
            return 1;
        }
    }
    if (percentCpu < 1 || percentCpu > 100) {
        printf(TEXT_ERROR "Invalid percent CPU = %d\n", percentCpu);
        usage(argv[0]);
        return 1;
    }
    if ((numVoices < 1 && numVoicesHigh <= 0)
        || numVoices < 0
        || numVoices > kSynthmarkMaxVoices) {
        printf(TEXT_ERROR "Invalid num voices = %d\n", numVoices);
        usage(argv[0]);
        return 1;
    }
    if (numVoicesHigh != 0 && numVoicesHigh < numVoices) {
        printf(TEXT_ERROR "Invalid num voices high = %d\n", numVoicesHigh);
        usage(argv[0]);
        return 1;
    }
    if (voicesMode != VOICES_UNDEFINED && numVoicesHigh == 0) {
        printf(TEXT_ERROR "-N must be set when using -m\n");
        usage(argv[0]);
        return 1;
    }
    if (numSeconds < 1) {
        printf(TEXT_ERROR "Invalid duration in seconds = %d\n", numSeconds);
        usage(argv[0]);
        return 1;
    }
    if (numSecondsDelayNoteOn < 0 || numSecondsDelayNoteOn > numSeconds){
        printf(TEXT_ERROR "Invalid delay for note on = %d\n", numSecondsDelayNoteOn);
        return 1;
    }
    if (framesPerBurst < 4) {
        printf(TEXT_ERROR "Block size too small = %d\n", framesPerBurst);
        usage(argv[0]);
        return 1;
    }

    audioSink.setRequestedCpu(cpuAffinity);

    // Create a test harness and set the parameters.
    switch(testCode) {
        case 'v':
            {
                VoiceMarkHarness *voiceHarness = new VoiceMarkHarness(&audioSink, &result);
                voiceHarness->setTargetCpuLoad(percentCpu * 0.01);
                voiceHarness->setInitialVoiceCount(numVoices);
                harness = voiceHarness;
            }
            break;

        case 'l':
            {
                LatencyMarkHarness *latencyHarness = new LatencyMarkHarness(&audioSink, &result);
                latencyHarness->setNumVoicesHigh(numVoicesHigh);
                latencyHarness->setVoicesMode(voicesMode);
                harness = latencyHarness;
            }
            break;

        case 'j':
            {
                JitterMarkHarness *jitterHarness = new JitterMarkHarness(&audioSink, &result);
                jitterHarness->setNumVoicesHigh(numVoicesHigh);
                jitterHarness->setVoicesMode(voicesMode);
                harness = jitterHarness;
            }
            break;

        case 'c':
            {
                ClockRampHarness *clockHarness = new ClockRampHarness(&audioSink, &result);
                clockHarness->setNumVoicesHigh(numVoicesHigh);
                clockHarness->setVoicesMode(voicesMode);
                harness = clockHarness;
            }
            break;

        case 'u':
            {
                UtilizationMarkHarness *utilizationHarness
                        = new UtilizationMarkHarness(&audioSink, &result);
                harness = utilizationHarness;
            }
            break;

        case 'a':
            {
                AutomatedTestSuite *testSuite = new AutomatedTestSuite(&audioSink, &result);
                harness = testSuite;
            }
            break;

        case 's':
            {
                UtilizationSeriesHarness *seriesHarness
                        = new UtilizationSeriesHarness(&audioSink, &result);
                seriesHarness->setNumVoicesHigh(numVoicesHigh);
                harness = seriesHarness;
            }
            break;

        default:
            printf(TEXT_ERROR "unrecognized testCode = %c\n", testCode);
            usage(argv[0]);
            return 1;
            break;
    }
    harness->setNumVoices(numVoices);
    harness->setDelayNoteOnSeconds(numSecondsDelayNoteOn);
    harness->setThreadType(useAudioThread
                           ? HostThreadFactory::ThreadType::Audio
                           : HostThreadFactory::ThreadType::Default);

    // Print specified parameters.
    printf("  test.name          = %s\n",  harness->getName());
    printf("  num.voices         = %6d\n", numVoices);
    printf("  num.voices.high    = %6d\n", numVoicesHigh);
    printf("  voices.mode        = %6d\n", voicesMode);
    printf("  note.on.delay      = %6d\n", numSecondsDelayNoteOn);
    printf("  target.cpu.percent = %6d\n", percentCpu);
    printf("  frames.per.burst   = %6d\n", framesPerBurst);
    printf("  msec.per.burst     = %6.2f\n", ((framesPerBurst * 1000.0) / sampleRate));
    printf("  cpu.affinity       = %6d\n", cpuAffinity);
    printf("  cpu.count          = %6d\n", HostTools::getCpuCount());
    printf("  audio.thread       = %6d\n", (useAudioThread ? 1 : 0));
    printf("# wait at least %d seconds for benchmark to complete\n", numSeconds);
    fflush(stdout);

    // Run the benchmark.
    harness->runTest(sampleRate, framesPerBurst, numSeconds);

    // Print the test results.
    printf(TEXT_RESULTS_BEGIN "\n");
    std::cout << result.getResultMessage();
    printf(TEXT_RESULTS_END "\n");
    printf("# Benchmark complete.\n");

    return result.getResultCode();
}
<commit_msg>Check for invalid numeric arguments on command line.<commit_after>/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <stdlib.h>
#include <tools/AutomatedTestSuite.h>

#include "SynthMark.h"
#include "synth/IncludeMeOnce.h"
#include "synth/Synthesizer.h"
#include "tools/ClockRampHarness.h"
#include "tools/JitterMarkHarness.h"
#include "tools/ITestHarness.h"
#include "tools/LatencyMarkHarness.h"
#include "tools/TimingAnalyzer.h"
#include "tools/UtilizationMarkHarness.h"
#include "tools/UtilizationSeriesHarness.h"
#include "tools/VirtualAudioSink.h"
#include "tools/VoiceMarkHarness.h"

constexpr char kDefaultTestCode         = 'v';
constexpr int  kDefaultSeconds          = 10;
constexpr int  kDefaultFramesPerBurst   = 96; // 2 msec at 48000 Hz
constexpr int  kDefaultNumVoices        = 8;
constexpr int  kDefaultNoteOnDelay      = 0;
constexpr int  kDefaultPercentCpu       = 50;

void usage(const char *name) {
    printf("SynthMark version %d.%d\n", SYNTHMARK_MAJOR_VERSION, SYNTHMARK_MINOR_VERSION);
    printf("%s -t{test} -n{numVoices} -d{noteOnDelay} -p{percentCPU} -r{sampleRate}"
           " -s{seconds} -b{burstSize} -c{cpuAffinity}\n", name);
    printf("    -t{test}, v=voice, l=latency, j=jitter, u=utilization"
           ", s=series_util, c=clock_ramp, default is %c\n",
           kDefaultTestCode);
    printf("    -n{numVoices} to render, default = %d\n", kDefaultNumVoices);
    printf("    -N{numVoices} to render for toggling high load, LatencyMark only\n");
    printf("    -m{voicesMode} algorithm to choose the number of voices in the range\n"
           "      [-n, -N]. This value can be 'l' for a linear increment, 'r' for a\n"
           "      random choice, or 's' to switch between -n and -N. default = s\n");
    printf("    -d{noteOnDelay} seconds to delay the first NoteOn, default = %d\n",
           kDefaultNoteOnDelay);
    printf("    -p{percentCPU} target load, default = %d\n", kDefaultPercentCpu);
    printf("    -r{sampleRate} should be typical, 44100, 48000, etc. default is %d\n",
           kSynthmarkSampleRate);
    printf("    -s{seconds} to run the test, latencyMark may take longer, default is %d\n",
           kDefaultSeconds);
    printf("    -b{burstSize} frames read by virtual hardware at one time, default = %d\n",
           kDefaultFramesPerBurst);
    printf("    -c{cpuAffinity} index of CPU to run on, default = UNSPECIFIED\n");
    printf("    -a{enable} 0 for normal thread, 1 for audio callback, default = 1\n");
}

#define TEXT_ERROR "ERROR: "

/**
 * Convert the input string to a positive integer.
 * @param input
 * @param message
 * @return -1 if an invalid number and print the message
 */
long stringToPositiveInteger(const char *input, const char *message) {
    char *end;
    long result = strtol(input,	&end, 10);
    if (errno || (*end != '\0')) {
        printf(TEXT_ERROR "argument %s invalid : %s\n", input, message);
        result = -1;
    }
    return result;
}

int main(int argc, char **argv)
{
    int32_t percentCpu = kDefaultPercentCpu;
    int32_t sampleRate = kSynthmarkSampleRate;
    int32_t framesPerBurst = kDefaultFramesPerBurst;
    int32_t numSeconds = kDefaultSeconds;
    int32_t numVoices = kDefaultNumVoices;
    int32_t numVoicesHigh = 0;
    int32_t numSecondsDelayNoteOn = kDefaultNoteOnDelay;
    int32_t cpuAffinity = SYNTHMARK_CPU_UNSPECIFIED;
    bool    useAudioThread = true;
    VoicesMode voicesMode = VOICES_UNDEFINED;
    char testCode = kDefaultTestCode;

    ITestHarness *harness = nullptr;

    SynthMarkResult result;
    VirtualAudioSink audioSink;

    printf("# SynthMark V%d.%d\n", SYNTHMARK_MAJOR_VERSION, SYNTHMARK_MINOR_VERSION);

    // Parse command line arguments.
    for (int iarg = 1; iarg < argc; iarg++) {
        char * arg = argv[iarg];
        const char *errstr;
        int temp;
        if (arg[0] == '-') {
            switch(arg[1]) {
                case 'a':
                    temp = stringToPositiveInteger(&arg[2], "-a");
                    if (temp < 0) return 1;
                    useAudioThread = (temp > 0);
                    break;
                case 'c':
                    if ((cpuAffinity = stringToPositiveInteger(&arg[2], "-c")) < 0) return 1;
                    break;
                case 'p':
                    if ((percentCpu = stringToPositiveInteger(&arg[2], "-p")) < 0) return 1;
                    break;
                case 'n':
                    if ((numVoices = stringToPositiveInteger(&arg[2], "-n")) < 0) return 1;
                    break;
                case 'N':
                    if ((numVoicesHigh = stringToPositiveInteger(&arg[2], "-N")) < 0) return 1;
                    break;
                case 'd':
                    if ((numSecondsDelayNoteOn = stringToPositiveInteger(&arg[2], "-d")) < 0) return 1;
                    break;
                case 'r':
                    if ((sampleRate = stringToPositiveInteger(&arg[2], "-r")) < 0) return 1;
                    break;
                case 'm':
                    switch (arg[2]) {
                        case 'r':
                            voicesMode = VOICES_RANDOM;
                            break;
                        case 'l':
                            voicesMode = VOICES_LINEAR_LOOP;
                            break;
                        case 's':
                        default:
                            voicesMode = VOICES_SWITCH;
                            break;
                    }
                    break;
                case 's':
                    if ((numSeconds = stringToPositiveInteger(&arg[2], "-s")) < 0) return 1;
                    break;
                case 'b':
                    if ((framesPerBurst = stringToPositiveInteger(&arg[2], "-b")) < 0) return 1;
                    break;
                case 't':
                    testCode = arg[2];
                    break;
                case 'h': // help
                case '?': // help
                    usage(argv[0]);
                    return 0;
                default:
                    printf(TEXT_ERROR "Unrecognized switch: %s\n", arg);
                    usage(argv[0]);
                    return 1;
            }
        } else {
            printf(TEXT_ERROR "Unrecognized argument: %s\n", arg);
            usage(argv[0]);
            return 1;
        }
    }
    if (percentCpu < 1 || percentCpu > 100) {
        printf(TEXT_ERROR "Invalid percent CPU = %d\n", percentCpu);
        usage(argv[0]);
        return 1;
    }
    if ((numVoices < 1 && numVoicesHigh <= 0)
        || numVoices < 0
        || numVoices > kSynthmarkMaxVoices) {
        printf(TEXT_ERROR "Invalid num voices = %d\n", numVoices);
        usage(argv[0]);
        return 1;
    }
    if (numVoicesHigh != 0 && numVoicesHigh < numVoices) {
        printf(TEXT_ERROR "Invalid num voices high = %d\n", numVoicesHigh);
        usage(argv[0]);
        return 1;
    }
    if (voicesMode != VOICES_UNDEFINED && numVoicesHigh == 0) {
        printf(TEXT_ERROR "-N must be set when using -m\n");
        usage(argv[0]);
        return 1;
    }
    if (numSeconds < 1) {
        printf(TEXT_ERROR "Invalid duration in seconds = %d\n", numSeconds);
        usage(argv[0]);
        return 1;
    }
    if (numSecondsDelayNoteOn < 0 || numSecondsDelayNoteOn > numSeconds){
        printf(TEXT_ERROR "Invalid delay for note on = %d\n", numSecondsDelayNoteOn);
        return 1;
    }
    if (framesPerBurst < 4) {
        printf(TEXT_ERROR "Block size too small = %d\n", framesPerBurst);
        usage(argv[0]);
        return 1;
    }

    audioSink.setRequestedCpu(cpuAffinity);

    // Create a test harness and set the parameters.
    switch(testCode) {
        case 'v':
            {
                VoiceMarkHarness *voiceHarness = new VoiceMarkHarness(&audioSink, &result);
                voiceHarness->setTargetCpuLoad(percentCpu * 0.01);
                voiceHarness->setInitialVoiceCount(numVoices);
                harness = voiceHarness;
            }
            break;

        case 'l':
            {
                LatencyMarkHarness *latencyHarness = new LatencyMarkHarness(&audioSink, &result);
                latencyHarness->setNumVoicesHigh(numVoicesHigh);
                latencyHarness->setVoicesMode(voicesMode);
                harness = latencyHarness;
            }
            break;

        case 'j':
            {
                JitterMarkHarness *jitterHarness = new JitterMarkHarness(&audioSink, &result);
                jitterHarness->setNumVoicesHigh(numVoicesHigh);
                jitterHarness->setVoicesMode(voicesMode);
                harness = jitterHarness;
            }
            break;

        case 'c':
            {
                ClockRampHarness *clockHarness = new ClockRampHarness(&audioSink, &result);
                clockHarness->setNumVoicesHigh(numVoicesHigh);
                clockHarness->setVoicesMode(voicesMode);
                harness = clockHarness;
            }
            break;

        case 'u':
            {
                UtilizationMarkHarness *utilizationHarness
                        = new UtilizationMarkHarness(&audioSink, &result);
                harness = utilizationHarness;
            }
            break;

        case 'a':
            {
                AutomatedTestSuite *testSuite = new AutomatedTestSuite(&audioSink, &result);
                harness = testSuite;
            }
            break;

        case 's':
            {
                UtilizationSeriesHarness *seriesHarness
                        = new UtilizationSeriesHarness(&audioSink, &result);
                seriesHarness->setNumVoicesHigh(numVoicesHigh);
                harness = seriesHarness;
            }
            break;

        default:
            printf(TEXT_ERROR "unrecognized testCode = %c\n", testCode);
            usage(argv[0]);
            return 1;
            break;
    }
    harness->setNumVoices(numVoices);
    harness->setDelayNoteOnSeconds(numSecondsDelayNoteOn);
    harness->setThreadType(useAudioThread
                           ? HostThreadFactory::ThreadType::Audio
                           : HostThreadFactory::ThreadType::Default);

    // Print specified parameters.
    printf("  test.name          = %s\n",  harness->getName());
    printf("  num.voices         = %6d\n", numVoices);
    printf("  num.voices.high    = %6d\n", numVoicesHigh);
    printf("  voices.mode        = %6d\n", voicesMode);
    printf("  note.on.delay      = %6d\n", numSecondsDelayNoteOn);
    printf("  target.cpu.percent = %6d\n", percentCpu);
    printf("  frames.per.burst   = %6d\n", framesPerBurst);
    printf("  msec.per.burst     = %6.2f\n", ((framesPerBurst * 1000.0) / sampleRate));
    printf("  cpu.affinity       = %6d\n", cpuAffinity);
    printf("  cpu.count          = %6d\n", HostTools::getCpuCount());
    printf("  audio.thread       = %6d\n", (useAudioThread ? 1 : 0));
    printf("# wait at least %d seconds for benchmark to complete\n", numSeconds);
    fflush(stdout);

    // Run the benchmark.
    harness->runTest(sampleRate, framesPerBurst, numSeconds);

    // Print the test results.
    printf(TEXT_RESULTS_BEGIN "\n");
    std::cout << result.getResultMessage();
    printf(TEXT_RESULTS_END "\n");
    printf("# Benchmark complete.\n");

    return result.getResultCode();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <vector>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <boost/tokenizer.hpp>
#include <list>

using namespace std;
using namespace boost;

bool do_exec(vector<char*> &arg)
{
	int status;
	int pid = fork();
	//error with fork
	if(pid < 0)
	{
		perror("fork()");
		exit(1);
	}
	//child process
	else if(pid == 0)
	{
		if(-1 == execvp(arg[0], arg.data()))//insert arg
		{
			perror("execvp()");
			_exit(1);
		}
		_exit(0);
	}
	//parent process
	else if(pid > 0)
	{
		if(-1 == waitpid(-1, &status, 0))
		{
			perror("waitpid()");
			exit(1);
		}
		if(status != 0)
		{
			return false;
		}
	}
	return true;
}

int main()
{
	char hostname[256];
	gethostname(hostname, 256);
	if(gethostname(hostname, 256) == -1)
	{
		perror("hostname()");
	}
	if(getlogin() == NULL)
	{
		perror("getlogin()");
	}
	while(1)
	{
		string input_cmd;
		list<string> parse_list;
		bool conn_semi_c = false;
		bool conn_and = false;
		bool conn_or = false;
		bool exec_check = false;

		//outputs user login and host name along with command prompt
		cout << getlogin() << "@" << hostname << "$ ";

		//takes in commands
		getline(cin, input_cmd);

		//parse command input
		char_separator<char> delim(" \t","#;&|");
		tokenizer< char_separator<char> > mytok(input_cmd, delim);
		for(auto it = mytok.begin(); it != mytok.end(); ++it)
		{
			parse_list.push_back(*it);
		}

		vector<string> cmd_line;
		vector<char*> arg(parse_list.size() + 1);
		list<string> cmd_list;

		string exit_flag = parse_list.front();

		//push only the commands, saving connectors in list
		while(!(parse_list.empty()) && parse_list.front() != "#" &&
				parse_list.front() != ";" && parse_list.front() != "&" &&
				parse_list.front() != "|")
		{
			cmd_line.push_back(parse_list.front());
			cmd_list.push_back(parse_list.front());
			parse_list.pop_front();
		}

		for(unsigned int i = 0; i != cmd_line.size(); ++i)
		{
			arg[i] = &cmd_line[i][0];
		}

		//make it so that anything after exit will still exit
		//
		//if exit entered, exit shell
		if(exit_flag == "exit")
		{
			exit(0);
		}

		while(!(cmd_list.empty()))
		{

			if(parse_list.front() == "#")
			{
				cmd_list.clear();
				exec_check = do_exec(arg);
			}
			else if(parse_list.front() == ";")
			{
				conn_semi_c = true;
				parse_list.pop_front();
			}
			else if(parse_list.front() == "&")
			{
				parse_list.pop_front();
				if(parse_list.front() == "&")
				{
					conn_and = true;
					parse_list.pop_front();
				}
				else{
					conn_and = false;
				}
			}
			else if(parse_list.front() == "|")
			{
				parse_list.pop_front();
				if(parse_list.front() == "|")
				{
					conn_or = true;
					parse_list.pop_front();
				}
				else{
					conn_or = false;
				}
			}
			else{
				exec_check = do_exec(arg);
				cmd_list.pop_front();
				break;
			}

			if(conn_semi_c == true)
			{
				exec_check = do_exec(arg);
				cmd_list.pop_front();
			}
			else if(conn_and == true && exec_check == true)
			{
				exec_check = do_exec(arg);
				cmd_list.pop_front();
			}
			else if(conn_or == true && exec_check == false)
			{
				exec_check = do_exec(arg);
				cmd_list.pop_front();
			}

		}

	}

	return 0;
}
<commit_msg>fixed some perrors<commit_after>#include <iostream>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <vector>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <boost/tokenizer.hpp>
#include <list>

using namespace std;
using namespace boost;

bool do_exec(vector<char*> &arg)
{
	int status;
	int pid = fork();
	//error with fork
	if(pid < 0)
	{
		perror("fork()");
		exit(1);
	}
	//child process
	else if(pid == 0)
	{
		if(-1 == execvp(arg[0], arg.data()))//insert arg
		{
			perror("execvp()");
			_exit(1);
		}
		_exit(0);
	}
	//parent process
	else if(pid > 0)
	{
		if(-1 == waitpid(-1, &status, 0))
		{
			perror("waitpid()");
			exit(1);
		}
		if(status != 0)
		{
			return false;
		}
	}
	return true;
}

int main()
{
	char hostname[256];
	char *login_info;
	if(gethostname(hostname, 256) == -1)
	{
		perror("hostname()");
	}

	login_info = getlogin();
	if(login_info == NULL)
	{
		perror("getlogin()");
	}
	while(1)
	{
		string input_cmd;
		list<string> parse_list;
		bool conn_semi_c = false;
		bool conn_and = false;
		bool conn_or = false;
		bool exec_check = false;

		//outputs user login and host name along with command prompt
		cout << login_info << "@" << hostname << "$ ";

		//takes in commands
		getline(cin, input_cmd);

		//parse command input
		char_separator<char> delim(" \t","#;&|");
		tokenizer< char_separator<char> > mytok(input_cmd, delim);
		for(auto it = mytok.begin(); it != mytok.end(); ++it)
		{
			parse_list.push_back(*it);
		}

		vector<string> cmd_line;
		vector<char*> arg(parse_list.size() + 1);
		list<string> cmd_list;

		string exit_flag = parse_list.front();

		//push only the commands, saving connectors in list
		while(!(parse_list.empty()) && parse_list.front() != "#" &&
				parse_list.front() != ";" && parse_list.front() != "&" &&
				parse_list.front() != "|")
		{
			cmd_line.push_back(parse_list.front());
			cmd_list.push_back(parse_list.front());
			parse_list.pop_front();
		}

		for(unsigned int i = 0; i != cmd_line.size(); ++i)
		{
			arg[i] = &cmd_line[i][0];
		}

		//make it so that anything after exit will still exit
		//
		//if exit entered, exit shell
		if(exit_flag == "exit")
		{
			exit(0);
		}

		while(!(cmd_list.empty()))
		{

			if(parse_list.front() == "#")
			{
				cmd_list.clear();
				exec_check = do_exec(arg);
			}
			else if(parse_list.front() == ";")
			{
				conn_semi_c = true;
				parse_list.pop_front();
			}
			else if(parse_list.front() == "&")
			{
				parse_list.pop_front();
				if(parse_list.front() == "&")
				{
					conn_and = true;
					parse_list.pop_front();
				}
				else{
					conn_and = false;
					cout << "Error: Invalid connector." << endl;
					break;
				}
			}
			else if(parse_list.front() == "|")
			{
				parse_list.pop_front();
				if(parse_list.front() == "|")
				{
					conn_or = true;
					parse_list.pop_front();
				}
				else{
					conn_or = false;
					cout << "Error: Invalid connector." << endl;
					break;
				}
			}
			else{
				exec_check = do_exec(arg);
				cmd_list.pop_front();
				break;
			}

			if(conn_semi_c == true)
			{
				exec_check = do_exec(arg);
				cmd_list.pop_front();
			}
			if(conn_and == true && exec_check == true)
			{
				exec_check = do_exec(arg);
				cmd_list.pop_front();
			}
			if(conn_or == true && exec_check == false)
			{
				exec_check = do_exec(arg);
				cmd_list.pop_front();
			}

		}

	}

	return 0;
}
<|endoftext|>


<commit_before><commit_msg>Delete givestake.cpp<commit_after><|endoftext|>


<commit_before>// glfw_main.cpp

#include <GL/glew.h>

#if defined(_WIN32)
#  include <Windows.h>
#  define GLFW_EXPOSE_NATIVE_WIN32
#  define GLFW_EXPOSE_NATIVE_WGL
#elif defined(__linux__)
#  include <X11/X.h>
#  include <X11/extensions/Xrandr.h>
#  define GLFW_EXPOSE_NATIVE_X11
#  define GLFW_EXPOSE_NATIVE_GLX
#endif

#include <GLFW/glfw3.h>

#if !defined(__APPLE__)
#  include <GLFW/glfw3native.h>
#endif

#include <glm/gtc/type_ptr.hpp>

#include <stdio.h>
#include <string.h>
#include <sstream>

// Set VSync is framework-dependent and has to come before the include
///@param state 0=off, 1=on, -1=adaptive
// Set vsync for both contexts.
static void SetVsync(int state)
{
    glfwSwapInterval(state);
}

static void ErrorCallback(int p_Error, const char* p_Description)
{
    (void)p_Error;
    (void)p_Description;
}

void keyboard(GLFWwindow* pWindow, int key, int codes, int action, int mods)
{
    (void)pWindow;
    (void)codes;

    if (action == GLFW_PRESS)
    {
    switch (key)
    {
        default:
            break;

        case GLFW_KEY_ESCAPE:
            glfwTerminate();
            break;
        }
    }
}

void resize(GLFWwindow* pWindow, int w, int h)
{
    (void)pWindow;
}

int main(int argc, char** argv)
{
    bool useOpenGLCoreContext = false;

#ifdef USE_CORE_CONTEXT
    useOpenGLCoreContext = true;
#endif

#ifdef _LINUX
    // Linux driver seems to be lagging a bit
    useOpenGLCoreContext = false;
#endif

    // Command line options
    for (int i=0; i<argc; ++i)
    {
        const std::string a = argv[i];
        if (!a.compare("-core"))
        {
            useOpenGLCoreContext = true;
        }
        else if (!a.compare("-compat"))
        {
            useOpenGLCoreContext = false;
        }
    }

    GLFWwindow* l_Window = NULL;
    glfwSetErrorCallback(ErrorCallback);
    if (!glfwInit())
    {
        exit(EXIT_FAILURE);
    }

#ifndef _LINUX
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
#  if defined(_MACOS)
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
#  else
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
#  endif
#endif //ndef _LINUX
    if (useOpenGLCoreContext)
    {
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    }
    else
    {
#ifndef _LINUX
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);
#endif
    }

    glfwWindowHint(GLFW_SAMPLES, 0);
    l_Window = glfwCreateWindow(800, 600, "kinderegg", NULL, NULL);
    if (!l_Window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(l_Window);
    glfwSetWindowSizeCallback(l_Window, resize);
    glfwSetKeyCallback(l_Window, keyboard);

    glfwMakeContextCurrent(l_Window);

    // Don't forget to initialize Glew, turn glewExperimental on to
    // avoid problems fetching function pointers...
    glewExperimental = GL_TRUE;
    const GLenum l_Result = glewInit();
    if (l_Result != GLEW_OK)
    {
        exit(EXIT_FAILURE);
    }

    while (!glfwWindowShouldClose(l_Window))
    {
        glfwPollEvents();

        glClearColor(0.f, 1.f, 0.f, 1.f);
        glClear(GL_COLOR_BUFFER_BIT);
        glfwSwapBuffers(l_Window);
    }

    glfwDestroyWindow(l_Window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
<commit_msg>Get a simple triangle drawing in the window.<commit_after>// glfw_main.cpp

#include <GL/glew.h>

#if defined(_WIN32)
#  include <Windows.h>
#  define GLFW_EXPOSE_NATIVE_WIN32
#  define GLFW_EXPOSE_NATIVE_WGL
#elif defined(__linux__)
#  include <X11/X.h>
#  include <X11/extensions/Xrandr.h>
#  define GLFW_EXPOSE_NATIVE_X11
#  define GLFW_EXPOSE_NATIVE_GLX
#endif

#include <GLFW/glfw3.h>

#if !defined(__APPLE__)
#  include <GLFW/glfw3native.h>
#endif

#include <glm/gtc/type_ptr.hpp>

#include <stdio.h>
#include <string.h>
#include <sstream>

// Set VSync is framework-dependent and has to come before the include
///@param state 0=off, 1=on, -1=adaptive
// Set vsync for both contexts.
static void SetVsync(int state)
{
    glfwSwapInterval(state);
}

static void ErrorCallback(int p_Error, const char* p_Description)
{
    (void)p_Error;
    (void)p_Description;
}

void keyboard(GLFWwindow* pWindow, int key, int codes, int action, int mods)
{
    (void)pWindow;
    (void)codes;

    if (action == GLFW_PRESS)
    {
    switch (key)
    {
        default:
            break;

        case GLFW_KEY_ESCAPE:
            glfwTerminate();
            break;
        }
    }
}

void resize(GLFWwindow* pWindow, int w, int h)
{
    (void)pWindow;
}

int main(int argc, char** argv)
{
    bool useOpenGLCoreContext = false;

#ifdef USE_CORE_CONTEXT
   // useOpenGLCoreContext = true;
#endif

#ifdef _LINUX
    // Linux driver seems to be lagging a bit
    useOpenGLCoreContext = false;
#endif

    // Command line options
    for (int i=0; i<argc; ++i)
    {
        const std::string a = argv[i];
        if (!a.compare("-core"))
        {
            useOpenGLCoreContext = true;
        }
        else if (!a.compare("-compat"))
        {
            useOpenGLCoreContext = false;
        }
    }

    GLFWwindow* l_Window = NULL;
    glfwSetErrorCallback(ErrorCallback);
    if (!glfwInit())
    {
        exit(EXIT_FAILURE);
    }

#ifndef _LINUX
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
#  if defined(_MACOS)
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
#  else
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
#  endif
#endif //ndef _LINUX
    if (useOpenGLCoreContext)
    {
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    }
    else
    {
#ifndef _LINUX
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);
#endif
    }

    glfwWindowHint(GLFW_SAMPLES, 0);
    l_Window = glfwCreateWindow(800, 600, "kinderegg", NULL, NULL);
    if (!l_Window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(l_Window);
    glfwSetWindowSizeCallback(l_Window, resize);
    glfwSetKeyCallback(l_Window, keyboard);

    glfwMakeContextCurrent(l_Window);

    // Don't forget to initialize Glew, turn glewExperimental on to
    // avoid problems fetching function pointers...
    glewExperimental = GL_TRUE;
    const GLenum l_Result = glewInit();
    if (l_Result != GLEW_OK)
    {
        exit(EXIT_FAILURE);
    }

    GLuint l_vao = 0;
    glGenVertexArrays(1, &l_vao);
    glBindVertexArray(l_vao);

    GLuint program = glCreateProgram();
    GLuint vsId = glCreateShader(GL_VERTEX_SHADER);
    GLuint fsId = glCreateShader(GL_FRAGMENT_SHADER);
    const GLchar* pVsSrcStr = "in vec2 vPosition; void main(){gl_Position = vec4(vPosition, 0., 1.)}";
    const GLchar* pFsSrcStr = "in vec2 vfTex; out vec4 fragColor; void main(){fragColor = vec4(1.,1.,0.,1.)}";
    int length = strlen(pVsSrcStr);
    glShaderSource(vsId, 1, &pVsSrcStr, &length);
    length = strlen(pFsSrcStr);
    glShaderSource(fsId, 1, &pVsSrcStr, &length);

    glCompileShader(vsId);
    glCompileShader(fsId);
    glAttachShader(program, vsId);
    glAttachShader(program, fsId);
    glLinkProgram(program);
    glUseProgram(0);//program);

    while (!glfwWindowShouldClose(l_Window))
    {
        glfwPollEvents();

#if 1
        glBegin(GL_TRIANGLES);
        glColor3f(1.f, 0.f, 0.f);
        glVertex3f(0.f, 0.f, 0.f);

        glColor3f(0.f, 1.f, 0.f);
        glVertex3f(1.f, 0.f, 0.f);

        glColor3f(0.f, 0.f, 1.f);
        glVertex3f(0.f, 1.f, 0.f);

        glEnd();
#endif

        glfwSwapBuffers(l_Window);
    }

    glfwDestroyWindow(l_Window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <stdlib.h>
#include <string>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstring>
#include <vector>

using namespace std;

int main()
{
	while(true)
	{
		if(NULL == getlogin())//Display login user
		{
			perror("getlogin");
		}
		else
		{
			cout << getlogin();
		}
		char host_name[64] ={0};
		if(-1 == gethostname(host_name,64))//Display host name
		{
			perror("hostname");
		}
		else
		{
			cout << "@" << host_name;
		}
		string commands;//Receive command line
		cout << "$";
		getline(cin,commands);
		const int y = commands.size() + 1;
		char* stuff = new char[y];//Stores command line as c strings
		strcpy(stuff,commands.c_str());
		char** cmd= new char*[y];//Stores the parsed command line
		int x = 0;
		char* tok = strtok(stuff, " ;\n\t\r");//Parses the c_strings
		while(tok != NULL)//Adding tokens into storage
		{
			if(strcmp(tok, "exit") == 0)//if an argument is exit
						    //it will exit
			{
				exit(0);
			}
			cmd[x] = tok;
			tok = strtok(NULL," ;\n\t\r");
			//cout << cmd[x] << " ";
			++x;
		}

		//cout << x << " " << x+1 << endl;Checks how many arguments and
						//which would be the null
						//argument
		cmd[x] = NULL;//Makes last argument the null character
		int pid = fork();
		if(pid == 0)
		{
			//cout << "This is the child" << endl;
			if(-1 == execvp(cmd[0], cmd))
			perror("execvp");
			exit(1);
		}
		else if (pid == -1)//If fork fails
		{
			perror("fork");
		}
		else
		{
			if(-1 == wait(0))
			{
				perror("wait");
			}
			//cout << "This is the parent" << endl;
		}

	}

	return 0;
}
<commit_msg>Added comments<commit_after>#include <iostream>
#include <stdlib.h>
#include <string>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstring>
#include <vector>

using namespace std;

int main()
{
	while(true)
	{
		if(NULL == getlogin())//Display login user
		{
			perror("getlogin");
		}
		else
		{
			cout << getlogin();
		}
		char host_name[64] ={0};
		if(-1 == gethostname(host_name,64))//Display host name
		{
			perror("hostname");
		}
		else
		{
			cout << "@" << host_name;
		}
		string commands;//Receive command line
		cout << "$";
		getline(cin,commands);

		//Removing comment
		int size_str = commands.find("#");
		commands = commands.substr(0,size_str);

		const int y = commands.size() + 1;
		char* stuff = new char[y];//Stores command line as c strings
		strcpy(stuff,commands.c_str());

		char** cmd= new char*[y];//Stores the parsed command line
		int x = 0;
		char* tok = strtok(stuff, " ;\n\t\r");//Parses the c_strings

		while(tok != NULL)//Adding tokens into storage
		{
			if(strcmp(tok, "exit") == 0)//if an argument is exit
						    //it will exit
			{
				exit(0);
			}
			cmd[x] = tok;
			tok = strtok(NULL," ;\n\t\r");
			//cout << cmd[x] << " ";
			++x;
		}

		//cout << x << " " << x+1 << endl;Checks how many arguments and
						//which would be the null
						//argument
		cmd[x] = NULL;//Makes last argument the null character
		int pid = fork();
		if(pid == 0)
		{
			//cout << "This is the child" << endl;
			if(-1 == execvp(cmd[0], cmd))
			perror("execvp");
			exit(1);
		}
		else if (pid == -1)//If fork fails
		{
			perror("fork");
		}
		else
		{
			if(-1 == wait(0))
			{
				perror("wait");
			}
			//cout << "This is the parent" << endl;
		}

	}

	return 0;
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "VisitorUtils.hpp"

#include "ltac/Statement.hpp"
#include "ltac/PseudoRegister.hpp"
#include "ltac/PseudoFloatRegister.hpp"
#include "ltac/LiveRegistersProblem.hpp"

using namespace eddic;

typedef ltac::LiveRegistersProblem::ProblemDomain ProblemDomain;

void ltac::LiveRegisterValues::insert(ltac::PseudoRegister reg){
    registers.insert(reg);
}

void ltac::LiveRegisterValues::insert(ltac::PseudoFloatRegister reg){
    float_registers.insert(reg);
}

void ltac::LiveRegisterValues::erase(ltac::PseudoRegister reg){
    registers.erase(reg);
}

void ltac::LiveRegisterValues::erase(ltac::PseudoFloatRegister reg){
    float_registers.erase(reg);
}

std::size_t ltac::LiveRegisterValues::size(){
    return (static_cast<std::size_t>(std::numeric_limits<unsigned short>::max()) + 1) * registers.size() + float_registers.size();
}

std::ostream& ltac::operator<<(std::ostream& stream, ltac::LiveRegisterValues& value){
    stream << "set{";

    for(auto& v : value.registers){
        stream << v << ", ";
    }

    for(auto& v : value.float_registers){
        stream << v << ", ";
    }

    return stream << "}";
}

ProblemDomain ltac::LiveRegistersProblem::Boundary(mtac::function_p /*function*/){
    auto value = default_element();
    return value;
}

ProblemDomain ltac::LiveRegistersProblem::Init(mtac::function_p /*function*/){
    auto value = default_element();
    return value;
}

ProblemDomain ltac::LiveRegistersProblem::meet(ProblemDomain& in, ProblemDomain& out){
    if(out.top()){
        return in;
    } else if(in.top()){
        return out;
    }

    typename ProblemDomain::Values values;
    ProblemDomain result(values);

    for(auto& value : in.values().registers){
        result.values().insert(value);
    }

    for(auto& value : in.values().float_registers){
        result.values().insert(value);
    }

    for(auto& value : out.values().registers){
        result.values().insert(value);
    }

    for(auto& value : out.values().float_registers){
        result.values().insert(value);
    }

    return result;
}

namespace {

struct LivenessCollector : public boost::static_visitor<> {
    ProblemDomain& in;

    LivenessCollector(ProblemDomain& in) : in(in) {}

    template<typename Arg>
    inline void set_live(Arg& arg){
        if(auto* ptr = boost::get<ltac::PseudoRegister>(&arg)){
            in.values().insert(*ptr);
        } else if(auto* ptr = boost::get<ltac::PseudoFloatRegister>(&arg)){
            in.values().insert(*ptr);
        }
    }

    template<typename Arg>
    inline void set_dead(Arg& arg){
        if(auto* ptr = boost::get<ltac::PseudoRegister>(&arg)){
            in.values().erase(*ptr);
        } else if(auto* ptr = boost::get<ltac::PseudoFloatRegister>(&arg)){
            in.values().erase(*ptr);
        }
    }

    template<typename Arg>
    inline void set_live_opt(Arg& arg){
        if(arg){
            set_live(*arg);
        }
    }

    void operator()(std::shared_ptr<ltac::Instruction> instruction){
        if(instruction->op != ltac::Operator::NOP){
            if(ltac::erase_result_complete(instruction->op)){
                set_dead(*instruction->arg1);
            } else {
                set_live_opt(instruction->arg1);
            }

            set_live_opt(instruction->arg2);
            set_live_opt(instruction->arg3);
        }

        for(auto& reg : instruction->uses){
            in.values().insert(reg);
        }

        for(auto& reg : instruction->float_uses){
            in.values().insert(reg);
        }
    }

    void operator()(std::shared_ptr<ltac::Jump> instruction){
        for(auto& reg : instruction->uses){
            in.values().insert(reg);
        }

        for(auto& reg : instruction->float_uses){
            in.values().insert(reg);
        }
    }

    template<typename T>
    void operator()(T&){
        //Nothing to do
    }
};

} //End of anonymous namespace

ProblemDomain ltac::LiveRegistersProblem::transfer(mtac::basic_block_p /*basic_block*/, ltac::Statement& statement, ProblemDomain& in){
    auto out = in;

    LivenessCollector collector(out);
    visit(collector, statement);

    return out;
}

bool ltac::LiveRegistersProblem::optimize(ltac::Statement& /*statement*/, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> /*results*/){
    //This analysis is only made to gather information, not to optimize anything
    throw "Unimplemented";
}
<commit_msg>Fix liveness calculation<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "VisitorUtils.hpp"

#include "ltac/Statement.hpp"
#include "ltac/PseudoRegister.hpp"
#include "ltac/PseudoFloatRegister.hpp"
#include "ltac/LiveRegistersProblem.hpp"

using namespace eddic;

typedef ltac::LiveRegistersProblem::ProblemDomain ProblemDomain;

void ltac::LiveRegisterValues::insert(ltac::PseudoRegister reg){
    registers.insert(reg);
}

void ltac::LiveRegisterValues::insert(ltac::PseudoFloatRegister reg){
    float_registers.insert(reg);
}

void ltac::LiveRegisterValues::erase(ltac::PseudoRegister reg){
    registers.erase(reg);
}

void ltac::LiveRegisterValues::erase(ltac::PseudoFloatRegister reg){
    float_registers.erase(reg);
}

std::size_t ltac::LiveRegisterValues::size(){
    return (static_cast<std::size_t>(std::numeric_limits<unsigned short>::max()) + 1) * registers.size() + float_registers.size();
}

std::ostream& ltac::operator<<(std::ostream& stream, ltac::LiveRegisterValues& value){
    stream << "set{";

    for(auto& v : value.registers){
        stream << v << ", ";
    }

    for(auto& v : value.float_registers){
        stream << v << ", ";
    }

    return stream << "}";
}

ProblemDomain ltac::LiveRegistersProblem::Boundary(mtac::function_p /*function*/){
    auto value = default_element();
    return value;
}

ProblemDomain ltac::LiveRegistersProblem::Init(mtac::function_p /*function*/){
    auto value = default_element();
    return value;
}

ProblemDomain ltac::LiveRegistersProblem::meet(ProblemDomain& in, ProblemDomain& out){
    if(out.top()){
        return in;
    } else if(in.top()){
        return out;
    }

    typename ProblemDomain::Values values;
    ProblemDomain result(values);

    for(auto& value : in.values().registers){
        result.values().insert(value);
    }

    for(auto& value : in.values().float_registers){
        result.values().insert(value);
    }

    for(auto& value : out.values().registers){
        result.values().insert(value);
    }

    for(auto& value : out.values().float_registers){
        result.values().insert(value);
    }

    return result;
}

namespace {

struct LivenessCollector : public boost::static_visitor<> {
    ProblemDomain& in;

    LivenessCollector(ProblemDomain& in) : in(in) {}

    template<typename Arg>
    inline void set_live(Arg& arg){
        if(auto* ptr = boost::get<ltac::PseudoRegister>(&arg)){
            in.values().insert(*ptr);
        } else if(auto* ptr = boost::get<ltac::PseudoFloatRegister>(&arg)){
            in.values().insert(*ptr);
        } else if(auto* ptr = boost::get<ltac::Address>(&arg)){
            set_live_opt(ptr->base_register);
            set_live_opt(ptr->scaled_register);
        }
    }

    template<typename Arg>
    inline void set_dead(Arg& arg){
        if(auto* ptr = boost::get<ltac::PseudoRegister>(&arg)){
            in.values().erase(*ptr);
        } else if(auto* ptr = boost::get<ltac::PseudoFloatRegister>(&arg)){
            in.values().erase(*ptr);
        }     }

    template<typename Arg>
    inline void set_live_opt(Arg& arg){
        if(arg){
            set_live(*arg);
        }
    }

    void operator()(std::shared_ptr<ltac::Instruction> instruction){
        if(instruction->op != ltac::Operator::NOP){
            if(ltac::erase_result_complete(instruction->op)){
                set_dead(*instruction->arg1);
            } else {
                set_live_opt(instruction->arg1);
            }

            set_live_opt(instruction->arg2);
            set_live_opt(instruction->arg3);
        }

        for(auto& reg : instruction->uses){
            in.values().insert(reg);
        }

        for(auto& reg : instruction->float_uses){
            in.values().insert(reg);
        }
    }

    void operator()(std::shared_ptr<ltac::Jump> instruction){
        for(auto& reg : instruction->uses){
            in.values().insert(reg);
        }

        for(auto& reg : instruction->float_uses){
            in.values().insert(reg);
        }
    }

    template<typename T>
    void operator()(T&){
        //Nothing to do
    }
};

} //End of anonymous namespace

ProblemDomain ltac::LiveRegistersProblem::transfer(mtac::basic_block_p /*basic_block*/, ltac::Statement& statement, ProblemDomain& in){
    auto out = in;

    LivenessCollector collector(out);
    visit(collector, statement);

    return out;
}

bool ltac::LiveRegistersProblem::optimize(ltac::Statement& /*statement*/, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> /*results*/){
    //This analysis is only made to gather information, not to optimize anything
    throw "Unimplemented";
}
<|endoftext|>


<commit_before>#include "core/crc32.h"
#include "core/input_system.h"
#include "core/lua_wrapper.h"
#include "engine.h"
#include "engine/plugin_manager.h"
#include "iplugin.h"
#include "lua_script/lua_script_system.h"
#include "renderer/material.h"
#include "renderer/render_scene.h"
#include "renderer/texture.h"
#include "universe/hierarchy.h"
#include "universe/universe.h"

namespace Lumix
{

namespace LuaAPI
{

static int getEnvironment(lua_State* L)
{
	if (!LuaWrapper::checkParameterType<void*>(L, 1) || !LuaWrapper::checkParameterType<int>(L, 2))
	{
		lua_pushnil(L);
		return 1;
	}

	LuaScriptScene* scene = (LuaScriptScene*)lua_touserdata(L, 1);
	Entity entity = (Entity)lua_tointeger(L, 2);

	int env = scene->getEnvironment(entity);

	if (env < 0)
	{
		lua_pushnil(L);
	}
	else
	{
		lua_rawgeti(L, LUA_REGISTRYINDEX, env);
	}
	return 1;
}

static Texture* getMaterialTexture(Material* material, int texture_index)
{
	if (!material) return nullptr;
	return material->getTexture(texture_index);
}

static Material* getTerrainMaterial(RenderScene* scene, Entity entity)
{
	if (!scene) return nullptr;
	ComponentIndex cmp = scene->getTerrainComponent(entity);
	if (cmp < 0) return nullptr;
	return scene->getTerrainMaterial(cmp);
}

static void* getScene(UniverseContext* ctx, const char* name)
{
	if (ctx)
	{
		uint32 hash = crc32(name);
		for (auto* scene : ctx->m_scenes)
		{
			if (crc32(scene->getPlugin().getName()) == hash)
			{
				return scene;
			}
		}
	}
	return nullptr;
}

static int createComponent(IScene* scene, const char* type, int entity_idx)
{
	if (!scene)
	{
		return -1;
	}
	Entity e(entity_idx);
	return scene->createComponent(crc32(type), e);
}

static int multVecQuat(lua_State* L)
{
	Vec3 v;
	v.x = (float)lua_tonumber(L, 1);
	v.y = (float)lua_tonumber(L, 2);
	v.z = (float)lua_tonumber(L, 3);
	Vec3 axis;
	axis.x = (float)lua_tonumber(L, 4);
	axis.y = (float)lua_tonumber(L, 5);
	axis.z = (float)lua_tonumber(L, 6);
	Quat q(axis, (float)lua_tonumber(L, 7));

	Vec3 res = q * v;

	lua_createtable(L, 3, 0);
	int table_idx = lua_gettop(L);

	lua_pushnumber(L, res.x);
	lua_rawseti(L, table_idx, 0);

	lua_pushnumber(L, res.y);
	lua_rawseti(L, table_idx, 1);

	lua_pushnumber(L, res.z);
	lua_rawseti(L, table_idx, 2);

	return 1;
}

static void logError(const char* text)
{
	g_log_error.log("lua script") << text;
}

static void logInfo(const char* text)
{
	g_log_info.log("lua script") << text;
}

static void setEntityPosition(Universe* univ, int entity_index, float x, float y, float z)
{
	univ->setPosition(entity_index, x, y, z);
}

static void setEntityRotation(Universe* univ,
	int entity_index,
	float x,
	float y,
	float z,
	float angle)
{
	if (entity_index < 0 || entity_index > univ->getEntityCount()) return;

	univ->setRotation(entity_index, Quat(Vec3(x, y, z), angle));
}

static void setEntityLocalRotation(IScene* hierarchy,
	Entity entity,
	float x,
	float y,
	float z,
	float angle)
{
	if (entity == INVALID_ENTITY) return;

	static_cast<Hierarchy*>(hierarchy)->setLocalRotation(entity, Quat(Vec3(x, y, z), angle));
}

static void setRenderablePath(IScene* scene, int component, const char* path)
{
	RenderScene* render_scene = (RenderScene*)scene;
	render_scene->setRenderablePath(component, path);
}

static float getInputActionValue(Engine* engine, uint32 action)
{
	auto v = engine->getInputSystem().getActionValue(action);
	return v;
}

static void addInputAction(Engine* engine, uint32 action, int type, int key, int controller_id)
{
	engine->getInputSystem().addAction(
		action, Lumix::InputSystem::InputType(type), key, controller_id);
}

} // namespace LuaAPI

static void
registerCFunction(lua_State* L, const char* name, lua_CFunction func)
{
	lua_pushcfunction(L, func);
	lua_setglobal(L, name);
}

void registerUniverse(UniverseContext* ctx, lua_State* L)
{
	lua_pushlightuserdata(L, ctx);
	lua_setglobal(L, "g_universe_context");

	for (auto* scene : ctx->m_scenes)
	{
		const char* name = scene->getPlugin().getName();
		char tmp[128];

		copyString(tmp, "g_scene_");
		catString(tmp, name);
		lua_pushlightuserdata(L, scene);
		lua_setglobal(L, tmp);
	}

	lua_pushlightuserdata(L, ctx ? ctx->m_universe : nullptr);
	lua_setglobal(L, "g_universe");
}

void registerEngineLuaAPI(Engine& engine, lua_State* L)
{
	lua_pushlightuserdata(L, &engine);
	lua_setglobal(L, "g_engine");

	registerCFunction(L, "API_getEnvironment", &LuaAPI::getEnvironment);

	registerCFunction(L,
					  "API_getMaterialTexture",
					  LuaWrapper::wrap<decltype(&LuaAPI::getMaterialTexture),
									   LuaAPI::getMaterialTexture>);

	registerCFunction(L,
					  "API_getTerrainMaterial",
					  LuaWrapper::wrap<decltype(&LuaAPI::getTerrainMaterial),
									   LuaAPI::getTerrainMaterial>);

	registerCFunction(
		L,
		"API_getScene",
		LuaWrapper::wrap<decltype(&LuaAPI::getScene), LuaAPI::getScene>);

	registerCFunction(L,
					  "API_setEntityPosition",
					  LuaWrapper::wrap<decltype(&LuaAPI::setEntityPosition),
									   LuaAPI::setEntityPosition>);

	registerCFunction(L,
					  "API_setEntityRotation",
					  LuaWrapper::wrap<decltype(&LuaAPI::setEntityRotation),
									   LuaAPI::setEntityRotation>);

	registerCFunction(
		L,
		"API_setEntityLocalRotation",
		LuaWrapper::wrap<decltype(&LuaAPI::setEntityLocalRotation),
						 LuaAPI::setEntityLocalRotation>);

	registerCFunction(L,
					  "API_createComponent",
					  LuaWrapper::wrap<decltype(&LuaAPI::createComponent),
									   LuaAPI::createComponent>);

	registerCFunction(L,
					  "API_setRenderablePath",
					  LuaWrapper::wrap<decltype(&LuaAPI::setRenderablePath),
									   LuaAPI::setRenderablePath>);

	registerCFunction(L,
					  "API_getInputActionValue",
					  LuaWrapper::wrap<decltype(&LuaAPI::getInputActionValue),
									   LuaAPI::getInputActionValue>);
	registerCFunction(L,
					  "API_addInputAction",
					  LuaWrapper::wrap<decltype(&LuaAPI::addInputAction),
									   LuaAPI::addInputAction>);

	registerCFunction(
		L,
		"API_logError",
		LuaWrapper::wrap<decltype(&LuaAPI::logError), LuaAPI::logError>);

	registerCFunction(
		L,
		"API_logInfo",
		LuaWrapper::wrap<decltype(&LuaAPI::logInfo), LuaAPI::logInfo>);

	registerCFunction(L, "API_multVecQuat", &LuaAPI::multVecQuat);
}

} // namespace Lumix<commit_msg>refactor<commit_after>#include "core/crc32.h"
#include "core/input_system.h"
#include "core/lua_wrapper.h"
#include "engine.h"
#include "engine/plugin_manager.h"
#include "iplugin.h"
#include "lua_script/lua_script_system.h"
#include "renderer/material.h"
#include "renderer/render_scene.h"
#include "renderer/texture.h"
#include "universe/hierarchy.h"
#include "universe/universe.h"

namespace Lumix
{

namespace LuaAPI
{

static int getEnvironment(lua_State* L)
{
	if (!LuaWrapper::checkParameterType<void*>(L, 1) || !LuaWrapper::checkParameterType<int>(L, 2))
	{
		lua_pushnil(L);
		return 1;
	}

	LuaScriptScene* scene = (LuaScriptScene*)lua_touserdata(L, 1);
	Entity entity = (Entity)lua_tointeger(L, 2);

	int env = scene->getEnvironment(entity);

	if (env < 0)
	{
		lua_pushnil(L);
	}
	else
	{
		lua_rawgeti(L, LUA_REGISTRYINDEX, env);
	}
	return 1;
}

static Texture* getMaterialTexture(Material* material, int texture_index)
{
	if (!material) return nullptr;
	return material->getTexture(texture_index);
}

static Material* getTerrainMaterial(RenderScene* scene, Entity entity)
{
	if (!scene) return nullptr;
	ComponentIndex cmp = scene->getTerrainComponent(entity);
	if (cmp < 0) return nullptr;
	return scene->getTerrainMaterial(cmp);
}

static int createComponent(IScene* scene, const char* type, int entity_idx)
{
	if (!scene)
	{
		return -1;
	}
	Entity e(entity_idx);
	return scene->createComponent(crc32(type), e);
}

static int multVecQuat(lua_State* L)
{
	Vec3 v;
	v.x = (float)lua_tonumber(L, 1);
	v.y = (float)lua_tonumber(L, 2);
	v.z = (float)lua_tonumber(L, 3);
	Vec3 axis;
	axis.x = (float)lua_tonumber(L, 4);
	axis.y = (float)lua_tonumber(L, 5);
	axis.z = (float)lua_tonumber(L, 6);
	Quat q(axis, (float)lua_tonumber(L, 7));

	Vec3 res = q * v;

	lua_createtable(L, 3, 0);
	int table_idx = lua_gettop(L);

	lua_pushnumber(L, res.x);
	lua_rawseti(L, table_idx, 0);

	lua_pushnumber(L, res.y);
	lua_rawseti(L, table_idx, 1);

	lua_pushnumber(L, res.z);
	lua_rawseti(L, table_idx, 2);

	return 1;
}

static void logError(const char* text)
{
	g_log_error.log("lua script") << text;
}

static void logInfo(const char* text)
{
	g_log_info.log("lua script") << text;
}

static void setEntityPosition(Universe* univ, int entity_index, float x, float y, float z)
{
	univ->setPosition(entity_index, x, y, z);
}

static void setEntityRotation(Universe* univ,
	int entity_index,
	float x,
	float y,
	float z,
	float angle)
{
	if (entity_index < 0 || entity_index > univ->getEntityCount()) return;

	univ->setRotation(entity_index, Quat(Vec3(x, y, z), angle));
}

static void setEntityLocalRotation(IScene* hierarchy,
	Entity entity,
	float x,
	float y,
	float z,
	float angle)
{
	if (entity == INVALID_ENTITY) return;

	static_cast<Hierarchy*>(hierarchy)->setLocalRotation(entity, Quat(Vec3(x, y, z), angle));
}

static void setRenderablePath(IScene* scene, int component, const char* path)
{
	RenderScene* render_scene = (RenderScene*)scene;
	render_scene->setRenderablePath(component, path);
}

static float getInputActionValue(Engine* engine, uint32 action)
{
	auto v = engine->getInputSystem().getActionValue(action);
	return v;
}

static void addInputAction(Engine* engine, uint32 action, int type, int key, int controller_id)
{
	engine->getInputSystem().addAction(
		action, Lumix::InputSystem::InputType(type), key, controller_id);
}

} // namespace LuaAPI

static void registerCFunction(lua_State* L, const char* name, lua_CFunction func)
{
	lua_pushcfunction(L, func);
	lua_setglobal(L, name);
}

void registerUniverse(UniverseContext* ctx, lua_State* L)
{
	lua_pushlightuserdata(L, ctx);
	lua_setglobal(L, "g_universe_context");

	for (auto* scene : ctx->m_scenes)
	{
		const char* name = scene->getPlugin().getName();
		char tmp[128];

		copyString(tmp, "g_scene_");
		catString(tmp, name);
		lua_pushlightuserdata(L, scene);
		lua_setglobal(L, tmp);
	}

	lua_pushlightuserdata(L, ctx ? ctx->m_universe : nullptr);
	lua_setglobal(L, "g_universe");
}

void registerEngineLuaAPI(Engine& engine, lua_State* L)
{
	lua_pushlightuserdata(L, &engine);
	lua_setglobal(L, "g_engine");

	#define REGISTER_FUNCTION(name) \
		registerCFunction(L, "API_" #name, LuaWrapper::wrap<decltype(&LuaAPI::name), LuaAPI::name>)

	REGISTER_FUNCTION(createComponent);
	REGISTER_FUNCTION(getEnvironment);
	REGISTER_FUNCTION(getMaterialTexture);
	REGISTER_FUNCTION(getTerrainMaterial);
	REGISTER_FUNCTION(setEntityPosition);
	REGISTER_FUNCTION(setEntityRotation);
	REGISTER_FUNCTION(setEntityLocalRotation);
	REGISTER_FUNCTION(setRenderablePath);
	REGISTER_FUNCTION(getInputActionValue);
	REGISTER_FUNCTION(addInputAction);
	REGISTER_FUNCTION(logError);
	REGISTER_FUNCTION(logInfo);
	REGISTER_FUNCTION(logInfo);

	registerCFunction(L, "API_multVecQuat", &LuaAPI::multVecQuat);

	#undef REGISTER_FUNCTION
}

} // namespace Lumix<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fuchar.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 18:46:59 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "fuchar.hxx"

#include <sfx2/viewfrm.hxx>

#include <svx/editdata.hxx>
#include <svx/svxids.hrc>
#ifndef _EEITEM_HXX //autogen
#include <svx/eeitem.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif

//CHINA001 #include "dlg_char.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#include "drawdoc.hxx"
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#include "DrawDocShell.hxx"
#include "sdabstdlg.hxx" //CHINA001
#include "dlg_char.hrc" //CHINA001
namespace sd {

TYPEINIT1( FuChar, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuChar::FuChar (
    ViewShell* pViewSh,
    ::sd::Window* pWin,
    ::sd::View* pView,
    SdDrawDocument* pDoc,
    SfxRequest& rReq)
    : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}

FunctionReference FuChar::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
    FunctionReference xFunc( new FuChar( pViewSh, pWin, pView, pDoc, rReq ) );
    xFunc->DoExecute(rReq);
    return xFunc;
}

void FuChar::DoExecute( SfxRequest& rReq )
{
    const SfxItemSet* pArgs = rReq.GetArgs();

    if( !pArgs )
    {
        SfxItemSet aEditAttr( pDoc->GetPool() );
        pView->GetAttributes( aEditAttr );

        SfxItemSet aNewAttr( pViewShell->GetPool(),
                                EE_ITEMS_START, EE_ITEMS_END );
        aNewAttr.Put( aEditAttr, FALSE );

        //CHINA001 SdCharDlg* pDlg = new SdCharDlg( NULL, &aNewAttr, pDoc->GetDocSh() );
        SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();//CHINA001
        DBG_ASSERT(pFact, "SdAbstractDialogFactory fail!");//CHINA001
        SfxAbstractTabDialog* pDlg = pFact->CreateSdTabDialog(ResId( TAB_CHAR ), NULL, &aNewAttr, pDoc->GetDocSh() );
        DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
        USHORT nResult = pDlg->Execute();

        switch( nResult )
        {
            case RET_OK:
            {
                rReq.Done( *( pDlg->GetOutputItemSet() ) );

                pArgs = rReq.GetArgs();
            }
            break;

            default:
            {
                delete pDlg;
            }
            return; // Abbruch
        }
        delete( pDlg );
    }
    pView->SetAttributes(*pArgs);

    // invalidieren der Slots, die in der DrTxtObjBar auftauchen
    static USHORT SidArray[] = {
                    SID_ATTR_CHAR_FONT,
                    SID_ATTR_CHAR_POSTURE,
                    SID_ATTR_CHAR_WEIGHT,
                    SID_ATTR_CHAR_UNDERLINE,
                    SID_ATTR_CHAR_FONTHEIGHT,
                    SID_ATTR_CHAR_COLOR,
                    SID_SET_SUPER_SCRIPT,
                    SID_SET_SUB_SCRIPT,
                    0 };

    pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );

    if( pDoc->GetOnlineSpell() )
    {
        const SfxPoolItem* pItem;
        if( SFX_ITEM_SET == pArgs->GetItemState(EE_CHAR_LANGUAGE, FALSE, &pItem ) ||
            SFX_ITEM_SET == pArgs->GetItemState(EE_CHAR_LANGUAGE_CJK, FALSE, &pItem ) ||
            SFX_ITEM_SET == pArgs->GetItemState(EE_CHAR_LANGUAGE_CTL, FALSE, &pItem ) )
        {
            pDoc->StopOnlineSpelling();
            pDoc->StartOnlineSpelling();
        }
    }
}

void FuChar::Activate()
{
}

void FuChar::Deactivate()
{
}

} // end of namespace sd
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.9.38); FILE MERGED 2006/11/22 12:41:51 cl 1.9.38.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fuchar.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 17:14:18 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "fuchar.hxx"

#include <sfx2/viewfrm.hxx>

#include <svx/editdata.hxx>
#include <svx/svxids.hrc>
#ifndef _EEITEM_HXX //autogen
#include <svx/eeitem.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif

#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif
#include "drawdoc.hxx"
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#include "DrawDocShell.hxx"
#include "sdabstdlg.hxx"

namespace sd {

TYPEINIT1( FuChar, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuChar::FuChar (
    ViewShell* pViewSh,
    ::sd::Window* pWin,
    ::sd::View* pView,
    SdDrawDocument* pDoc,
    SfxRequest& rReq)
    : FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}

FunctionReference FuChar::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
    FunctionReference xFunc( new FuChar( pViewSh, pWin, pView, pDoc, rReq ) );
    xFunc->DoExecute(rReq);
    return xFunc;
}

void FuChar::DoExecute( SfxRequest& rReq )
{
    const SfxItemSet* pArgs = rReq.GetArgs();

    if( !pArgs )
    {
        SfxItemSet aEditAttr( mpDoc->GetPool() );
        mpView->GetAttributes( aEditAttr );

        SfxItemSet aNewAttr( mpViewShell->GetPool(),
                                EE_ITEMS_START, EE_ITEMS_END );
        aNewAttr.Put( aEditAttr, FALSE );

        SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();
        SfxAbstractTabDialog* pDlg = pFact ? pFact->CreateSdTabCharDialog( NULL, &aNewAttr, mpDoc->GetDocSh() ) : 0;
        if( pDlg )
        {
            USHORT nResult = pDlg->Execute();

            if( nResult == RET_OK )
            {
                rReq.Done( *( pDlg->GetOutputItemSet() ) );
                pArgs = rReq.GetArgs();
            }

            delete pDlg;

            if( nResult != RET_OK )
            {
                return;
            }
        }
    }
    mpView->SetAttributes(*pArgs);

    // invalidieren der Slots, die in der DrTxtObjBar auftauchen
    static USHORT SidArray[] = {
                    SID_ATTR_CHAR_FONT,
                    SID_ATTR_CHAR_POSTURE,
                    SID_ATTR_CHAR_WEIGHT,
                    SID_ATTR_CHAR_UNDERLINE,
                    SID_ATTR_CHAR_FONTHEIGHT,
                    SID_ATTR_CHAR_COLOR,
                    SID_SET_SUPER_SCRIPT,
                    SID_SET_SUB_SCRIPT,
                    0 };

    mpViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );

    if( mpDoc->GetOnlineSpell() )
    {
        const SfxPoolItem* pItem;
        if( SFX_ITEM_SET == pArgs->GetItemState(EE_CHAR_LANGUAGE, FALSE, &pItem ) ||
            SFX_ITEM_SET == pArgs->GetItemState(EE_CHAR_LANGUAGE_CJK, FALSE, &pItem ) ||
            SFX_ITEM_SET == pArgs->GetItemState(EE_CHAR_LANGUAGE_CTL, FALSE, &pItem ) )
        {
            mpDoc->StopOnlineSpelling();
            mpDoc->StartOnlineSpelling();
        }
    }
}

void FuChar::Activate()
{
}

void FuChar::Deactivate()
{
}

} // end of namespace sd
<|endoftext|>