Beispiel #1
0
void ZoomCamera::adjust(const Bounds2D& bounds) {
    adjust(bounds, true);
}
Beispiel #2
0
// multiple merge sort
bool externalSort::mergeSort() {
  if (fileNum <= 0) {
    return false;
  }
    
  // make sure file won't be written twice
  remove("sorted_cust.dat");
  remove("sorted_order.dat");

 
  FILE *fout_cust = fopen("sorted_cust.dat", "ab+");
  FILE *fout_order = fopen("sorted_order.dat", "ab+");

  FILE* *farray = new FILE*[fileNum]; // point pointers to temp files
  // creat pointers to each temp file  
  for (int i = 0; i < fileNum; ++i) {
    char* tempFile = fileName(i);
    farray[i] = fopen(tempFile, "rb");
    free(tempFile);
  }

  int *dataCust = new int[fileNum + 1]; // leaves node
  int *dataOrder = new int[fileNum];
  int *ls = new int[fileNum]; // loser tree, stores the position of parents
  int MINKEY = 0;
  int MAXKEY = 999999999;


  memset(dataCust, 0, sizeof(int) * (fileNum + 1));
  memset(dataOrder, 0, sizeof(int) * fileNum);
  memset(ls, 0, sizeof(int) * fileNum);

  //read data
  for (int i = 0; i < fileNum; i++) {
    fread(&dataCust[i], sizeof(int), 1, farray[i]);
    fread(&dataOrder[i], sizeof(int), 1, farray[i]);

  }
  dataCust[fileNum] = MINKEY; // use for create loser tree

  createLoserTree(ls, dataCust);

  // sort
  while(dataCust[ls[0]] != MAXKEY) {
    int index = ls[0]; // position stores the file index of minimum custkey

    // writes the custkey and orderkey of winner
    fwrite(&dataCust[index], sizeof(int), 1, fout_cust);
    fwrite(&dataOrder[index], sizeof(int), 1, fout_order);

    // read new data
    fread(&dataCust[index], sizeof(int), 1, farray[index]);
    if (feof(farray[index]) != 0) {
      dataCust[index] = MAXKEY; // set end mark
    } else {
      fread(&dataOrder[index], sizeof(int), 1, farray[index]);
    }
    adjust(ls,index,dataCust);
  }
  // close file
  delete [] dataCust;
  delete [] dataOrder;
  for (int i = 0; i < fileNum; ++i) {
    fclose(farray[i]);
  }

  // delete the temporary file    
  for (int i = 0; i < fileNum; ++i) {
    remove(fileName(i));
  }
    
  delete [] farray;
  fclose(fout_cust);
  fclose(fout_order);
  return true;
}
//////////////////////
// Maximize the likelihood when dealing with a single parameter
//////////////////////
void ML_single_NewtonRaphson::find_maximum() {

    history.clear();

    RatePVector& rpv = branch_rate_manager.get_ratepvector();
    assert(rpv.size() == 1);
    int thisparm = 0;
    Likelihood::RatePBounds& b = bounds[thisparm];
    
    b.delta = determine_machine_delta();
    // double b.delta = 0.0000001;
    double parameter = (b.lowerbound + 
                        b.upperbound) / 2.0;
    double logL_m_delta = compute_for_single_parameter(parameter - 
                                                       b.delta);
    // double logL_m_05delta = compute_for_single_parameter(parameter -
    //                                                 (0.5*b.delta));
    double logL = compute_for_single_parameter(parameter);
    // double logL_p_05delta = compute_for_single_parameter(parameter +
    //                                                 (0.5*b.delta));
    double logL_p_delta = compute_for_single_parameter(parameter + 
                                                  b.delta);

    history.add(parameter, b.accuracy, b.delta, 
                b.lowerbound, b.upperbound, 
                logL_m_delta,
                // logL_m_05delta,
                logL,
                // logL_p_05delta,
                logL_p_delta);

    do {
        parameter = adjust();
        if (parameter < b.lowerbound || parameter > b.upperbound) {
            std::cout << "warning: exceeded bound" << std::endl;
        }
        logL_m_delta = compute_for_single_parameter(parameter - b.delta);
        // logL_m_05delta = compute_for_single_parameter(parameter - (0.5*b.delta));
        logL = compute_for_single_parameter(parameter);
        // logL_p_05delta = compute_for_single_parameter(parameter + (0.5*b.delta));
        logL_p_delta = compute_for_single_parameter(parameter + b.delta);
        history.add(parameter, b.accuracy, b.delta, b.lowerbound, 
                    b.upperbound, logL_m_delta,
                    // logL_m_05delta,
                    logL,
                    // logL_p_05delta,
                    logL_p_delta);
        if (MAXDEBUG) {
            std::cout << "History complete:" << std::endl;
            // history.print();
            history.simple_print();
        }
    } while (! converged());
    
    if (MAXDEBUG_HISTORY_AT_CONVERGENCE) {
        history.simple_print();
    }

    int hsz = history.size();
    if (compute_for_single_parameter(b.lowerbound) > history[hsz - 1].logL) {
        std::cerr << "log-Likelihood(b.lowerbound) > log-Likelihood(converged)"
                  << std::endl;
    }
    if (compute_for_single_parameter(b.upperbound) > history[hsz - 1].logL) {
        std::cerr << "log-Likelihood(b.upperbound) > log-Likelihood(converged)"
                  << std::endl;
    }
    rpv[thisparm].set_ratep(history[hsz - 1].parameter);

    set_log_likelihood(history[hsz - 1].logL);
}
void QHexEditPrivate::setAsciiArea(bool asciiArea)
{
    _asciiArea = asciiArea;
    adjust();
}
void QHexEditPrivate::keyPressEvent(QKeyEvent *event)
{
    int charX = (_cursorX - _xPosHex) / _charWidth;
    int posX = (charX / 3) * 2 + (charX % 3);
    int posBa = (_cursorY / _charHeight) * BYTES_PER_LINE + posX / 2;


/*****************************************************************************/
/* Cursor movements */
/*****************************************************************************/

    if (event->matches(QKeySequence::MoveToNextChar))
    {
        setCursorPos(_cursorPosition + 1);
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToPreviousChar))
    {
        setCursorPos(_cursorPosition - 1);
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToEndOfLine))
    {
        setCursorPos(_cursorPosition | (2 * BYTES_PER_LINE -1));
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToStartOfLine))
    {
        setCursorPos(_cursorPosition - (_cursorPosition % (2 * BYTES_PER_LINE)));
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToPreviousLine))
    {
        setCursorPos(_cursorPosition - (2 * BYTES_PER_LINE));
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToNextLine))
    {
        setCursorPos(_cursorPosition + (2 * BYTES_PER_LINE));
        resetSelection(_cursorPosition);
    }

    if (event->matches(QKeySequence::MoveToNextPage))
    {
        setCursorPos(_cursorPosition + (((_scrollArea->viewport()->height() / _charHeight) - 1) * 2 * BYTES_PER_LINE));
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToPreviousPage))
    {
        setCursorPos(_cursorPosition - (((_scrollArea->viewport()->height() / _charHeight) - 1) * 2 * BYTES_PER_LINE));
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToEndOfDocument))
    {
        setCursorPos(_data.size() * 2);
        resetSelection(_cursorPosition);
    }
    if (event->matches(QKeySequence::MoveToStartOfDocument))
    {
        setCursorPos(0);
        resetSelection(_cursorPosition);
    }

/*****************************************************************************/
/* Select commands */
/*****************************************************************************/
    if (event->matches(QKeySequence::SelectAll))
    {
        resetSelection(0);
        setSelection(2*_data.length() + 1);
    }
    if (event->matches(QKeySequence::SelectNextChar))
    {
        int pos = _cursorPosition + 1;
        setCursorPos(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectPreviousChar))
    {
        int pos = _cursorPosition - 1;
        setSelection(pos);
        setCursorPos(pos);
    }
    if (event->matches(QKeySequence::SelectEndOfLine))
    {
        int pos = _cursorPosition - (_cursorPosition % (2 * BYTES_PER_LINE)) + (2 * BYTES_PER_LINE);
        setCursorPos(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectStartOfLine))
    {
        int pos = _cursorPosition - (_cursorPosition % (2 * BYTES_PER_LINE));
        setCursorPos(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectPreviousLine))
    {
        int pos = _cursorPosition - (2 * BYTES_PER_LINE);
        setCursorPos(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectNextLine))
    {
        int pos = _cursorPosition + (2 * BYTES_PER_LINE);
        setCursorPos(pos);
        setSelection(pos);
    }

    if (event->matches(QKeySequence::SelectNextPage))
    {
        int pos = _cursorPosition + (((_scrollArea->viewport()->height() / _charHeight) - 1) * 2 * BYTES_PER_LINE);
        setCursorPos(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectPreviousPage))
    {
        int pos = _cursorPosition - (((_scrollArea->viewport()->height() / _charHeight) - 1) * 2 * BYTES_PER_LINE);
        setCursorPos(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectEndOfDocument))
    {
        int pos = _data.size() * 2;
        setCursorPos(pos);
        setSelection(pos);
    }
    if (event->matches(QKeySequence::SelectStartOfDocument))
    {
        int pos = 0;
        setCursorPos(pos);
        setSelection(pos);
    }

/*****************************************************************************/
/* Edit Commands */
/*****************************************************************************/
if (!_readOnly)
{
    /* Hex input */
        int key = int(event->text()[0].toAscii());
        if ((key>='0' && key<='9') || (key>='a' && key <= 'f'))
        {
            if (getSelectionBegin() != getSelectionEnd())
            {
                posBa = getSelectionBegin();
                remove(posBa, getSelectionEnd() - posBa);
                setCursorPos(2*posBa);
                resetSelection(2*posBa);
            }

            // If insert mode, then insert a byte
            if (_overwriteMode == false)
                if ((charX % 3) == 0)
                {
                    insert(posBa, char(0));
                    adjust();
                }

            // Change content
            if (_data.size() > 0)
            {
                QByteArray hexValue = _data.mid(posBa, 1).toHex();
                if ((charX % 3) == 0)
                    hexValue[0] = key;
                else
                    hexValue[1] = key;
                replace(posBa, 1, QByteArray().fromHex(hexValue));

                setCursorPos(_cursorPosition + 1);
                resetSelection(_cursorPosition);
            }
        }

        /* Cut & Paste */
        if (event->matches(QKeySequence::Cut))
        {
            QString result = QString();
            for (int idx = getSelectionBegin(); idx < getSelectionEnd(); idx++)
            {
                result += _data.mid(idx, 1).toHex() + " ";
                if ((idx % 16) == 15)
                    result.append("\n");
            }
            remove(getSelectionBegin(), getSelectionEnd());
            QClipboard *clipboard = QApplication::clipboard();
            clipboard->setText(result);
            setCursorPos(getSelectionBegin());
            resetSelection(getSelectionBegin());
        }

        if (event->matches(QKeySequence::Paste))
        {
            QClipboard *clipboard = QApplication::clipboard();
            QByteArray ba = QByteArray().fromHex(clipboard->text().toLatin1());
            insert(_cursorPosition / 2, ba);
            setCursorPos((_cursorPosition + (2 * ba.length()) + 1) & 0xfffffffe);
            resetSelection(getSelectionBegin());
        }


        /* Delete char */
        if (event->matches(QKeySequence::Delete))
        {
            if (getSelectionBegin() != getSelectionEnd())
            {
                posBa = getSelectionBegin();
                remove(posBa, getSelectionEnd() - posBa);
                setCursorPos(2*posBa);
                resetSelection(2*posBa);
            }
            else
            {
                remove(posBa);
            }
        }

        /* Backspace */
        if ((event->key() == Qt::Key_Backspace) && (event->modifiers() == Qt::NoModifier))
            {
                if (getSelectionBegin() != getSelectionEnd())
                {
                    posBa = getSelectionBegin();
                    remove(posBa, getSelectionEnd() - posBa);
                    setCursorPos(2*posBa);
                    resetSelection(2*posBa);
                }
                else
                {
                    remove(posBa - 1);
                    setCursorPos(_cursorPosition - 2);
                }
            }
    }

    if (event->matches(QKeySequence::Copy))
    {
        QString result = QString();
        for (int idx = getSelectionBegin(); idx < getSelectionEnd(); idx++)
        {
            result += _data.mid(idx, 1).toHex() + " ";
            if ((idx % 16) == 15)
                result.append('\n');
        }
        QClipboard *clipboard = QApplication::clipboard();
        clipboard->setText(result);
    }

    // Switch between insert/overwrite mode
    if ((event->key() == Qt::Key_Insert) && (event->modifiers() == Qt::NoModifier))
    {
        setOverwriteMode(!_overwriteMode);
        setCursorPos(_cursorPosition);
    }

    _scrollArea->ensureVisible(_cursorX, _cursorY + _charHeight/2, 3, _charHeight/2 + 2);

    update();
}
Beispiel #6
0
const ScaleMat &ScaleMat::adjust( const float pct ) {
  return adjust( pct, pct, pct );
}
Beispiel #7
0
void make_heap() {
    int len = size / 2;
    for(int i =  len; i >= 1; i--) {
        adjust(i);
    }
}
Beispiel #8
0
void heap::heapify()
{
   //for ( int i = (int)floor(double(count())/2); i>=1; adjust(i--) );

   for ( int i = count()/2; i>=1; adjust(i--) );
}
Beispiel #9
0
int
set_variable(char *variable, int on, char *val_string)
{
    int             value;
    register struct variable_defs *var;

    if (strncmp(variable, "no", 2) == 0) {
	on = !on;
	variable += 2;
	if (variable[0] == '-')
	    variable++;
    }
    if ((var = lookup_variable(variable)) == NULL)
	return 0;

    if (!in_init && (var->var_flags & (V_INIT | V_SAFE))) {
	if (var->var_flags & V_INIT) {
	    msg("'%s' can only be set in the init file", variable);
	    return 0;
	}
	if (shell_restrictions) {
	    msg("Restricted operation - cannot change");
	    return 0;
	}
    }
    if (var->var_flags & V_LOCKED) {
	msg("Variable '%s' is locked", variable);
	return 0;
    }
    if (!on || val_string == NULL)
	value = 0;
    else
	value = atoi(val_string);

    var->var_flags |= V_MODIFIED;

    switch (VAR_TYPE) {

	case V_STRING:

	    if (on)
		adjust(val_string);

	    switch (VAR_OP) {
		case 0:
		    STR_VAR = (on && val_string) ? copy_str(val_string) : (char *) NULL;
		    break;

		case 1:
		    strcpy(CBUF_VAR, (on && val_string) ? val_string : "");
		    break;

		case 2:
		    if (on) {
			char            exp_buf[FILENAME];

			if (val_string) {
			    if (expand_file_name(exp_buf, val_string, 1))
				STR_VAR = home_relative(exp_buf);
			}
		    } else
			STR_VAR = (char *) NULL;
		    break;

		case 3:
		case 4:
		    if (!on || val_string == NULL) {
			msg("Cannot unset string `%s'", variable);
			break;
		    }
		    if (VAR_OP == 4) {
			char            exp_buf[FILENAME];
			if (expand_file_name(exp_buf, val_string, 1)) {
			    STR_VAR = copy_str(exp_buf);
			    break;
			}
		    }
		    STR_VAR = copy_str(val_string);
		    break;
		case 5:
		    STR_VAR = (on && val_string) ? copy_str(val_string) : "";
		    break;

	    }
	    break;

	case V_BOOLEAN:

	    adjust(val_string);
	    if (val_string && *val_string != NUL) {
		if (val_string[0] == 'o')
		    on = val_string[1] == 'n';	/* on */
		else
		    on = val_string[0] == 't';	/* true */
	    }
	    switch (VAR_OP) {
		case 0:
		    BOOL_VAR = on;
		    break;

		case 1:
		    BOOL_VAR = on;
		    return 1;

		case 2:
		    if (BOOL_VAR) {	/* don't change if already ok */
			if (!on)
			    break;
		    } else if (on)
			break;

		    BOOL_VAR = !on;
		    if (!in_init) {
			sort_articles(BOOL_VAR ? 0 : -1);
			return 1;
		    }
		    break;

		case 4:
		    BOOL_VAR = !on;
		    break;
	    }
	    break;

	case V_INTEGER:

	    switch (VAR_OP) {
		case 0:
		case 1:
		    INT_VAR = value;
		    break;

		case 2:
		case 3:
		    if (!on)
			value = -1;
		    INT_VAR = value;
		    break;
	    }
	    return (VAR_OP & 1);

	case V_KEY:
	    switch (VAR_OP) {
		case 0:
		    if (val_string) {
			if (*val_string)
			    adjust(val_string + 1);	/* #N is valid */
			KEY_VAR = parse_key(val_string);
		    }
		    break;
	    }
	    break;

	case V_SPECIAL:

	    switch (VAR_OP) {
		case 1:
		    if (val_string) {
			adjust(val_string);
			news_record = home_relative(val_string);
			mail_record = news_record;
			var->var_flags &= ~V_MODIFIED;
			lookup_variable("mail-record")->var_flags |= V_MODIFIED;
			lookup_variable("news-record")->var_flags |= V_MODIFIED;
		    }
		    break;

		case 2:
		    also_read_articles = on;
		    article_limit = (on && value > 0) ? value : -1;
		    break;

		case 3:
		    {
			struct chset   *csp;
			struct variable_defs *dbvar;

			dbvar = lookup_variable("data-bits");

			if (on && val_string) {
			    if ((csp = getchset(val_string)) == NULL)
				msg("Illegal value for `%s' variable", variable);
			    else {
				curchset = csp;
				data_bits = csp->cs_width ? csp->cs_width : 7;
				dbvar->var_flags &= ~V_MODIFIED;
			    }
			} else
			    msg("Cannot unset special `%s' variable", variable);
		    }
		    break;
	    }
	    break;

	case V_CODES:
	    {
		char            codes[80], code[16], *sp, *cp, *vs;

		if (val_string == NULL)
		    on = 0;
		if (on) {
		    adjust(val_string);
		    if (val_string[0] == NUL)
			on = 0;
		}
		if (on) {
		    sp = codes;
		    vs = val_string;
		    while (*vs) {
			while (*vs && (!isascii(*vs) || isspace(*vs)))
			    vs++;
			if (*vs == NUL)
			    break;
			cp = code;
			while (*vs && isascii(*vs) && !isspace(*vs))
			    *cp++ = *vs++;
			*cp = NUL;
			*sp++ = parse_key(code);
		    }
		    *sp = NUL;
		    if (codes[0] == NUL)
			on = 0;
		}
		freeobj(code_strings[VAR_OP]);
		code_strings[VAR_OP] = on ? copy_str(val_string) : NULL;
		STR_VAR = on ? copy_str(codes) : (char *) NULL;
		break;
	    }
    }
    return 0;
}
Beispiel #10
0
 inline Date Calendar::endOfMonth(const Date& d) const {
     return adjust(Date::endOfMonth(d), Preceding);
 }
Beispiel #11
0
int main(int argc, char *argv[])
{
int         MAXLINES = 1000;
FILE        *fp;
char        buf[BUFSIZ];
int         i;
char        **olptr;
int         done = FALSE;
int         length = 0;
#if CAN_RESIZE
bool        use_resize = TRUE;
#endif

    while ((i = getopt(argc, argv, "n:rtT:")) != EOF) {
	switch (i) {
	case 'n':
	    if ((MAXLINES = atoi(optarg)) < 1)
		usage();
	    break;
#if CAN_RESIZE
	case 'r':
	    use_resize = FALSE;
	    break;
#endif
#ifdef TRACE
	case 'T':
	    trace(atoi(optarg));
	    break;
	case 't':
	    trace(TRACE_CALLS);
	    break;
#endif
	default:
	    usage();
	}
    }
    if (optind + 1 != argc)
	usage();

    if ((lines = (char **)calloc(MAXLINES+2, sizeof(*lines))) == 0)
	usage();

    fname = argv[optind];
    if ((fp = fopen(fname, "r")) == 0) {
	perror(fname);
	return EXIT_FAILURE;
    }

    (void) signal(SIGINT, finish);      /* arrange interrupts to terminate */
#if CAN_RESIZE
    if (use_resize)
	(void) signal(SIGWINCH, adjust); /* arrange interrupts to resize */
#endif

    /* slurp the file */
    for (lptr = &lines[0]; (lptr - lines) < MAXLINES; lptr++) {
	char temp[BUFSIZ], *s, *d;
	int  col;

	if (fgets(buf, sizeof(buf), fp) == 0)
	    break;

	/* convert tabs so that shift will work properly */
	for (s = buf, d = temp, col = 0; (*d = *s) != '\0'; s++) {
	    if (*d == '\n') {
		*d = '\0';
		break;
	    } else if (*d == '\t') {
		col = (col | 7) + 1;
		while ((d-temp) != col)
		    *d++ = ' ';
	    } else if (isprint(*d)) {
		col++;
		d++;
	    } else {
		sprintf(d, "\\%03o", *s & 0xff);
		d += strlen(d);
		col = (d - temp);
	    }
	}
	*lptr = strdup(temp);
    }
    (void) fclose(fp);
    length = lptr - lines;

    (void) initscr();      /* initialize the curses library */
    keypad(stdscr, TRUE);  /* enable keyboard mapping */
    (void) nonl();         /* tell curses not to do NL->CR/NL on output */
    (void) cbreak();       /* take input chars one at a time, no wait for \n */
    (void) noecho();       /* don't echo input */
    idlok(stdscr, TRUE);   /* allow use of insert/delete line */

    lptr = lines;
    while (!done) {
	int n, c;
	bool got_number;

	show_all();

	got_number = FALSE;
	n = 0;
        for (;;) {
#if CAN_RESIZE
	    if (interrupted)
		adjust(0);
#endif
	    waiting = TRUE;
	    c = getch();
	    waiting = FALSE;
	    if ((c < 127) && isdigit(c)) {
		if (!got_number) {
		    mvprintw(0,0, "Count: ");
		    clrtoeol();
		}
		addch(c);
		n = 10 * n + (c - '0');
		got_number = TRUE;
	    }
	    else
		break;
	}
	if (!got_number && n == 0)
	    n = 1;

	switch(c) {
	case KEY_DOWN:
	case 'n':
	    olptr = lptr;
	    for (i = 0; i < n; i++)
		if ((lptr - lines) < (length - LINES + 1))
		    lptr++;
		else
		    break;
	    wscrl(stdscr, lptr - olptr);
	    break;

	case KEY_UP:
	case 'p':
	    olptr = lptr;
	    for (i = 0; i < n; i++)
		if (lptr > lines)
		    lptr--;
		else
		    break;
	    wscrl(stdscr, lptr - olptr);
	    break;

	case 'h':
	case KEY_HOME:
	    lptr = lines;
	    break;

	case 'e':
	case KEY_END:
	    if (length > LINES)
		lptr = lines + length - LINES + 1;
	    else
		lptr = lines;
	    break;

	case 'r':
	case KEY_RIGHT:
	    shift++;
	    break;

	case 'l':
	case KEY_LEFT:
	    if (shift)
		shift--;
	    else
		beep();
	    break;

	case 'q':
	    done = TRUE;
	    break;

#ifdef KEY_RESIZE
	case KEY_RESIZE: 	/* ignore this; ncurses will repaint */
	    break;
#endif
#if CAN_RESIZE
	case ERR:
	    break;
#endif
	default:
	    beep();
	}
    }

    finish(0);			/* we're done */
}
Beispiel #12
0
 inline bool Calendar::isEndOfMonth(const Date& d) const {
     return (d.month() != adjust(d+1).month());
 }
Beispiel #13
0
void CChatLog::output(enum CHAT type, BYTE* buf, ...)
{
	SYSTEMTIME t = _gettime(NULL);

	if (_checkdate(&t) == false)
		return;	// ファイル関連の障害ぐらい...
 

	va_list ap;
	va_start(ap, buf);


	switch (type)
	{
		case CT_ZONEINFO:
			{
				int p1 = va_arg(ap, int);	// mapname
				TCHAR* name = va_arg(ap, TCHAR*);
				adjust(_T("SYS %s has connected\r\n"), name);
				adjust(_T("MAP %s (%04d-%02d-%02d %02d:%02d:%02d)\r\n"), buf+p1, t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond);
			}
			break;

		case CT_CHANGEMAP:
		case CT_CHANGEZONE:
			{
				int p1 = va_arg(ap, int);	// mapname
				adjust(_T("MAP %s (%04d-%02d-%02d %02d:%02d:%02d)\r\n"), buf+p1, t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond);
			}
			break;

		case CT_MVP:
			{
				DWORD AID = va_arg(ap, DWORD);	// AID
				adjust(_T("MVP %02d:%02d:%02d AID=%08X\r\n"), t.wHour, t.wMinute, t.wSecond, AID);
			}
			break;

		case CT_NORMALCHAT:
		case CT_NORMALCHAT_OWN:
			{
				int p1 = va_arg(ap, int);	// body
				adjust(_T("%s %02d:%02d:%02d %s\r\n"), _T("NOR"), t.wHour, t.wMinute, t.wSecond, buf+p1);
			}
			break;

		case CT_SENDWHISPER:
			{
				int p1 = va_arg(ap, int);	// name
				int p2 = va_arg(ap, int);	// body
				adjust(_T("WIS %02d:%02d:%02d TO %s : %s\r\n"), t.wHour, t.wMinute, t.wSecond, buf+p1, buf+p2);
			}
			break;

		case CT_RECVWHISPER:
			{
				int p1 = va_arg(ap, int);	// name
				int p2 = va_arg(ap, int);	// body
				adjust(_T("WIS %02d:%02d:%02d FROM %s : %s\r\n"), t.wHour, t.wMinute, t.wSecond, buf+p1, buf+p2);
			}
			break;

		case CT_BROADCAST:
			{
				int p1 = va_arg(ap, int);	// body
				adjust(_T("%s %02d:%02d:%02d %s\r\n"), _T("GOD"), t.wHour, t.wMinute, t.wSecond, buf+p1);
			}
			break;

		case CT_PTCHAT:
			{
				int p1 = va_arg(ap, int);	// body
				adjust(_T("%s %02d:%02d:%02d %s\r\n"), _T("PRT"), t.wHour, t.wMinute, t.wSecond, buf+p1);
			}
			break;

		case CT_GUILDCHAT:
			{
				int p1 = va_arg(ap, int);	// body
				adjust(_T("%s %02d:%02d:%02d %s\r\n"), _T("GLD"), t.wHour, t.wMinute, t.wSecond, buf+p1);
			}
			break;

		case CT_TALKIE:
			{
				int p1 = va_arg(ap, int);	// body
				adjust(_T("%s %02d:%02d:%02d %s\r\n"), _T("TLK"), t.wHour, t.wMinute, t.wSecond, buf+p1);
			}
			break;

		case CT_LOCALBROADCAST:
			{
				int p1 = va_arg(ap, int);	// body
				adjust(_T("%s %02d:%02d:%02d %s\r\n"), _T("LBC"), t.wHour, t.wMinute, t.wSecond, buf+p1);
			}
			break;
	}


	va_end(ap);
}
Beispiel #14
0
void ViewEngineering::onRender( RenderContext & context, const RectInt & window )
{
	GameDocument * pDoc = (GameDocument *)document();
	if ( pDoc == NULL )
		return;

	UniverseContext * pContext = pDoc->context();
	ASSERT( pContext );
	NounShip * pShip = pDoc->ship();
	ASSERT( pShip );

	// get the time elapsed
	float t = context.elapsed();
	// calculate the distance from the ship based upon it's radius
	float cameraDistance = pShip->radius() * 2.5f;
	// calculate the camera frame and position
	Matrix33 cameraFrame( pShip->frame() );
	cameraFrame.rotate( PI / 4, ViewGame::s_CameraTime * (PI / 4), 0 );
	Vector3	cameraPosition( pShip->worldPosition() - (cameraFrame.k * cameraDistance) );

	if ( ViewGame::s_CameraTime < CAMERA_SNAP_TIME )
	{
		// if ship is moving, keep it from jumping around while the camera is animating
		if ( m_Adjust )
		{
			Vector3 position( pShip->worldPosition() );
			Vector3 adjust( position - m_AdjustPosition );
			m_AdjustPosition = position;

			ViewGame::s_CameraPosition += adjust;
		}
		else
		{
			m_AdjustPosition = pShip->worldPosition();
			m_Adjust = true;
		}

		float d = ViewGame::s_CameraTime / CAMERA_SNAP_TIME;
		// move the camera
		Vector3 deltaPosition( cameraPosition - ViewGame::s_CameraPosition );
		ViewGame::s_CameraPosition += deltaPosition * d;

		// update the camera frame
		ViewGame::s_CameraFrame.i += (cameraFrame.i - ViewGame::s_CameraFrame.i) * d;
		ViewGame::s_CameraFrame.j += (cameraFrame.j - ViewGame::s_CameraFrame.j) * d;
		ViewGame::s_CameraFrame.k += (cameraFrame.k - ViewGame::s_CameraFrame.k) * d;
		ViewGame::s_CameraFrame.orthoNormalizeXY();
	}
	else
	{
		// animation is over, snap directly to the desired frame/position
		ViewGame::s_CameraFrame = cameraFrame;
		ViewGame::s_CameraPosition = cameraPosition;
		m_Adjust = false;
	}

	m_UpdateStatus += t;
	if ( m_UpdateStatus > 1.0f )
	{
		m_UpdateStatus = 0.0f;

		// update the ship status
		String shipStatus;
		shipStatus += String().format("Hull:<X;75;Color;ff00ffff>%d%%</Color>\n", int(pShip->damageRatioInv() * 100) );
		shipStatus += String().format("Energy:<X;75;Color;ff00ffff>%d / %d</Color>\n", pShip->energy(), pShip->maxEnergy() );
		shipStatus += String().format("Velocity:<X;75;Color;ff00ffff>%.1f / %.1f</Color>\n", pShip->velocity(), pShip->maxVelocity() );
		shipStatus += String().format("Signature:<X;75;Color;ff00ffff>%.1f</Color>\n", pShip->signature() );

		shipStatus += "\nSYSTEMS:\n";

		// display armor status
		for(int i=0;i<pShip->childCount();i++)
			if ( WidgetCast<GadgetArmor>( pShip->child(i) ) )
			{
				GadgetArmor * pArmor = (GadgetArmor *)pShip->child(i);
				shipStatus += String().format("%s<X;100>%d%%\n", 
					pArmor->nounContext()->name(), 
					(pArmor->armor() * 100 ) / pArmor->strength() );
			}
		// display shield status
		for(i=0;i<pShip->childCount();i++)
			if ( WidgetCast<GadgetShield>( pShip->child(i) ) )
			{
				GadgetShield * pShield = (GadgetShield *)pShip->child(i);
				shipStatus += String().format("%s<X;100>%d%%\n", 
					pShield->nounContext()->name(), 
					(pShield->charge() * 100 ) / pShield->maxCharge() );
			}

		for(i=0;i<pShip->childCount();i++)
			if ( WidgetCast<NounGadget>( pShip->child(i) ) )
			{
				NounGadget * pGadget = (NounGadget *)pShip->child(i);
				if ( WidgetCast<GadgetArmor>( pGadget ) )
					continue;
				if ( WidgetCast<GadgetShield>( pGadget ) )
					continue;
				
				shipStatus += String().format("%s<X;100>%d%%\n", 
					pGadget->nounContext()->name(), 
					int( pGadget->damageRatioInv() * 100 ) );
			}

		m_pShipStatus->setText( shipStatus );
	}
	
	if ( m_pLayoutRepair->visible() )
	{
		for(int i=0;i<pShip->repairCount();i++)
			GetButton<ButtonGadget>( m_pRepairQueue, i )->setGadget( pShip->repair( i ) );

		// remove excess buttons
		m_pRepairQueue->cullChildren( pShip->repairCount() );
	}

	//----------------------------------------------------------------------------

	// update the active zone
	pContext->setActiveZone( ViewGame::s_CameraPosition );

	// create our render context
	RenderContext engineeringContext( context );
	engineeringContext.setPosition( ViewGame::s_CameraPosition );
	engineeringContext.setFrame(  ViewGame::s_CameraFrame );
	engineeringContext.setTime( pContext->tick() * TICK_DURATION_S );

	//----------------------------------------------------------------------------

	// render the universe
	pContext->render( engineeringContext, 
		~ViewGame::s_CameraFrame, ViewGame::s_CameraFrame * (-ViewGame::s_CameraPosition) );
}
Beispiel #15
0
void Batch::Prepare(View* view, bool setModelTransform) const
{
    if (!vertexShader_ || !pixelShader_)
        return;
    
    Graphics* graphics = view->GetGraphics();
    Renderer* renderer = view->GetRenderer();
    Node* cameraNode = camera_ ? camera_->GetNode() : 0;
    Light* light = lightQueue_ ? lightQueue_->light_ : 0;
    Texture2D* shadowMap = lightQueue_ ? lightQueue_->shadowMap_ : 0;

    // Set pass / material-specific renderstates
    if (pass_ && material_)
    {
        bool isShadowPass = pass_->GetType() == PASS_SHADOW;
        
        BlendMode blend = pass_->GetBlendMode();
        // Turn additive blending into subtract if the light is negative
        if (light && light->IsNegative())
        {
            if (blend == BLEND_ADD)
                blend = BLEND_SUBTRACT;
            else if (blend == BLEND_ADDALPHA)
                blend = BLEND_SUBTRACTALPHA;
        }
        
        graphics->SetBlendMode(blend);
        renderer->SetCullMode(isShadowPass ? material_->GetShadowCullMode() : material_->GetCullMode(), camera_);
        if (!isShadowPass)
        {
            const BiasParameters& depthBias = material_->GetDepthBias();
            graphics->SetDepthBias(depthBias.constantBias_, depthBias.slopeScaledBias_);
        }
        graphics->SetDepthTest(pass_->GetDepthTestMode());
        graphics->SetDepthWrite(pass_->GetDepthWrite());
    }
    
    // Set shaders first. The available shader parameters and their register/uniform positions depend on the currently set shaders
    graphics->SetShaders(vertexShader_, pixelShader_);
    
    // Set global (per-frame) shader parameters
    if (graphics->NeedParameterUpdate(SP_FRAME, (void*)0))
        view->SetGlobalShaderParameters();
    
    // Set camera shader parameters
    unsigned cameraHash = overrideView_ ? (unsigned)(size_t)camera_ + 4 : (unsigned)(size_t)camera_;
    if (graphics->NeedParameterUpdate(SP_CAMERA, reinterpret_cast<void*>(cameraHash)))
        view->SetCameraShaderParameters(camera_, true, overrideView_);
    
    // Set viewport shader parameters
    IntVector2 rtSize = graphics->GetRenderTargetDimensions();
    IntRect viewport = graphics->GetViewport();
    unsigned viewportHash = (viewport.left_) | (viewport.top_ << 8) | (viewport.right_ << 16) | (viewport.bottom_ << 24);
    
    if (graphics->NeedParameterUpdate(SP_VIEWPORT, reinterpret_cast<void*>(viewportHash)))
    {
        float rtWidth = (float)rtSize.x_;
        float rtHeight = (float)rtSize.y_;
        float widthRange = 0.5f * viewport.Width() / rtWidth;
        float heightRange = 0.5f * viewport.Height() / rtHeight;
        
        #ifdef URHO3D_OPENGL
        Vector4 bufferUVOffset(((float)viewport.left_) / rtWidth + widthRange,
            1.0f - (((float)viewport.top_) / rtHeight + heightRange), widthRange, heightRange);
        #else
        Vector4 bufferUVOffset((0.5f + (float)viewport.left_) / rtWidth + widthRange,
            (0.5f + (float)viewport.top_) / rtHeight + heightRange, widthRange, heightRange);
        #endif
        graphics->SetShaderParameter(VSP_GBUFFEROFFSETS, bufferUVOffset);
        
        float sizeX = 1.0f / rtWidth;
        float sizeY = 1.0f / rtHeight;
        graphics->SetShaderParameter(PSP_GBUFFERINVSIZE, Vector4(sizeX, sizeY, 0.0f, 0.0f));
    }
    
    // Set model or skinning transforms
    if (setModelTransform && graphics->NeedParameterUpdate(SP_OBJECTTRANSFORM, worldTransform_))
    {
        if (geometryType_ == GEOM_SKINNED)
        {
            graphics->SetShaderParameter(VSP_SKINMATRICES, reinterpret_cast<const float*>(worldTransform_), 
                12 * numWorldTransforms_);
        }
        else
            graphics->SetShaderParameter(VSP_MODEL, *worldTransform_);
        
        // Set the orientation for billboards, either from the object itself or from the camera
        if (geometryType_ == GEOM_BILLBOARD)
        {
            if (numWorldTransforms_ > 1)
                graphics->SetShaderParameter(VSP_BILLBOARDROT, worldTransform_[1].RotationMatrix());
            else
                graphics->SetShaderParameter(VSP_BILLBOARDROT, cameraNode->GetWorldRotation().RotationMatrix());
        }
    }
    
    // Set zone-related shader parameters
    BlendMode blend = graphics->GetBlendMode();
    // If the pass is additive, override fog color to black so that shaders do not need a separate additive path
    bool overrideFogColorToBlack = blend == BLEND_ADD || blend == BLEND_ADDALPHA;
    unsigned zoneHash = (unsigned)(size_t)zone_;
    if (overrideFogColorToBlack)
        zoneHash += 0x80000000;
    if (zone_ && graphics->NeedParameterUpdate(SP_ZONE, reinterpret_cast<void*>(zoneHash)))
    {
        graphics->SetShaderParameter(VSP_AMBIENTSTARTCOLOR, zone_->GetAmbientStartColor());
        graphics->SetShaderParameter(VSP_AMBIENTENDCOLOR, zone_->GetAmbientEndColor().ToVector4() - zone_->GetAmbientStartColor().ToVector4());
        
        const BoundingBox& box = zone_->GetBoundingBox();
        Vector3 boxSize = box.Size();
        Matrix3x4 adjust(Matrix3x4::IDENTITY);
        adjust.SetScale(Vector3(1.0f / boxSize.x_, 1.0f / boxSize.y_, 1.0f / boxSize.z_));
        adjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f));
        Matrix3x4 zoneTransform = adjust * zone_->GetInverseWorldTransform();
        graphics->SetShaderParameter(VSP_ZONE, zoneTransform);
        
        graphics->SetShaderParameter(PSP_AMBIENTCOLOR, zone_->GetAmbientColor());
        graphics->SetShaderParameter(PSP_FOGCOLOR, overrideFogColorToBlack ? Color::BLACK : zone_->GetFogColor());
        
        float farClip = camera_->GetFarClip();
        float fogStart = Min(zone_->GetFogStart(), farClip);
        float fogEnd = Min(zone_->GetFogEnd(), farClip);
        if (fogStart >= fogEnd * (1.0f - M_LARGE_EPSILON))
            fogStart = fogEnd * (1.0f - M_LARGE_EPSILON);
        float fogRange = Max(fogEnd - fogStart, M_EPSILON);
        Vector4 fogParams(fogEnd / farClip, farClip / fogRange, 0.0f, 0.0f);
        
        Node* zoneNode = zone_->GetNode();
        if (zone_->GetHeightFog() && zoneNode)
        {
            Vector3 worldFogHeightVec = zoneNode->GetWorldTransform() * Vector3(0.0f, zone_->GetFogHeight(), 0.0f);
            fogParams.z_ = worldFogHeightVec.y_;
            fogParams.w_ = zone_->GetFogHeightScale() / Max(zoneNode->GetWorldScale().y_, M_EPSILON);
        }
        
        graphics->SetShaderParameter(PSP_FOGPARAMS, fogParams);
    }
    
    // Set light-related shader parameters
    if (lightQueue_)
    {
        if (graphics->NeedParameterUpdate(SP_VERTEXLIGHTS, lightQueue_) && graphics->HasShaderParameter(VS, VSP_VERTEXLIGHTS))
        {
            Vector4 vertexLights[MAX_VERTEX_LIGHTS * 3];
            const PODVector<Light*>& lights = lightQueue_->vertexLights_;
            
            for (unsigned i = 0; i < lights.Size(); ++i)
            {
                Light* vertexLight = lights[i];
                Node* vertexLightNode = vertexLight->GetNode();
                LightType type = vertexLight->GetLightType();
                
                // Attenuation
                float invRange, cutoff, invCutoff;
                if (type == LIGHT_DIRECTIONAL)
                    invRange = 0.0f;
                else
                    invRange = 1.0f / Max(vertexLight->GetRange(), M_EPSILON);
                if (type == LIGHT_SPOT)
                {
                    cutoff = Cos(vertexLight->GetFov() * 0.5f);
                    invCutoff = 1.0f / (1.0f - cutoff);
                }
                else
                {
                    cutoff = -1.0f;
                    invCutoff = 1.0f;
                }
                
                // Color
                float fade = 1.0f;
                float fadeEnd = vertexLight->GetDrawDistance();
                float fadeStart = vertexLight->GetFadeDistance();
                
                // Do fade calculation for light if both fade & draw distance defined
                if (vertexLight->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
                    fade = Min(1.0f - (vertexLight->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
                
                Color color = vertexLight->GetEffectiveColor() * fade;
                vertexLights[i * 3] = Vector4(color.r_, color.g_, color.b_, invRange);
                
                // Direction
                vertexLights[i * 3 + 1] = Vector4(-(vertexLightNode->GetWorldDirection()), cutoff);
                
                // Position
                vertexLights[i * 3 + 2] = Vector4(vertexLightNode->GetWorldPosition(), invCutoff);
            }
            
            if (lights.Size())
                graphics->SetShaderParameter(VSP_VERTEXLIGHTS, vertexLights[0].Data(), lights.Size() * 3 * 4);
        }
    }
    
    if (light && graphics->NeedParameterUpdate(SP_LIGHT, light))
    {
        // Deferred light volume batches operate in a camera-centered space. Detect from material, zone & pass all being null
        bool isLightVolume = !material_ && !pass_ && !zone_;
        
        Matrix3x4 cameraEffectiveTransform = camera_->GetEffectiveWorldTransform();
        Vector3 cameraEffectivePos = cameraEffectiveTransform.Translation();

        Node* lightNode = light->GetNode();
        Matrix3 lightWorldRotation = lightNode->GetWorldRotation().RotationMatrix();
        
        graphics->SetShaderParameter(VSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
        
        float atten = 1.0f / Max(light->GetRange(), M_EPSILON);
        graphics->SetShaderParameter(VSP_LIGHTPOS, Vector4(lightNode->GetWorldPosition(), atten));
        
        if (graphics->HasShaderParameter(VS, VSP_LIGHTMATRICES))
        {
            switch (light->GetLightType())
            {
            case LIGHT_DIRECTIONAL:
                {
                    Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
                    unsigned numSplits = lightQueue_->shadowSplits_.Size();
                    for (unsigned i = 0; i < numSplits; ++i)
                        CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, Vector3::ZERO);
                    
                    graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
                }
                break;
                
            case LIGHT_SPOT:
                {
                    Matrix4 shadowMatrices[2];
                    
                    CalculateSpotMatrix(shadowMatrices[0], light, Vector3::ZERO);
                    bool isShadowed = shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP);
                    if (isShadowed)
                        CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, Vector3::ZERO);
                    
                    graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
                }
                break;
                
            case LIGHT_POINT:
                {
                    Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix());
                    // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
                    // the next parameter
                    #ifdef URHO3D_OPENGL
                    graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 16);
                    #else
                    graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 12);
                    #endif
                }
                break;
            }
        }
        
        float fade = 1.0f;
        float fadeEnd = light->GetDrawDistance();
        float fadeStart = light->GetFadeDistance();
        
        // Do fade calculation for light if both fade & draw distance defined
        if (light->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd)
            fade = Min(1.0f - (light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f);
        
        // Negative lights will use subtract blending, so write absolute RGB values to the shader parameter
        graphics->SetShaderParameter(PSP_LIGHTCOLOR, Color(light->GetEffectiveColor().Abs(),
            light->GetEffectiveSpecularIntensity()) * fade);
        graphics->SetShaderParameter(PSP_LIGHTDIR, lightWorldRotation * Vector3::BACK);
        graphics->SetShaderParameter(PSP_LIGHTPOS, Vector4((isLightVolume ? (lightNode->GetWorldPosition() -
            cameraEffectivePos) : lightNode->GetWorldPosition()), atten));
        
        if (graphics->HasShaderParameter(PS, PSP_LIGHTMATRICES))
        {
            switch (light->GetLightType())
            {
            case LIGHT_DIRECTIONAL:
                {
                    Matrix4 shadowMatrices[MAX_CASCADE_SPLITS];
                    unsigned numSplits = lightQueue_->shadowSplits_.Size();
                    for (unsigned i = 0; i < numSplits; ++i)
                    {
                        CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, isLightVolume ? cameraEffectivePos :
                            Vector3::ZERO);
                    }
                    graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits);
                }
                break;
                
            case LIGHT_SPOT:
                {
                    Matrix4 shadowMatrices[2];
                    
                    CalculateSpotMatrix(shadowMatrices[0], light, cameraEffectivePos);
                    bool isShadowed = lightQueue_->shadowMap_ != 0;
                    if (isShadowed)
                    {
                        CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, isLightVolume ? cameraEffectivePos :
                            Vector3::ZERO);
                    }
                    
                    graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16);
                }
                break;
                
            case LIGHT_POINT:
                {
                    Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix());
                    // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite
                    // the next parameter
                    #ifdef URHO3D_OPENGL
                    graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 16);
                    #else
                    graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 12);
                    #endif
                }
                break;
            }
        }
        
        // Set shadow mapping shader parameters
        if (shadowMap)
        {
            {
                // Calculate point light shadow sampling offsets (unrolled cube map)
                unsigned faceWidth = shadowMap->GetWidth() / 2;
                unsigned faceHeight = shadowMap->GetHeight() / 3;
                float width = (float)shadowMap->GetWidth();
                float height = (float)shadowMap->GetHeight();
                #ifdef URHO3D_OPENGL
                    float mulX = (float)(faceWidth - 3) / width;
                    float mulY = (float)(faceHeight - 3) / height;
                    float addX = 1.5f / width;
                    float addY = 1.5f / height;
                #else
                    float mulX = (float)(faceWidth - 4) / width;
                    float mulY = (float)(faceHeight - 4) / height;
                    float addX = 2.5f / width;
                    float addY = 2.5f / height;
                #endif
                // If using 4 shadow samples, offset the position diagonally by half pixel
                if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT)
                {
                    addX -= 0.5f / width;
                    addY -= 0.5f / height;
                }
                graphics->SetShaderParameter(PSP_SHADOWCUBEADJUST, Vector4(mulX, mulY, addX, addY));
            }
            
            {
                // Calculate shadow camera depth parameters for point light shadows and shadow fade parameters for
                //  directional light shadows, stored in the same uniform
                Camera* shadowCamera = lightQueue_->shadowSplits_[0].shadowCamera_;
                float nearClip = shadowCamera->GetNearClip();
                float farClip = shadowCamera->GetFarClip();
                float q = farClip / (farClip - nearClip);
                float r = -q * nearClip;
                
                const CascadeParameters& parameters = light->GetShadowCascade();
                float viewFarClip = camera_->GetFarClip();
                float shadowRange = parameters.GetShadowRange();
                float fadeStart = parameters.fadeStart_ * shadowRange / viewFarClip;
                float fadeEnd = shadowRange / viewFarClip;
                float fadeRange = fadeEnd - fadeStart;
                
                graphics->SetShaderParameter(PSP_SHADOWDEPTHFADE, Vector4(q, r, fadeStart, 1.0f / fadeRange));
            }
            
            {
                float intensity = light->GetShadowIntensity();
                float fadeStart = light->GetShadowFadeDistance();
                float fadeEnd = light->GetShadowDistance();
                if (fadeStart > 0.0f && fadeEnd > 0.0f && fadeEnd > fadeStart)
                    intensity = Lerp(intensity, 1.0f, Clamp((light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f));
                float pcfValues = (1.0f - intensity);
                float samples = renderer->GetShadowQuality() >= SHADOWQUALITY_HIGH_16BIT ? 4.0f : 1.0f;

                graphics->SetShaderParameter(PSP_SHADOWINTENSITY, Vector4(pcfValues / samples, intensity, 0.0f, 0.0f));
            }
            
            float sizeX = 1.0f / (float)shadowMap->GetWidth();
            float sizeY = 1.0f / (float)shadowMap->GetHeight();
            graphics->SetShaderParameter(PSP_SHADOWMAPINVSIZE, Vector4(sizeX, sizeY, 0.0f, 0.0f));
            
            Vector4 lightSplits(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE);
            if (lightQueue_->shadowSplits_.Size() > 1)
                lightSplits.x_ = lightQueue_->shadowSplits_[0].farSplit_ / camera_->GetFarClip();
            if (lightQueue_->shadowSplits_.Size() > 2)
                lightSplits.y_ = lightQueue_->shadowSplits_[1].farSplit_ / camera_->GetFarClip();
            if (lightQueue_->shadowSplits_.Size() > 3)
                lightSplits.z_ = lightQueue_->shadowSplits_[2].farSplit_ / camera_->GetFarClip();
            
            graphics->SetShaderParameter(PSP_SHADOWSPLITS, lightSplits);
        }
    }
    
    // Set material-specific shader parameters and textures
    if (material_)
    {
        if (graphics->NeedParameterUpdate(SP_MATERIAL, material_))
        {
            // Update shader parameter animations
            material_->UpdateShaderParameterAnimations();

            const HashMap<StringHash, MaterialShaderParameter>& parameters = material_->GetShaderParameters();
            for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
                graphics->SetShaderParameter(i->first_, i->second_.value_);
        }
        
        const SharedPtr<Texture>* textures = material_->GetTextures();
        for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i)
        {
            TextureUnit unit = (TextureUnit)i;
            if (textures[i] && graphics->HasTextureUnit(unit))
                graphics->SetTexture(i, textures[i]);
        }
    }
    
    // Set light-related textures
    if (light)
    {
        if (shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP))
            graphics->SetTexture(TU_SHADOWMAP, shadowMap);
        if (graphics->HasTextureUnit(TU_LIGHTRAMP))
        {
            Texture* rampTexture = light->GetRampTexture();
            if (!rampTexture)
                rampTexture = renderer->GetDefaultLightRamp();
            graphics->SetTexture(TU_LIGHTRAMP, rampTexture);
        }
        if (graphics->HasTextureUnit(TU_LIGHTSHAPE))
        {
            Texture* shapeTexture = light->GetShapeTexture();
            if (!shapeTexture && light->GetLightType() == LIGHT_SPOT)
                shapeTexture = renderer->GetDefaultLightSpot();
            graphics->SetTexture(TU_LIGHTSHAPE, shapeTexture);
        }
    }
}
Beispiel #16
0
//! show on scene
void Edge::show()
{
	adjust();
	QGraphicsItem::show();
	name->show();
}
Beispiel #17
0
	//現在値を強制変更
	void setNow(const float now)
	{
		m_now = now;
		adjust();
	}
Beispiel #18
0
void Edge::setSourceNode(Node *node)
{
    source = node;
    adjust();
}
Beispiel #19
0
const RotMat &RotMat::rotateZ( GLfloat theta, bool postmult ) {
  return adjust( Angel::RotateZ( theta ), postmult );
}
Beispiel #20
0
void Edge::setDestNode(Node *node)
{
    dest = node;
    adjust();
}
void QHexEditPrivate::setAddressArea(bool addressArea)
{
    _addressArea = addressArea;
    adjust();
    setCursorPos(_cursorPosition);
}
void pop(Node *heap, int p, int &len)
{
    heap[p] = heap[--len];
    adjust(heap, p, len);
}
void QHexEditPrivate::setFont(const QFont &font)
{
    QWidget::setFont(font);
    adjust();
}
Beispiel #24
0
void
ACE_SizeCDR::adjust (size_t size)
{
  adjust (size, size);
}
void QHexEditPrivate::setAddressOffset(int offset)
{
    _addressOffset = offset;
    adjust();
}
Beispiel #26
0
void
StereoHarm::processReplacing (float **inputs,
								float **outputs,
								int sampleFrames)
{

    int i;
	param->PERIOD = sampleFrames;
	param->fPERIOD = param->PERIOD;
	adjust(DS_state);

	float *inputs2[2];
	inputs2[0] = new float[nPERIOD+100];
	inputs2[1] = new float[nPERIOD+100];

    if(DS_state != 0) {
        memcpy(templ, inputs[0],sizeof(float)*param->PERIOD);
        memcpy(tempr, inputs[1],sizeof(float)*param->PERIOD);
        U_Resample->out(templ,tempr,inputs2[0],inputs2[1],param->PERIOD,u_up);
    }
	else
	{
        memcpy(inputs2[0], inputs[0],sizeof(float)*param->PERIOD);
        memcpy(inputs2[1], inputs[1],sizeof(float)*param->PERIOD);
	}


    for (i = 0; i < nPERIOD; i++) {


        outil[i] = inputs2[0][i] * (1.0f - lrcross) + inputs2[1][i] * lrcross;
        if (outil[i] > 1.0)
            outil[i] = 1.0f;
        if (outil[i] < -1.0)
            outil[i] = -1.0f;

        outir[i] = inputs2[1][i] * (1.0f - lrcross) + inputs2[0][i] * lrcross;
        if (outir[i] > 1.0)
            outir[i] = 1.0f;
        if (outir[i] < -1.0)
            outir[i] = -1.0f;

    }

    if ((PMIDI) || (PSELECT)) {
        PSl->ratio = param->r__ratio[1];
        PSr->ratio = param->r__ratio[2];
    }

    if (PSl->ratio != 1.0f) {
        PSl->smbPitchShift (PSl->ratio, nPERIOD, window, hq, nfSAMPLE_RATE, outil, outol);
    } else
        memcpy(outol,outil,sizeof(float)*nPERIOD);


    if (PSr->ratio != 1.0f) {
        PSr->smbPitchShift (PSr->ratio, nPERIOD, window, hq, nfSAMPLE_RATE, outir, outor);
    } else
        memcpy(outor,outir,sizeof(float)*nPERIOD);


    if(DS_state != 0) {
        D_Resample->out(outol,outor,templ,tempr,nPERIOD,u_down);
    } else {
        memcpy(templ, outol,sizeof(float)*param->PERIOD);
        memcpy(tempr, outor,sizeof(float)*param->PERIOD);

    }


    for (i = 0; i < param->PERIOD; i++) {
        outputs[0][i] = templ[i] * gainl;
        outputs[1][i] = tempr[i] * gainr;
    }
	delete[] inputs2[0];
	delete[] inputs2[1];


};
Beispiel #27
0
bool SessionImpl::getIncoming(IncomingMessages::Handler& handler, qpid::messaging::Duration timeout)
{
    return incoming.get(handler, adjust(timeout));
}
Beispiel #28
0
heapify(struct node *a[],int n)
{
	int i;
	for(i=n/2;i>=1;i--)
	 adjust(a,i,n);
}
Beispiel #29
0
void QHexEdit::resizeEvent(QResizeEvent *)
{
    adjust();
}
Beispiel #30
0
Vector Orientation::variance_from_sd(float sdx, float sdy, float sdz) const {
  Vector result(sdx, sdy, sdz);
  adjust(result);
  for (int n = 0; n < 3; n++) result[n] *= result[n];
  return result;
}