示例#1
0
void b_Acoeff(const emlrtStack *sp, real_T ksi, real_T j, const emxArray_real_T *
              x, real_T t, const emxArray_real_T *gridT, emxArray_real_T *vals)
{
  emxArray_real_T *b;
  emxArray_real_T *r8;
  int32_T b_x;
  int32_T i;
  emxArray_boolean_T *b_t;
  real_T c_x;
  emxArray_boolean_T *c_t;
  emxArray_real_T *z0;
  emxArray_real_T *d_x;
  emxArray_real_T *e_x;
  emxArray_real_T *r9;
  int32_T b_b[2];
  int32_T f_x[2];
  emxArray_real_T *g_x;
  emxArray_real_T *r10;
  const mxArray *y;
  static const int32_T iv16[2] = { 1, 45 };

  const mxArray *m6;
  char_T cv18[45];
  static const char_T cv19[45] = { 'C', 'o', 'd', 'e', 'r', ':', 't', 'o', 'o',
    'l', 'b', 'o', 'x', ':', 'm', 't', 'i', 'm', 'e', 's', '_', 'n', 'o', 'D',
    'y', 'n', 'a', 'm', 'i', 'c', 'S', 'c', 'a', 'l', 'a', 'r', 'E', 'x', 'p',
    'a', 'n', 's', 'i', 'o', 'n' };

  const mxArray *b_y;
  static const int32_T iv17[2] = { 1, 21 };

  char_T cv20[21];
  static const char_T cv21[21] = { 'C', 'o', 'd', 'e', 'r', ':', 'M', 'A', 'T',
    'L', 'A', 'B', ':', 'i', 'n', 'n', 'e', 'r', 'd', 'i', 'm' };

  emxArray_boolean_T *d_t;
  real_T h_x;
  emxArray_boolean_T *e_t;
  emxArray_real_T *i_x;
  emxArray_real_T *r11;
  emxArray_real_T *j_x;
  emxArray_real_T *r12;
  emxArray_real_T *z1;
  int32_T b_z0[2];
  emxArray_real_T *c_z0;
  emxArray_real_T *k_x;
  const mxArray *c_y;
  static const int32_T iv18[2] = { 1, 45 };

  const mxArray *d_y;
  static const int32_T iv19[2] = { 1, 21 };

  emlrtStack st;
  emlrtStack b_st;
  emlrtStack c_st;
  emlrtStack d_st;
  st.prev = sp;
  st.tls = sp->tls;
  b_st.prev = &st;
  b_st.tls = st.tls;
  c_st.prev = &b_st;
  c_st.tls = b_st.tls;
  d_st.prev = &b_st;
  d_st.tls = b_st.tls;
  emlrtHeapReferenceStackEnterFcnR2012b(sp);
  emxInit_real_T(sp, &b, 2, &bb_emlrtRTEI, true);
  emxInit_real_T(sp, &r8, 2, &bb_emlrtRTEI, true);

  /*  evaluate the coefficient A at the  boundary ksi=0 or ksi=1; */
  /*  for the index j which describes the time steps timePoints_j, at time t and space */
  /*  point x */
  /*  timePoints is a vector describing the time descritized domain */
  b_x = gridT->size[1];
  i = (int32_T)emlrtIntegerCheckFastR2012b(j, &emlrtDCI, sp);
  if (t <= gridT->data[emlrtDynamicBoundsCheckFastR2012b(i, 1, b_x, &d_emlrtBCI,
       sp) - 1]) {
    b_x = vals->size[0] * vals->size[1];
    vals->size[0] = 1;
    vals->size[1] = 1;
    emxEnsureCapacity(sp, (emxArray__common *)vals, b_x, (int32_T)sizeof(real_T),
                      &bb_emlrtRTEI);
    vals->data[0] = 0.0;
  } else {
    emxInit_boolean_T(sp, &b_t, 2, &bb_emlrtRTEI, true);
    b_x = b_t->size[0] * b_t->size[1];
    b_t->size[0] = 1;
    b_t->size[1] = 2 + x->size[1];
    emxEnsureCapacity(sp, (emxArray__common *)b_t, b_x, (int32_T)sizeof
                      (boolean_T), &bb_emlrtRTEI);
    b_x = gridT->size[1];
    i = (int32_T)j;
    b_t->data[0] = (t > gridT->data[emlrtDynamicBoundsCheckFastR2012b(i, 1, b_x,
      &e_emlrtBCI, sp) - 1]);
    b_x = gridT->size[1];
    i = (int32_T)((uint32_T)j + 1U);
    b_t->data[b_t->size[0]] = (t <= gridT->
      data[emlrtDynamicBoundsCheckFastR2012b(i, 1, b_x, &f_emlrtBCI, sp) - 1]);
    i = x->size[1];
    for (b_x = 0; b_x < i; b_x++) {
      b_t->data[b_t->size[0] * (b_x + 2)] = (x->data[x->size[0] * b_x] == ksi);
    }

    st.site = &pe_emlrtRSI;
    if (all(&st, b_t)) {
      b_x = gridT->size[1];
      i = (int32_T)j;
      emlrtDynamicBoundsCheckFastR2012b(i, 1, b_x, &c_emlrtBCI, sp);
      c_x = (t - gridT->data[(int32_T)j - 1]) / 3.1415926535897931;
      st.site = &emlrtRSI;
      if (c_x < 0.0) {
        b_st.site = &f_emlrtRSI;
        eml_error(&b_st);
      }

      b_x = vals->size[0] * vals->size[1];
      vals->size[0] = 1;
      vals->size[1] = 1;
      emxEnsureCapacity(sp, (emxArray__common *)vals, b_x, (int32_T)sizeof
                        (real_T), &bb_emlrtRTEI);
      vals->data[0] = muDoubleScalarSqrt(c_x);
    } else {
      emxInit_boolean_T(sp, &c_t, 2, &bb_emlrtRTEI, true);
      b_x = c_t->size[0] * c_t->size[1];
      c_t->size[0] = 1;
      c_t->size[1] = 2 + x->size[1];
      emxEnsureCapacity(sp, (emxArray__common *)c_t, b_x, (int32_T)sizeof
                        (boolean_T), &bb_emlrtRTEI);
      b_x = gridT->size[1];
      i = (int32_T)j;
      c_t->data[0] = (t > gridT->data[emlrtDynamicBoundsCheckFastR2012b(i, 1,
        b_x, &g_emlrtBCI, sp) - 1]);
      b_x = gridT->size[1];
      i = (int32_T)((uint32_T)j + 1U);
      c_t->data[c_t->size[0]] = (t <= gridT->
        data[emlrtDynamicBoundsCheckFastR2012b(i, 1, b_x, &h_emlrtBCI, sp) - 1]);
      i = x->size[1];
      for (b_x = 0; b_x < i; b_x++) {
        c_t->data[c_t->size[0] * (b_x + 2)] = (x->data[x->size[0] * b_x] != ksi);
      }

      emxInit_real_T(sp, &z0, 2, &cb_emlrtRTEI, true);
      emxInit_real_T(sp, &d_x, 2, &bb_emlrtRTEI, true);
      st.site = &qe_emlrtRSI;
      if (all(&st, c_t)) {
        st.site = &b_emlrtRSI;
        b_x = gridT->size[1];
        i = (int32_T)j;
        c_x = t - gridT->data[emlrtDynamicBoundsCheckFastR2012b(i, 1, b_x,
          &m_emlrtBCI, &st) - 1];
        if (c_x < 0.0) {
          b_st.site = &f_emlrtRSI;
          eml_error(&b_st);
        }

        emxInit_real_T(&st, &e_x, 2, &bb_emlrtRTEI, true);
        b_x = e_x->size[0] * e_x->size[1];
        e_x->size[0] = 1;
        e_x->size[1] = x->size[1];
        emxEnsureCapacity(sp, (emxArray__common *)e_x, b_x, (int32_T)sizeof
                          (real_T), &bb_emlrtRTEI);
        i = x->size[0] * x->size[1];
        for (b_x = 0; b_x < i; b_x++) {
          e_x->data[b_x] = x->data[b_x] - ksi;
        }

        emxInit_real_T(sp, &r9, 2, &bb_emlrtRTEI, true);
        b_abs(sp, e_x, r9);
        b_x = r8->size[0] * r8->size[1];
        r8->size[0] = 1;
        r8->size[1] = r9->size[1];
        emxEnsureCapacity(sp, (emxArray__common *)r8, b_x, (int32_T)sizeof
                          (real_T), &bb_emlrtRTEI);
        i = r9->size[0] * r9->size[1];
        emxFree_real_T(&e_x);
        for (b_x = 0; b_x < i; b_x++) {
          r8->data[b_x] = r9->data[b_x];
        }

        emxFree_real_T(&r9);
        rdivide(sp, r8, 2.0 * muDoubleScalarSqrt(c_x), z0);
        st.site = &re_emlrtRSI;
        mpower(&st, z0, d_x);
        b_x = d_x->size[0] * d_x->size[1];
        d_x->size[0] = 1;
        emxEnsureCapacity(sp, (emxArray__common *)d_x, b_x, (int32_T)sizeof
                          (real_T), &bb_emlrtRTEI);
        i = d_x->size[0];
        b_x = d_x->size[1];
        i *= b_x;
        for (b_x = 0; b_x < i; b_x++) {
          d_x->data[b_x] = -d_x->data[b_x];
        }

        b_x = b->size[0] * b->size[1];
        b->size[0] = 1;
        b->size[1] = d_x->size[1];
        emxEnsureCapacity(sp, (emxArray__common *)b, b_x, (int32_T)sizeof(real_T),
                          &bb_emlrtRTEI);
        i = d_x->size[0] * d_x->size[1];
        for (b_x = 0; b_x < i; b_x++) {
          b->data[b_x] = d_x->data[b_x];
        }

        for (i = 0; i < d_x->size[1]; i++) {
          b->data[i] = muDoubleScalarExp(b->data[i]);
        }

        st.site = &re_emlrtRSI;
        b_mrdivide(&st, b, z0);
        for (b_x = 0; b_x < 2; b_x++) {
          i = d_x->size[0] * d_x->size[1];
          d_x->size[b_x] = z0->size[b_x];
          emxEnsureCapacity(sp, (emxArray__common *)d_x, i, (int32_T)sizeof
                            (real_T), &ab_emlrtRTEI);
        }

        for (i = 0; i < z0->size[1]; i++) {
          d_x->data[i] = scalar_erf(z0->data[i]);
        }

        b_x = d_x->size[0] * d_x->size[1];
        d_x->size[0] = 1;
        emxEnsureCapacity(sp, (emxArray__common *)d_x, b_x, (int32_T)sizeof
                          (real_T), &bb_emlrtRTEI);
        i = d_x->size[0];
        b_x = d_x->size[1];
        i *= b_x;
        for (b_x = 0; b_x < i; b_x++) {
          d_x->data[b_x] *= 1.7724538509055159;
        }

        for (b_x = 0; b_x < 2; b_x++) {
          b_b[b_x] = b->size[b_x];
        }

        for (b_x = 0; b_x < 2; b_x++) {
          f_x[b_x] = d_x->size[b_x];
        }

        emxInit_real_T(sp, &g_x, 2, &bb_emlrtRTEI, true);
        emlrtSizeEqCheck2DFastR2012b(b_b, f_x, &o_emlrtECI, sp);
        b_x = g_x->size[0] * g_x->size[1];
        g_x->size[0] = 1;
        g_x->size[1] = x->size[1];
        emxEnsureCapacity(sp, (emxArray__common *)g_x, b_x, (int32_T)sizeof
                          (real_T), &bb_emlrtRTEI);
        i = x->size[0] * x->size[1];
        for (b_x = 0; b_x < i; b_x++) {
          g_x->data[b_x] = x->data[b_x] - ksi;
        }

        emxInit_real_T(sp, &r10, 2, &bb_emlrtRTEI, true);
        b_abs(sp, g_x, r10);
        b_x = r8->size[0] * r8->size[1];
        r8->size[0] = 1;
        r8->size[1] = r10->size[1];
        emxEnsureCapacity(sp, (emxArray__common *)r8, b_x, (int32_T)sizeof
                          (real_T), &bb_emlrtRTEI);
        i = r10->size[0] * r10->size[1];
        emxFree_real_T(&g_x);
        for (b_x = 0; b_x < i; b_x++) {
          r8->data[b_x] = r10->data[b_x];
        }

        emxFree_real_T(&r10);
        rdivide(sp, r8, 3.5449077018110318, vals);
        st.site = &re_emlrtRSI;
        b_x = b->size[0] * b->size[1];
        b->size[0] = 1;
        emxEnsureCapacity(&st, (emxArray__common *)b, b_x, (int32_T)sizeof
                          (real_T), &bb_emlrtRTEI);
        i = b->size[0];
        b_x = b->size[1];
        i *= b_x;
        for (b_x = 0; b_x < i; b_x++) {
          b->data[b_x] -= d_x->data[b_x];
        }

        b_st.site = &he_emlrtRSI;
        if (!(vals->size[1] == 1)) {
          if ((vals->size[1] == 1) || (b->size[1] == 1)) {
            y = NULL;
            m6 = emlrtCreateCharArray(2, iv16);
            for (i = 0; i < 45; i++) {
              cv18[i] = cv19[i];
            }

            emlrtInitCharArrayR2013a(&b_st, 45, m6, cv18);
            emlrtAssign(&y, m6);
            c_st.site = &fh_emlrtRSI;
            d_st.site = &vg_emlrtRSI;
            b_error(&c_st, message(&d_st, y, &j_emlrtMCI), &k_emlrtMCI);
          } else {
            b_y = NULL;
            m6 = emlrtCreateCharArray(2, iv17);
            for (i = 0; i < 21; i++) {
              cv20[i] = cv21[i];
            }

            emlrtInitCharArrayR2013a(&b_st, 21, m6, cv20);
            emlrtAssign(&b_y, m6);
            c_st.site = &gh_emlrtRSI;
            d_st.site = &wg_emlrtRSI;
            b_error(&c_st, message(&d_st, b_y, &l_emlrtMCI), &m_emlrtMCI);
          }
        }

        c_x = vals->data[0];
        b_x = vals->size[0] * vals->size[1];
        vals->size[0] = 1;
        vals->size[1] = b->size[1];
        emxEnsureCapacity(&st, (emxArray__common *)vals, b_x, (int32_T)sizeof
                          (real_T), &bb_emlrtRTEI);
        i = b->size[1];
        for (b_x = 0; b_x < i; b_x++) {
          vals->data[vals->size[0] * b_x] = c_x * b->data[b->size[0] * b_x];
        }
      } else {
        emxInit_boolean_T(sp, &d_t, 2, &bb_emlrtRTEI, true);
        b_x = d_t->size[0] * d_t->size[1];
        d_t->size[0] = 1;
        d_t->size[1] = 1 + x->size[1];
        emxEnsureCapacity(sp, (emxArray__common *)d_t, b_x, (int32_T)sizeof
                          (boolean_T), &bb_emlrtRTEI);
        b_x = gridT->size[1];
        i = (int32_T)((uint32_T)j + 1U);
        d_t->data[0] = (t > gridT->data[emlrtDynamicBoundsCheckFastR2012b(i, 1,
          b_x, &i_emlrtBCI, sp) - 1]);
        i = x->size[1];
        for (b_x = 0; b_x < i; b_x++) {
          d_t->data[d_t->size[0] * (b_x + 1)] = (x->data[x->size[0] * b_x] ==
            ksi);
        }

        st.site = &se_emlrtRSI;
        if (all(&st, d_t)) {
          b_x = gridT->size[1];
          i = (int32_T)j;
          emlrtDynamicBoundsCheckFastR2012b(i, 1, b_x, &b_emlrtBCI, sp);
          c_x = (t - gridT->data[(int32_T)j - 1]) / 3.1415926535897931;
          b_x = gridT->size[1];
          i = (int32_T)(j + 1.0);
          emlrtDynamicBoundsCheckFastR2012b(i, 1, b_x, &emlrtBCI, sp);
          h_x = (t - gridT->data[(int32_T)(j + 1.0) - 1]) / 3.1415926535897931;
          st.site = &c_emlrtRSI;
          if (c_x < 0.0) {
            b_st.site = &f_emlrtRSI;
            eml_error(&b_st);
          }

          st.site = &c_emlrtRSI;
          if (h_x < 0.0) {
            b_st.site = &f_emlrtRSI;
            eml_error(&b_st);
          }

          b_x = vals->size[0] * vals->size[1];
          vals->size[0] = 1;
          vals->size[1] = 1;
          emxEnsureCapacity(sp, (emxArray__common *)vals, b_x, (int32_T)sizeof
                            (real_T), &bb_emlrtRTEI);
          vals->data[0] = muDoubleScalarSqrt(c_x) - muDoubleScalarSqrt(h_x);
        } else {
          emxInit_boolean_T(sp, &e_t, 2, &bb_emlrtRTEI, true);
          b_x = e_t->size[0] * e_t->size[1];
          e_t->size[0] = 1;
          e_t->size[1] = 1 + x->size[1];
          emxEnsureCapacity(sp, (emxArray__common *)e_t, b_x, (int32_T)sizeof
                            (boolean_T), &bb_emlrtRTEI);
          b_x = gridT->size[1];
          i = (int32_T)((uint32_T)j + 1U);
          e_t->data[0] = (t > gridT->data[emlrtDynamicBoundsCheckFastR2012b(i, 1,
            b_x, &j_emlrtBCI, sp) - 1]);
          i = x->size[1];
          for (b_x = 0; b_x < i; b_x++) {
            e_t->data[e_t->size[0] * (b_x + 1)] = (x->data[x->size[0] * b_x] !=
              ksi);
          }

          st.site = &te_emlrtRSI;
          if (all(&st, e_t)) {
            st.site = &d_emlrtRSI;
            b_x = gridT->size[1];
            i = (int32_T)j;
            c_x = t - gridT->data[emlrtDynamicBoundsCheckFastR2012b(i, 1, b_x,
              &k_emlrtBCI, &st) - 1];
            if (c_x < 0.0) {
              b_st.site = &f_emlrtRSI;
              eml_error(&b_st);
            }

            emxInit_real_T(&st, &i_x, 2, &bb_emlrtRTEI, true);
            b_x = i_x->size[0] * i_x->size[1];
            i_x->size[0] = 1;
            i_x->size[1] = x->size[1];
            emxEnsureCapacity(sp, (emxArray__common *)i_x, b_x, (int32_T)sizeof
                              (real_T), &bb_emlrtRTEI);
            i = x->size[0] * x->size[1];
            for (b_x = 0; b_x < i; b_x++) {
              i_x->data[b_x] = x->data[b_x] - ksi;
            }

            emxInit_real_T(sp, &r11, 2, &bb_emlrtRTEI, true);
            b_abs(sp, i_x, r11);
            b_x = r8->size[0] * r8->size[1];
            r8->size[0] = 1;
            r8->size[1] = r11->size[1];
            emxEnsureCapacity(sp, (emxArray__common *)r8, b_x, (int32_T)sizeof
                              (real_T), &bb_emlrtRTEI);
            i = r11->size[0] * r11->size[1];
            emxFree_real_T(&i_x);
            for (b_x = 0; b_x < i; b_x++) {
              r8->data[b_x] = r11->data[b_x];
            }

            emxFree_real_T(&r11);
            rdivide(sp, r8, 2.0 * muDoubleScalarSqrt(c_x), z0);
            st.site = &e_emlrtRSI;
            b_x = gridT->size[1];
            i = (int32_T)((uint32_T)j + 1U);
            c_x = t - gridT->data[emlrtDynamicBoundsCheckFastR2012b(i, 1, b_x,
              &l_emlrtBCI, &st) - 1];
            if (c_x < 0.0) {
              b_st.site = &f_emlrtRSI;
              eml_error(&b_st);
            }

            emxInit_real_T(&st, &j_x, 2, &bb_emlrtRTEI, true);
            b_x = j_x->size[0] * j_x->size[1];
            j_x->size[0] = 1;
            j_x->size[1] = x->size[1];
            emxEnsureCapacity(sp, (emxArray__common *)j_x, b_x, (int32_T)sizeof
                              (real_T), &bb_emlrtRTEI);
            i = x->size[0] * x->size[1];
            for (b_x = 0; b_x < i; b_x++) {
              j_x->data[b_x] = x->data[b_x] - ksi;
            }

            emxInit_real_T(sp, &r12, 2, &bb_emlrtRTEI, true);
            b_abs(sp, j_x, r12);
            b_x = r8->size[0] * r8->size[1];
            r8->size[0] = 1;
            r8->size[1] = r12->size[1];
            emxEnsureCapacity(sp, (emxArray__common *)r8, b_x, (int32_T)sizeof
                              (real_T), &bb_emlrtRTEI);
            i = r12->size[0] * r12->size[1];
            emxFree_real_T(&j_x);
            for (b_x = 0; b_x < i; b_x++) {
              r8->data[b_x] = r12->data[b_x];
            }

            emxFree_real_T(&r12);
            emxInit_real_T(sp, &z1, 2, &db_emlrtRTEI, true);
            rdivide(sp, r8, 2.0 * muDoubleScalarSqrt(c_x), z1);
            st.site = &ue_emlrtRSI;
            mpower(&st, z0, d_x);
            b_x = d_x->size[0] * d_x->size[1];
            d_x->size[0] = 1;
            emxEnsureCapacity(sp, (emxArray__common *)d_x, b_x, (int32_T)sizeof
                              (real_T), &bb_emlrtRTEI);
            i = d_x->size[0];
            b_x = d_x->size[1];
            i *= b_x;
            for (b_x = 0; b_x < i; b_x++) {
              d_x->data[b_x] = -d_x->data[b_x];
            }

            b_x = b->size[0] * b->size[1];
            b->size[0] = 1;
            b->size[1] = d_x->size[1];
            emxEnsureCapacity(sp, (emxArray__common *)b, b_x, (int32_T)sizeof
                              (real_T), &bb_emlrtRTEI);
            i = d_x->size[0] * d_x->size[1];
            for (b_x = 0; b_x < i; b_x++) {
              b->data[b_x] = d_x->data[b_x];
            }

            for (i = 0; i < d_x->size[1]; i++) {
              b->data[i] = muDoubleScalarExp(b->data[i]);
            }

            st.site = &ue_emlrtRSI;
            b_mrdivide(&st, b, z0);
            st.site = &ue_emlrtRSI;
            mpower(&st, z1, d_x);
            b_x = d_x->size[0] * d_x->size[1];
            d_x->size[0] = 1;
            emxEnsureCapacity(sp, (emxArray__common *)d_x, b_x, (int32_T)sizeof
                              (real_T), &bb_emlrtRTEI);
            i = d_x->size[0];
            b_x = d_x->size[1];
            i *= b_x;
            for (b_x = 0; b_x < i; b_x++) {
              d_x->data[b_x] = -d_x->data[b_x];
            }

            b_x = r8->size[0] * r8->size[1];
            r8->size[0] = 1;
            r8->size[1] = d_x->size[1];
            emxEnsureCapacity(sp, (emxArray__common *)r8, b_x, (int32_T)sizeof
                              (real_T), &bb_emlrtRTEI);
            i = d_x->size[0] * d_x->size[1];
            for (b_x = 0; b_x < i; b_x++) {
              r8->data[b_x] = d_x->data[b_x];
            }

            for (i = 0; i < d_x->size[1]; i++) {
              r8->data[i] = muDoubleScalarExp(r8->data[i]);
            }

            st.site = &ue_emlrtRSI;
            b_mrdivide(&st, r8, z1);
            for (b_x = 0; b_x < 2; b_x++) {
              b_b[b_x] = b->size[b_x];
            }

            for (b_x = 0; b_x < 2; b_x++) {
              b_z0[b_x] = r8->size[b_x];
            }

            emxInit_real_T(sp, &c_z0, 2, &bb_emlrtRTEI, true);
            emlrtSizeEqCheck2DFastR2012b(b_b, b_z0, &m_emlrtECI, sp);
            b_x = c_z0->size[0] * c_z0->size[1];
            c_z0->size[0] = 1;
            c_z0->size[1] = z0->size[1];
            emxEnsureCapacity(sp, (emxArray__common *)c_z0, b_x, (int32_T)sizeof
                              (real_T), &bb_emlrtRTEI);
            i = z0->size[0] * z0->size[1];
            for (b_x = 0; b_x < i; b_x++) {
              c_z0->data[b_x] = z0->data[b_x];
            }

            b_erf(sp, c_z0, z0);
            b_erf(sp, z1, d_x);
            emxFree_real_T(&c_z0);
            emxFree_real_T(&z1);
            for (b_x = 0; b_x < 2; b_x++) {
              b_z0[b_x] = z0->size[b_x];
            }

            for (b_x = 0; b_x < 2; b_x++) {
              f_x[b_x] = d_x->size[b_x];
            }

            emlrtSizeEqCheck2DFastR2012b(b_z0, f_x, &n_emlrtECI, sp);
            b_x = z0->size[0] * z0->size[1];
            z0->size[0] = 1;
            emxEnsureCapacity(sp, (emxArray__common *)z0, b_x, (int32_T)sizeof
                              (real_T), &bb_emlrtRTEI);
            i = z0->size[0];
            b_x = z0->size[1];
            i *= b_x;
            for (b_x = 0; b_x < i; b_x++) {
              z0->data[b_x] = 1.7724538509055159 * (z0->data[b_x] - d_x->
                data[b_x]);
            }

            for (b_x = 0; b_x < 2; b_x++) {
              b_b[b_x] = b->size[b_x];
            }

            for (b_x = 0; b_x < 2; b_x++) {
              b_z0[b_x] = z0->size[b_x];
            }

            emxInit_real_T(sp, &k_x, 2, &bb_emlrtRTEI, true);
            emlrtSizeEqCheck2DFastR2012b(b_b, b_z0, &m_emlrtECI, sp);
            b_x = k_x->size[0] * k_x->size[1];
            k_x->size[0] = 1;
            k_x->size[1] = x->size[1];
            emxEnsureCapacity(sp, (emxArray__common *)k_x, b_x, (int32_T)sizeof
                              (real_T), &bb_emlrtRTEI);
            i = x->size[0] * x->size[1];
            for (b_x = 0; b_x < i; b_x++) {
              k_x->data[b_x] = x->data[b_x] - ksi;
            }

            b_abs(sp, k_x, d_x);
            rdivide(sp, d_x, 3.5449077018110318, vals);
            st.site = &ue_emlrtRSI;
            b_x = b->size[0] * b->size[1];
            b->size[0] = 1;
            emxEnsureCapacity(&st, (emxArray__common *)b, b_x, (int32_T)sizeof
                              (real_T), &bb_emlrtRTEI);
            i = b->size[0];
            b_x = b->size[1];
            i *= b_x;
            emxFree_real_T(&k_x);
            for (b_x = 0; b_x < i; b_x++) {
              b->data[b_x] = (b->data[b_x] - r8->data[b_x]) + z0->data[b_x];
            }

            b_st.site = &he_emlrtRSI;
            if (!(vals->size[1] == 1)) {
              if ((vals->size[1] == 1) || (b->size[1] == 1)) {
                c_y = NULL;
                m6 = emlrtCreateCharArray(2, iv18);
                for (i = 0; i < 45; i++) {
                  cv18[i] = cv19[i];
                }

                emlrtInitCharArrayR2013a(&b_st, 45, m6, cv18);
                emlrtAssign(&c_y, m6);
                c_st.site = &fh_emlrtRSI;
                d_st.site = &vg_emlrtRSI;
                b_error(&c_st, message(&d_st, c_y, &j_emlrtMCI), &k_emlrtMCI);
              } else {
                d_y = NULL;
                m6 = emlrtCreateCharArray(2, iv19);
                for (i = 0; i < 21; i++) {
                  cv20[i] = cv21[i];
                }

                emlrtInitCharArrayR2013a(&b_st, 21, m6, cv20);
                emlrtAssign(&d_y, m6);
                c_st.site = &gh_emlrtRSI;
                d_st.site = &wg_emlrtRSI;
                b_error(&c_st, message(&d_st, d_y, &l_emlrtMCI), &m_emlrtMCI);
              }
            }

            c_x = vals->data[0];
            b_x = vals->size[0] * vals->size[1];
            vals->size[0] = 1;
            vals->size[1] = b->size[1];
            emxEnsureCapacity(&st, (emxArray__common *)vals, b_x, (int32_T)
                              sizeof(real_T), &bb_emlrtRTEI);
            i = b->size[1];
            for (b_x = 0; b_x < i; b_x++) {
              vals->data[vals->size[0] * b_x] = c_x * b->data[b->size[0] * b_x];
            }
          } else {
            b_x = vals->size[0] * vals->size[1];
            vals->size[0] = 1;
            vals->size[1] = 1;
            emxEnsureCapacity(sp, (emxArray__common *)vals, b_x, (int32_T)sizeof
                              (real_T), &bb_emlrtRTEI);
            vals->data[0] = 0.0;
          }

          emxFree_boolean_T(&e_t);
        }

        emxFree_boolean_T(&d_t);
      }

      emxFree_boolean_T(&c_t);
      emxFree_real_T(&d_x);
      emxFree_real_T(&z0);
    }

    emxFree_boolean_T(&b_t);
  }

  emxFree_real_T(&r8);
  emxFree_real_T(&b);
  emlrtHeapReferenceStackLeaveFcnR2012b(sp);
}
示例#2
0
// check that update preserves all(d_ > 1/n)
int el_sem_naive::backtracking(vec update)
{
    vec d = (constraints_.t() * (dual_ - update)) + 1.0;
    return all( d > (1.0 / n_));
}
示例#3
0
文件: main.cpp 项目: CCJY/coliru
int main() {
    std::cout << all(std::string("i3aa34"));
}
示例#4
0
/*
 * Converts a matrix to a boolean: true if all elements are nonzero, false
 * otherwise.
 */
bool MATLAB_NAMESPACE::to_bool(const MATRIX_T* m) {
	VECTOR_T* all_v = all(m);
	bool ret = all(all_v);
	VECTOR_ID(free)(all_v);
	return ret;
}
示例#5
0
void game (gamedata &g){

  SDL_Event event;
  quit = false;

  // Set first tick interval
  Uint32 next_time = SDL_GetTicks() + TICK_INTERVAL;

  while (!quit){
	  if(g.winner){
		finish_game(g);
		setup_game(g);
		GameState = STATE_INTRO;
		CurrentMenu = MenuMainIntro;
		SelectedItem = menuSwitchItem(CurrentMenu, 0);
		demo = true;
	  }
	 else if (g.winner == 0){

	    Uint8 *keys = SDL_GetKeyState(NULL);

	    if (SDL_PollEvent(&event) == 1){
	      switch (event.type){

	      case SDL_QUIT: {
		printf("Quit requested, quitting.\n");
		quit = true;
	      }
	      break;
	      }
	    }

	    if(GameState == STATE_INTRO || GameState == STATE_MENU)
	    {
		    menuInput(g);
	    }
	    else if(GameState == STATE_MENU_PLANE_SELECT)
	    {
		    menuPlanes(g);
	    }
	    else if(GameState == STATE_MENU_PLAYER_CONTROL_SELECT)
	    {
		    menuSelectPlayer(g);
	    }
	    else if(GameState == STATE_GAME)
	    {
		    if ((keys[SDLK_ESCAPE] == SDL_PRESSED) || (keys[51] == SDL_PRESSED)){
			keys[SDLK_ESCAPE] = SDL_RELEASED;
			GameState = STATE_MENU;
			CurrentMenu = MenuMain;
			SelectedItem = menuSwitchItem(CurrentMenu, 0);
		      //quit = true;
		    }
	    }

	    // Go through each plane individually
	    g.p.reset();
	    while (g.p.next()){

	      // Setup virtual joystick
	      int jx = 0;

	      int jy = 0;
	      bool jb = false;

	      if (g.p().state < 2){
		control(g, keys, jx, jy, jb);
		controlJoy(g, jx, jy, jb);
	      }
	      // Then move the plane
	      act(g, jx, jy, jb);
	      // Remove expunged planes
	      if (g.p().state == 4){
		g.drakms.fighter[g.p().id-7] = false;
		g.drakms.fightersout--;
		g.dp.reset();
		while(g.dp.next()){
		  if (g.dp().id == g.p().id) g.dp.kill();
		}
		g.p.kill();
	      }

	    }

	    // Then do everything else
	    all(g);
	    drawall(g);

	    // Delay for time remaining in TICK_INTERVAL
	    SDL_Delay(time_left(next_time));
	    next_time = SDL_GetTicks() + TICK_INTERVAL;

	  }
  }
}
    void BVH8Intersector16Chunk<PrimitiveIntersector16>::occluded(bool16* valid_i, BVH8* bvh, Ray16& ray)
    {
#if defined(__AVX512__)
      
      /* load ray */
      const bool16 valid = *valid_i;
      bool16 terminated = !valid;
      const Vec3f16 rdir = rcp_safe(ray.dir);
      const Vec3f16 org_rdir = ray.org * rdir;
      float16 ray_tnear = select(valid,ray.tnear,pos_inf);
      float16 ray_tfar  = select(valid,ray.tfar ,neg_inf);
      const float16 inf = float16(pos_inf);
      Precalculations pre(valid,ray);

      /* allocate stack and push root node */
      float16    stack_near[3*BVH8::maxDepth+1];
      NodeRef stack_node[3*BVH8::maxDepth+1];
      stack_node[0] = BVH8::invalidNode;
      stack_near[0] = inf;
      stack_node[1] = bvh->root;
      stack_near[1] = ray_tnear; 
      NodeRef* __restrict__ sptr_node = stack_node + 2;
      float16*    __restrict__ sptr_near = stack_near + 2;
      
      while (1)
      {
        /* pop next node from stack */
        sptr_node--;
        sptr_near--;
        NodeRef cur = *sptr_node;
        if (unlikely(cur == BVH8::invalidNode)) 
          break;
        
        /* cull node if behind closest hit point */
        float16 curDist = *sptr_near;
        if (unlikely(none(ray_tfar > curDist))) 
          continue;
        
        while (1)
        {
          /* test if this is a leaf node */
          if (unlikely(cur.isLeaf()))
            break;
          
          const bool16 valid_node = ray_tfar > curDist;
          STAT3(shadow.trav_nodes,1,popcnt(valid_node),8);
          const Node* __restrict__ const node = (Node*)cur.node();
          
          /* pop of next node */
          sptr_node--;
          sptr_near--;
          cur = *sptr_node; // FIXME: this trick creates issues with stack depth
          curDist = *sptr_near;
          
          for (unsigned i=0; i<BVH8::N; i++)
          {
            const NodeRef child = node->children[i];
            if (unlikely(child == BVH8::emptyNode)) break;
            
            const float16 lclipMinX = msub(node->lower_x[i],rdir.x,org_rdir.x);
            const float16 lclipMinY = msub(node->lower_y[i],rdir.y,org_rdir.y);
            const float16 lclipMinZ = msub(node->lower_z[i],rdir.z,org_rdir.z);
            const float16 lclipMaxX = msub(node->upper_x[i],rdir.x,org_rdir.x);
            const float16 lclipMaxY = msub(node->upper_y[i],rdir.y,org_rdir.y);
            const float16 lclipMaxZ = msub(node->upper_z[i],rdir.z,org_rdir.z);
            const float16 lnearP = max(max(min(lclipMinX, lclipMaxX), min(lclipMinY, lclipMaxY)), min(lclipMinZ, lclipMaxZ));
            const float16 lfarP  = min(min(max(lclipMinX, lclipMaxX), max(lclipMinY, lclipMaxY)), max(lclipMinZ, lclipMaxZ));
            const bool16 lhit   = max(lnearP,ray_tnear) <= min(lfarP,ray_tfar);      
            
            /* if we hit the child we choose to continue with that child if it 
               is closer than the current next child, or we push it onto the stack */
            if (likely(any(lhit)))
            {
              const float16 childDist = select(lhit,lnearP,inf);
              sptr_node++;
              sptr_near++;
              
              /* push cur node onto stack and continue with hit child */
              if (any(childDist < curDist))
              {
                *(sptr_node-1) = cur;
                *(sptr_near-1) = curDist; 
                curDist = childDist;
                cur = child;
              }
              
              /* push hit child onto stack*/
              else {
                *(sptr_node-1) = child;
                *(sptr_near-1) = childDist; 
              }
              assert(sptr_node - stack_node < BVH8::maxDepth);
            }	      
          }
        }
        
        /* return if stack is empty */
        if (unlikely(cur == BVH8::invalidNode)) 
          break;
        
        /* intersect leaf */
	assert(cur != BVH8::emptyNode);
        const bool16 valid_leaf = ray_tfar > curDist;
        STAT3(shadow.trav_leaves,1,popcnt(valid_leaf),8);
        size_t items; const Triangle* tri  = (Triangle*) cur.leaf(items);
        terminated |= PrimitiveIntersector16::occluded(!terminated,pre,ray,tri,items,bvh->scene);
        if (all(terminated)) break;
        ray_tfar = select(terminated,neg_inf,ray_tfar);
      }
      store16i(valid & terminated,&ray.geomID,0);
      AVX_ZERO_UPPER();
#endif      
    }
示例#7
0
//[[Rcpp::export]]
bool all_naC (Rcpp::NumericVector x) {
    return is_true(all(is_na(x)));
}
void
GcWindow::paintEvent(QPaintEvent * /*event*/)
{
    static QPixmap closeImage = QPixmap(":images/toolbar/popbutton.png");
    static QPixmap aluBar = QPixmap(":images/aluBar.png");
    static QPixmap aluBarDark = QPixmap(":images/aluBarDark.png");
    static QPixmap aluLight = QPixmap(":images/aluLight.jpg");
    static QPixmap carbon = QPixmap(":images/carbon.jpg");
    static QPalette defaultPalette;


    // setup a painter and the area to paint
    QPainter painter(this);
    // background light gray for now?
    QRect all(0,0,width(),height());
    painter.fillRect(all, property("color").value<QColor>());

    if (contentsMargins().top() > 0) {

        // fill in the title bar
        QRect bar(0,0,width(),contentsMargins().top());
        if (contentsMargins().top() < 25) {
        QColor bg;
        if (property("active").toBool() == true) {
            bg = GColor(CTILEBARSELECT);
            painter.drawPixmap(bar, aluBar);
        } else {
            bg = GColor(CTILEBAR);
            painter.drawPixmap(bar, aluBarDark);
        }
        } else {
            painter.setPen(Qt::darkGray);
            painter.drawRect(QRect(0,0,width()-1,height()-1));
        }

        // heading
        QFont font;
        font.setPointSize((contentsMargins().top()/2)+2);
        font.setWeight(QFont::Bold);
        painter.setFont(font);
        QString subtitle = property("subtitle").toString();
        QString title = property("title").toString();
        QString heading = subtitle != "" ? subtitle : title;

        // embossed...
        QRect shad = bar;
        shad.setY(bar.y()+2);
        //shad.setX(bar.x()+2);
        painter.setPen(QColor(255,255,255,180));
        painter.drawText(shad, heading, Qt::AlignVCenter | Qt::AlignCenter);

        painter.setPen(QColor(0,0,0,200));
        painter.drawText(bar, heading, Qt::AlignVCenter | Qt::AlignCenter);

        // border
        painter.setBrush(Qt::NoBrush);
        if (underMouse()) {

            QPixmap sized = closeImage.scaled(QSize(contentsMargins().top()-6,
                                                    contentsMargins().top()-6));
            //painter.drawPixmap(width()-3-sized.width(), 3, sized.width(), sized.height(), sized);

        } else {
            painter.setPen(Qt::darkGray);
            //painter.drawRect(QRect(0,0,width()-1,height()-1)); //XXX pointless
        }
    } else {
        // is this a layout manager?
        // background light gray for now?
        QRect all(0,0,width(),height());
        if (property("isManager").toBool() == true) {
            //painter.drawTiledPixmap(all, carbon);
            painter.fillRect(all, QColor("#B3B4BA"));
        } else {
            //painter.drawTiledPixmap(all, aluLight);
        }
    }
}
  __m128 BVH4Intersector4Hybrid<TriangleIntersector4>::occluded(const BVH4Intersector4Hybrid* This, Ray4& ray, const __m128 valid_i) 
  {
    sseb valid = valid_i;
    NodeRef invalid = (NodeRef)1;
    sseb terminated = !valid;
    const BVH4* bvh = This->bvh;
    
    /* load ray into registers */
    ssef ray_near = select(valid,ray.tnear,pos_inf);
    ssef ray_far  = select(valid,ray.tfar ,neg_inf);
    sse3f rdir = rcp_safe(ray.dir);

    /* allocate stack and push root node */
    NodeRef stack_node[3*BVH4::maxDepth+1];
    ssef  stack_near[3*BVH4::maxDepth+1];
    stack_node[0] = invalid;
    stack_near[0] = ssef(inf);
    stack_node[1] = bvh->root;
    stack_near[1] = ray_near;
    NodeRef* sptr_node = stack_node+2;
    ssef * sptr_near = stack_near+2;
 
    while (1)
    {
      /* pop next node from stack */
      sptr_node--;
      sptr_near--;
      ssef  curDist = *sptr_near;
      NodeRef curNode = *sptr_node;
      if (unlikely(curNode == invalid))
        break;

      /* cull node if behind closest hit point */
      const sseb active = curDist < ray_far;
      if (unlikely(none(active))) 
        continue;

      /* switch to single ray traversal */
      size_t bits = movemask(active);
      if (unlikely(__popcnt(bits) <= SWITCH_THRESHOLD)) {
        for (size_t i=__bsf(bits); bits!=0; bits=__btc(bits,i), i=__bsf(bits)) {
          if (BVH4Intersector1<TriangleIntersector1>::occluded1(bvh,curNode,i,ray,rdir))
            terminated[i] = -1;
        }
        if (all(terminated)) return terminated;

        /* let terminated rays miss all boxes */
        ray_far = select(terminated,neg_inf,ray_far);
        continue;
      }

      while (1)
      {
        /* test if this is a leaf node */
        if (unlikely(curNode.isLeaf())) 
          break;
        
        const Node* const node = curNode.node(bvh->nodePtr()); //NodeRef(curNode).node(nodes);
        //prefetch<PFHINT_L1>((ssef*)node + 1); // depth first order prefetch	
        
        /* pop of next node */
        sptr_node--;
        sptr_near--;
        curNode = *sptr_node;
        curDist = *sptr_near;
                
        for (unsigned i=0;i<4;i++)
	{
          const ssef dminx = (ssef(node->lower_x[i]) - ray.org.x) * rdir.x;
          const ssef dmaxx = (ssef(node->upper_x[i]) - ray.org.x) * rdir.x;
          const ssef dminy = (ssef(node->lower_y[i]) - ray.org.y) * rdir.y;
          const ssef dmaxy = (ssef(node->upper_y[i]) - ray.org.y) * rdir.y;
          const ssef dminz = (ssef(node->lower_z[i]) - ray.org.z) * rdir.z;
          const ssef dmaxz = (ssef(node->upper_z[i]) - ray.org.z) * rdir.z;
          
          const ssef dlowerx = min(dminx,dmaxx);
          const ssef dupperx = max(dminx,dmaxx);
          const ssef dlowery = min(dminy,dmaxy);
          const ssef duppery = max(dminy,dmaxy);
          const ssef dlowerz = min(dminz,dmaxz);
          const ssef dupperz = max(dminz,dmaxz);
          
          const ssef near = max(dlowerx,dlowery,dlowerz,ray_near);
          const ssef far  = min(dupperx,duppery,dupperz,ray_far );
          const sseb mhit = near <= far;
          
          const ssef childDist = select(mhit,near,inf);
          const sseb closer = childDist < curDist;

          /* if we hit the child we choose to continue with that child if it 
             is closer than the current next child, or we push it onto the stack */
          if (likely(any(mhit)))
          {
            const NodeRef child = node->child(i);
            //if (child != invalid)
            {
              sptr_node++;
              sptr_near++;
            
              /* push cur node onto stack and continue with hit child */
              if (any(closer)) {
                *(sptr_node-1) = curNode;
                *(sptr_near-1) = curDist; 
                curDist = childDist;
                curNode = child;
              } 
              
              /* push hit child onto stack*/
              else {
                *(sptr_node-1) = child;
                *(sptr_near-1) = childDist; 
              }          
            }	      
          }
        }
      }
      
      /* return if stack is empty */
      if (unlikely(curNode == invalid)) 
        break;
      
      /* decode leaf node */
      size_t num;
      Triangle* tri = (Triangle*) curNode.leaf(bvh->triPtr(),num);
      
      /* intersect triangles */
      for (size_t i=0; i<num; i++) {
        terminated |= TriangleIntersector4::occluded(valid,ray,tri[i],bvh->vertices);
        if (all(terminated)) return terminated;
      }
      ray_far = select(terminated,neg_inf,ray_far);
    }
    return valid & terminated;
  }
示例#10
0
 typename std::enable_if<types::has_shape<U>::value and types::has_shape<V>::value,bool>::type array_equal(U const& u, V const&v) {
     if(u.shape == v.shape) {
         return all(u == v);
     }
     return false;
 }
示例#11
0
static void CreatePiles(const HitData *Hits, int HitCount,
  PILE_INDEX_TYPE *PileIndexes)
	{
	Piles = all(PileData, PileCount);
	zero(Piles, PileData, PileCount);
	for (int i = 0; i < PileCount; ++i)
		{
		Piles[i].FamIndex = -1;
		Piles[i].SuperFamIndex = -1;
		Piles[i].Rev = -1;
		}

// Count images in stack
	ProgressStart("Create stacks: count images");
	for (int HitIndex = 0; HitIndex < HitCount; ++HitIndex)
		{
		const HitData &Hit = Hits[HitIndex];

		int Pos = Hit.QueryFrom/CHUNK_LENGTH;
		PILE_INDEX_TYPE PileIndex = PileIndexes[Pos];
		assert(PileIndex == PileIndexes[Hit.QueryTo/CHUNK_LENGTH]);
		assert(PileIndex >= 0 && PileIndex < PileCount);
		++(Piles[PileIndex].ImageCount);

		Pos = Hit.TargetFrom/CHUNK_LENGTH;
		PileIndex = PileIndexes[Pos];
		assert(PileIndex >= 0 && PileIndex < PileCount);
		assert(PileIndex == PileIndexes[Hit.TargetTo/CHUNK_LENGTH]);
		++(Piles[PileIndex].ImageCount);
		}
	ProgressDone();

// Allocate memory for image list
	int TotalImageCount = 0;
	ProgressStart("Create stacks: allocate image memory");
	for (int PileIndex = 0; PileIndex < PileCount; ++PileIndex)
		{
		PileData &Pile = Piles[PileIndex];
		const int ImageCount = Pile.ImageCount;
		TotalImageCount += ImageCount;
		assert(ImageCount > 0);
		Pile.Images = all(PileImageData, ImageCount);
		}
	ProgressDone();

// Build image list
	ProgressStart("Create stacks: build image list");
	for (int PileIndex = 0; PileIndex < PileCount; ++PileIndex)
		{
		PileData &Pile = Piles[PileIndex];
		Pile.ImageCount = 0;
		Pile.From = -1;
		Pile.To = -1;
		}

	for (int HitIndex = 0; HitIndex < HitCount; ++HitIndex)
		{
		const HitData &Hit = Hits[HitIndex];

		const bool Rev = Hit.Rev;

		const int Length1 = Hit.QueryTo - Hit.QueryFrom;
		const int Length2 = Hit.TargetTo - Hit.TargetFrom;

		const int From1 = Hit.QueryFrom;
		const int From2 = Hit.TargetFrom;

		const int To1 = Hit.QueryTo;
		const int To2 = Hit.TargetTo;

		const int Pos1 = From1/CHUNK_LENGTH;
		const int Pos2 = From2/CHUNK_LENGTH;

		PILE_INDEX_TYPE PileIndex1 = PileIndexes[Pos1];
		PILE_INDEX_TYPE PileIndex2 = PileIndexes[Pos2];

		assert(PileIndex1 == PileIndexes[(From1 + Length1 - 1)/CHUNK_LENGTH]);
		assert(PileIndex1 >= 0 && PileIndex1 < PileCount);

		assert(PileIndex2 == PileIndexes[(From2 + Length2 - 1)/CHUNK_LENGTH]);
		assert(PileIndex2 >= 0 && PileIndex2 < PileCount);

		PileData &Pile1 = Piles[PileIndex1];
		PileImageData &Image1 = Pile1.Images[Pile1.ImageCount++];
		Image1.SILength = Length2;
		Image1.SIPile = PileIndex2;
		Image1.SIRev = Rev;

		PileData &Pile2 = Piles[PileIndex2];
		PileImageData &Image2 = Pile2.Images[Pile2.ImageCount++];
		Image2.SILength = Length1;
		Image2.SIPile = PileIndex1;
		Image2.SIRev = Rev;

		if (Pile1.From == -1 || From1 < Pile1.From)
			Pile1.From = From1;
		if (Pile1.To == -1 || To1 > Pile1.To)
			Pile1.To = To1;

		if (Pile2.From == -1 || From2 < Pile2.From)
			Pile2.From = From2;
		if (Pile2.To == -1 || To2 > Pile2.To)
			Pile2.To = To2;

		if (Pile1.ImageCount > MaxImageCount)
			MaxImageCount = Pile1.ImageCount;
		if (Pile2.ImageCount > MaxImageCount)
			MaxImageCount = Pile2.ImageCount;
		}
	ProgressDone();
	}
  __m256 BVH4Intersector8Chunk<TriangleIntersector8>::occluded(const BVH4Intersector8Chunk* This, Ray8& ray, const __m256 valid_i)
  {
    avxb valid = valid_i;
    NodeRef invalid = (NodeRef)1;
    avxb terminated = !valid;
    const BVH4* bvh = This->bvh;
    
    /* load ray into registers */
    avxf ray_near = select(valid,ray.tnear,pos_inf);
    avxf ray_far  = select(valid,ray.tfar ,neg_inf);
    avx3f rdir = rcp_safe(ray.dir);

    /* allocate stack and push root node */
    NodeRef stack_node[3*BVH4::maxDepth+1];
    avxf  stack_near[3*BVH4::maxDepth+1];
    stack_node[0] = invalid;
    stack_near[0] = inf;
    stack_node[1] = bvh->root;
    stack_near[1] = ray_near;
    NodeRef* sptr_node = stack_node+2;
    avxf * sptr_near = stack_near+2;
 
    while (1)
    {
      /* pop next node from stack */
      sptr_node--;
      sptr_near--;
      avxf  curDist = *sptr_near;
      NodeRef curNode = *sptr_node;
      if (unlikely(curNode == invalid))
        break;

      /* cull node if behind closest hit point */
      const avxb m_dist = curDist < ray_far;
      if (unlikely(none(m_dist))) 
        continue;

      while (1)
      {
        /* test if this is a leaf node */
        if (unlikely(curNode.isLeaf())) 
          break;
        
        const Node* const node = curNode.node(bvh->nodePtr()); //NodeRef(curNode).node(nodes);
        //prefetch<PFHINT_L1>((avxf*)node + 1); // depth first order prefetch	
        
        /* pop of next node */
        sptr_node--;
        sptr_near--;
        curNode = *sptr_node;
        curDist = *sptr_near;
                
        for (unsigned i=0;i<4;i++)
	{
          const avxf dminx = (avxf(node->lower_x[i]) - ray.org.x) * rdir.x;
          const avxf dmaxx = (avxf(node->upper_x[i]) - ray.org.x) * rdir.x;
          const avxf dminy = (avxf(node->lower_y[i]) - ray.org.y) * rdir.y;
          const avxf dmaxy = (avxf(node->upper_y[i]) - ray.org.y) * rdir.y;
          const avxf dminz = (avxf(node->lower_z[i]) - ray.org.z) * rdir.z;
          const avxf dmaxz = (avxf(node->upper_z[i]) - ray.org.z) * rdir.z;
          
          const avxf dlowerx = min(dminx,dmaxx);
          const avxf dupperx = max(dminx,dmaxx);
          const avxf dlowery = min(dminy,dmaxy);
          const avxf duppery = max(dminy,dmaxy);
          const avxf dlowerz = min(dminz,dmaxz);
          const avxf dupperz = max(dminz,dmaxz);
          
          const avxf near = max(dlowerx,dlowery,dlowerz,ray_near);
          const avxf far  = min(dupperx,duppery,dupperz,ray_far );
          const avxb mhit = near <= far;
          
          const avxf childDist = select(mhit,near,inf);
          const avxb closer = childDist < curDist;

          /* if we hit the child we choose to continue with that child if it 
             is closer than the current next child, or we push it onto the stack */
          if (likely(any(mhit)))
          {
            const NodeRef child = node->child(i);
            //if (child != invalid)
            {
              sptr_node++;
              sptr_near++;
            
              /* push cur node onto stack and continue with hit child */
              if (any(closer)) {
                *(sptr_node-1) = curNode;
                *(sptr_near-1) = curDist; 
                curDist = childDist;
                curNode = child;
              } 
              
              /* push hit child onto stack*/
              else {
                *(sptr_node-1) = child;
                *(sptr_near-1) = childDist; 
              }          
            }	      
          }
        }
      }
      
      /* return if stack is empty */
      if (unlikely(curNode == invalid)) 
        break;
      
      /* decode leaf node */
      size_t num;
      Triangle* tri = (Triangle*) curNode.leaf(bvh->triPtr(),num);
      
      /* intersect triangles */
      for (size_t i=0; i<num; i++) {
        terminated |= TriangleIntersector8::occluded(valid,ray,tri[i],bvh->vertices);
        if (all(terminated)) return terminated;
      }
      ray_far = select(terminated,neg_inf,ray_far);
    }
    return valid & terminated;
  }
示例#13
0
 adjacent_remove_if_view<all_t<Rng>, Pred> operator()(Rng && rng, Pred pred) const
 {
     return {all(std::forward<Rng>(rng)), std::move(pred)};
 }
示例#14
0
void Font::drawText(vec2 pen, vec4 color, const char* text)
{
  uint vertexCount = 0;

  // Realize vertices for glyphs
  {
    const size_t length = std::strlen(text);
    m_vertices.resize(length * 6);

    for (const char* c = text;  *c != '\0'; )
    {
      const uint32 codepoint = utf8::next<const char*>(c, text + length);
      const Glyph* glyph = findGlyph(codepoint);
      if (!glyph)
      {
        glyph = findGlyph(0xfffd);
        if (!glyph)
          continue;
      }

      pen = round(pen);

      if (all(greaterThan(glyph->size, vec2(0.f))))
      {
        const Rect pa(pen + glyph->bearing - vec2(0.5f), glyph->size);
        const Rect ta(glyph->offset + vec2(0.5f), glyph->size);

        m_vertices[vertexCount + 0].texcoord = ta.position;
        m_vertices[vertexCount + 0].position = pa.position;
        m_vertices[vertexCount + 1].texcoord = ta.position + vec2(ta.size.x, 0.f);
        m_vertices[vertexCount + 1].position = pa.position + vec2(pa.size.x, 0.f);
        m_vertices[vertexCount + 2].texcoord = ta.position + ta.size;
        m_vertices[vertexCount + 2].position = pa.position + pa.size;

        m_vertices[vertexCount + 3] = m_vertices[vertexCount + 2];
        m_vertices[vertexCount + 4].texcoord = ta.position + vec2(0.f, ta.size.y);
        m_vertices[vertexCount + 4].position = pa.position + vec2(0.f, pa.size.y);
        m_vertices[vertexCount + 5] = m_vertices[vertexCount + 0];

        vertexCount += 6;
      }

      pen += vec2(glyph->advance, 0.f);
    }
  }

  if (!vertexCount)
    return;

  GL::VertexRange range = m_pool->allocate(vertexCount, Vertex2ft2fv::format);
  if (range.isEmpty())
  {
    logError("Failed to allocate vertices for text drawing");
    return;
  }

  range.copyFrom(&m_vertices[0]);

  m_pass.setUniformState(m_colorIndex, color);
  m_pass.apply();

  m_pool->context().render(GL::PrimitiveRange(GL::TRIANGLE_LIST, range));
}
示例#15
0
void Main::InitCommands()
{
	// コマンド
	m_commands = CreateCommands(COMMANDS, sizeof(COMMANDS) / sizeof(COMMANDS[0]));
	function current(this, &Main::ForwardToCurrent);
	function all    (this, &Main::ForwardToAll);
	function shown  (this, &Main::ForwardToShown);
	function hidden (this, &Main::ForwardToHidden);
	function left   (this, &Main::ForwardToLeft);
	function right  (this, &Main::ForwardToRight);
	function others (this, &Main::ForwardToOthers);
	function dups   (this, &Main::ForwardToDuplicate);
	function anyFolder(this, &Main::EnableIfAnyFolder);
	function anySelect(this, &Main::EnableIfAnySelection);

	// System
	CommandProcess(L"System.Exit"	, m_form, CommandClose);
	CommandProcess(L"System.Restart", &Main::SystemRestart);
	CommandProcess(L"System.About"	, &Main::SystemAbout);

	// File
	CommandProcess(L"Explorer.Clone"	, &Main::ExplorerImport, 0);
	CommandProcess(L"Explorer.Import"	, &Main::ExplorerImport, 1);
	CommandProcess(L"File.Open"			, &Main::FileOpen, 0);
	CommandProcess(L"File.Load"			, &Main::FileLoad);
	CommandHandler(L"File.Save"			, &Main::FileSave			, null, &Main::EnableIfAnyFolder, null);
	CommandHandler(L"File.MRU"			, &Main::FileMRU			, null, &Main::ObserveMRU, null);
	CommandHandler(L"RecycleBin.Empty"	, &Main::ProcessRecycleBin	, null, &Main::ObserveRecycleBin, null);

	// Current
	CommandHandler(L"Current.Lock(true)"	, &Main::CurrentLock, BoolTrue		, &Main::ObserveLock, BoolTrue);
	CommandHandler(L"Current.Lock(false)"	, &Main::CurrentLock, BoolFalse		, &Main::ObserveLock, BoolFalse);
	CommandHandler(L"Current.Lock(toggle)"	, &Main::CurrentLock, BoolUnknown	, &Main::ObserveLock, BoolUnknown);
	CommandToFocus(L"Current.Menu"			, CommandMenu);

	CommandToFocus(L"Current.New"				, AVESTA_New);
	CommandToFocus(L"Current.NewFolder"			, AVESTA_NewFolder);
	CommandToFocus(L"Current.SelectPattern"		, AVESTA_SelectPattern);
	CommandToFocus(L"Current.Close"				, CommandClose);
	CommandToFocus(L"Current.Show(false)"		, AVESTA_Hide);
	CommandToFocus(L"Current.Export"			, AVESTA_Export);
	CommandToFocus(L"Current.Refresh"			, CommandUpdate);
	CommandToFocus(L"Current.Find"				, AVESTA_Find);
	CommandToFocus(L"Current.PatternMask"		, AVESTA_PatternMask);

	CommandToSelect(L"Current.Cut"				, CommandCut);
	CommandToSelect(L"Current.Copy"				, CommandCopy);
	CommandToSelect(L"Current.Copy.Base"		, AVESTA_CopyBase);
	CommandToSelect(L"Current.Copy.Name"		, AVESTA_CopyName);
	CommandToSelect(L"Current.Copy.Path"		, AVESTA_CopyPath);
	CommandToSelect(L"Current.Copy.Here"		, AVESTA_CopyHere);
	CommandToSelect(L"Current.Delete"			, CommandDelete);
	CommandToSelect(L"Current.Bury"				, CommandBury);
	CommandToSelect(L"Current.Rename"			, CommandRename);
	CommandToSelect(L"Current.Rename.Dialog"	, AVESTA_RenameDialog);
	CommandToSelect(L"Current.Property"			, CommandProperty);
	CommandToSelect(L"Current.CopyTo"			, AVESTA_CopyTo);
	CommandToSelect(L"Current.MoveTo"			, AVESTA_MoveTo);
	CommandToSelect(L"Current.CopyToOther"		, AVESTA_CopyToOther);
	CommandToSelect(L"Current.MoveToOther"		, AVESTA_MoveToOther);
	CommandToSelect(L"Current.CopyCheckedTo"	, AVESTA_CopyCheckedTo);
	CommandToSelect(L"Current.MoveCheckedTo"	, AVESTA_MoveCheckedTo);
	CommandToFocus(L"Current.SyncDescendants"	, AVESTA_SyncDesc);

	CommandToFocus(L"Current.Key.Up"		, CommandKeyUp);
	CommandToFocus(L"Current.Key.Down"		, CommandKeyDown);
	CommandToFocus(L"Current.Key.Left"		, CommandKeyLeft);
	CommandToFocus(L"Current.Key.Right"		, CommandKeyRight);
	CommandToFocus(L"Current.Key.Home"		, CommandKeyHome);
	CommandToFocus(L"Current.Key.End"		, CommandKeyEnd);
	CommandToFocus(L"Current.Key.PageUp"	, CommandKeyPageUp);
	CommandToFocus(L"Current.Key.PageDown"	, CommandKeyPageDown);
	CommandToFocus(L"Current.Key.Space"		, CommandKeySpace);
	CommandToFocus(L"Current.Key.Enter"		, CommandKeyEnter);
	m_commands->Alias(L"Current.Cursor.Up"		, L"Current.Key.Up"			);
	m_commands->Alias(L"Current.Cursor.Down"	, L"Current.Key.Down"		);	
	m_commands->Alias(L"Current.Cursor.Left"	, L"Current.Key.Left"		);	
	m_commands->Alias(L"Current.Cursor.Right"	, L"Current.Key.Right"		);	
	m_commands->Alias(L"Current.Cursor.Home"	, L"Current.Key.Home"		);	
	m_commands->Alias(L"Current.Cursor.End"		, L"Current.Key.End"		);	
	m_commands->Alias(L"Current.Cursor.PageUp"	, L"Current.Key.PageUp"		);
	m_commands->Alias(L"Current.Cursor.PageDown", L"Current.Key.PageDown"	);	

	CommandToSelect(L"Current.SelectNone"		, CommandSelectNone);
	CommandToCheck(L"Current.CheckAll"			, CommandCheckAll);
	CommandToCheck(L"Current.CheckNone"			, CommandCheckNone);
	CommandToFocus(L"Current.SelectAll"			, CommandSelectAll);
	CommandToFocus(L"Current.SelectChecked"		, CommandSelectChecked);
	CommandToFocus(L"Current.SelectReverse"		, CommandSelectReverse);
	CommandToFocus(L"Current.SelectToFirst"		, CommandSelectToFirst);
	CommandToFocus(L"Current.SelectToLast"		, CommandSelectToLast);

	CommandToFocus(L"Current.Undo"				, CommandUndo);

	CommandProcess(L"Current.SyncFileDialog"	, &Main::ProcessSyncFileDialog);

	CommandHandler(L"Current.Paste"			, current, CommandPaste			, &Main::ObserveClipboard		, CF_SHELLIDLIST);
	CommandHandler(L"Current.PasteTo"		, current, AVESTA_PasteTo		, &Main::ObserveClipToSelect	, CF_HDROP);
	CommandHandler(L"Current.Rename.Paste"	, current, AVESTA_RenamePaste	, &Main::ObserveClipToSelect	, CF_UNICODETEXT);
	CommandHandler(L"Current.Go.Up"			, current, CommandGoUp			, &Main::ObserveGo	, DirNorth);
	CommandHandler(L"Current.Go.Back"		, current, CommandGoBack		, &Main::ObserveGo	, DirWest);
	CommandHandler(L"Current.Go.Forward"	, current, CommandGoForward		, &Main::ObserveGo	, DirEast);
	CommandHandler(L"Current.Go.Location"	, &Main::FileOpen, 1, anyFolder, null);
	CommandHandler(L"Current.AutoArrange"	, current, AVESTA_AutoArrange	, current, AVEOBS_AutoArrange);
	CommandHandler(L"Current.Grouping"		, current, AVESTA_Grouping		, current, AVEOBS_Grouping);
	CommandHandler(L"Current.ShowAllFiles"	, current, AVESTA_ShowAllFiles	, current, AVEOBS_ShowAllFiles);

	CommandHandler(L"Current.Mode.Icon"		, current, StyleMsg(ListStyleIcon)		, &Main::ObserveMode, ListStyleIcon);
	CommandHandler(L"Current.Mode.List"		, current, StyleMsg(ListStyleList)		, &Main::ObserveMode, ListStyleList);
	CommandHandler(L"Current.Mode.Details"	, current, StyleMsg(ListStyleDetails)	, &Main::ObserveMode, ListStyleDetails);
	CommandHandler(L"Current.Mode.Thumbnail", current, StyleMsg(ListStyleThumnail)	, &Main::ObserveMode, ListStyleThumnail);
	CommandHandler(L"Current.Mode.Tile"		, current, StyleMsg(ListStyleTile)		, &Main::ObserveMode, ListStyleTile);

	CommandToFocus(L"Current.AdjustToItem"	, CommandAdjustToItem);
	CommandToFocus(L"Current.AdjustToWindow", CommandAdjustToWindow);

	// All
	CommandHandler(L"All.Close"				, all, CommandClose			, anyFolder, null);
	CommandHandler(L"All.Refresh"			, all, CommandUpdate		, anyFolder, null);
	CommandHandler(L"All.Export"			, all, AVESTA_Export		, anyFolder, null);
	CommandHandler(L"All.Show(true)"		, all, AVESTA_Show			, anyFolder, null);

	// Shown
	CommandHandler(L"Shown.Close"			, shown	, CommandClose			, anyFolder, null);
	CommandHandler(L"Shown.Refresh"			, shown	, CommandUpdate			, anyFolder, null);
	CommandHandler(L"Shown.Export"			, shown	, AVESTA_Export			, anyFolder, null);
	CommandHandler(L"Shown.AdjustToItem"	, shown	, CommandAdjustToItem	, anyFolder, null);
	CommandHandler(L"Shown.AdjustToWindow"	, shown	, CommandAdjustToWindow	, anyFolder, null);
	CommandHandler(L"Shown.ToLeft"			, m_tab, CommandShownToLeft		, anyFolder, null);
	CommandHandler(L"Shown.ToRight"			, m_tab, CommandShownToRight	, anyFolder, null);

	// Locked
	CommandHandler(L"Locked.ToLeft"		, m_tab	, CommandLockedToLeft	, anyFolder, null);
	CommandHandler(L"Locked.ToRight"	, m_tab	, CommandLockedToRight	, anyFolder, null);

	// Hidden
	CommandHandler(L"Hidden.Close"		, hidden, CommandClose	, anyFolder, null);
	CommandHandler(L"Hidden.Refresh"	, hidden, CommandUpdate	, anyFolder, null);
	CommandHandler(L"Hidden.Export"		, hidden, AVESTA_Export	, anyFolder, null);

	// Duplicate
	CommandHandler(L"Duplicate.Close"	, dups	, CommandClose	, anyFolder, null);

	// Left
	CommandHandler(L"Left.Close"		, left	, CommandClose	, anyFolder, null);
	CommandHandler(L"Left.Show(false)"	, left	, AVESTA_Hide	, anyFolder, null);
	CommandHandler(L"Left.Show(true)"	, left	, AVESTA_Show	, anyFolder, null);

	// Right
	CommandHandler(L"Right.Close"		, right	, CommandClose	, anyFolder, null);
	CommandHandler(L"Right.Show(false)"	, right	, AVESTA_Hide	, anyFolder, null);
	CommandHandler(L"Right.Show(true)"	, right	, AVESTA_Show	, anyFolder, null);

	// Others
	CommandHandler(L"Others.Close"		, others, CommandClose	, anyFolder, null);
	CommandHandler(L"Others.Show(false)", others, AVESTA_Hide	, anyFolder, null);

	// Tab
	CommandProcess(L"Tab.Focus"	, m_tab, &IWindow::Focus);
	CommandHandler(L"Tab.Sort"	, &Main::ProcessTabSort, null, anyFolder, null);
	CommandHandler(L"Tab.Next"	, m_tab, CommandGoForward	, anyFolder, null);
	CommandHandler(L"Tab.Next2"	, m_tab, CommandGoDown		, anyFolder, null);
	CommandHandler(L"Tab.Prev"	, m_tab, CommandGoBack		, anyFolder, null);
	CommandHandler(L"Tab.Prev2"	, m_tab, CommandGoUp		, anyFolder, null);
	CommandHandler(L"Current.ToLeft"	, &Main::ProcessTabMove, -1, anyFolder, null);
	CommandHandler(L"Current.ToRight"	, &Main::ProcessTabMove, +1, anyFolder, null);

	// Single Tab
	for(int i = 0; i < 9; ++i)
	{
		TCHAR name[MAX_PATH];
		wsprintf(name, L"Tab[%d].Show(toggle)", (i+1));
		CommandHandler(name, &Main::ProcessTabShow , i, &Main::ObserveTabShow , i);
		wsprintf(name, L"Tab[%d].Focus", (i+1));
		CommandHandler(name, &Main::ProcessTabFocus, i, &Main::ObserveTabFocus, i);
	}

	// Form
	CommandProcess(L"Form.Show(true)"	, &Main::WindowVisibleTrue);
	CommandProcess(L"Form.Show(false)"	, m_form, CommandMinimize);
	CommandProcess(L"Form.Show(toggle)"	, &Main::WindowVisibleToggle);
	CommandProcess(L"Form.Maximize"		, m_form, CommandMaximize);
	CommandProcess(L"Form.Restore"		, m_form, CommandRestore);
	CommandProcess(L"Form.Resize"		, m_form, CommandResize);
	CommandProcess(L"Form.Move"			, m_form, CommandMove);
	CommandProcess(L"Form.Menu"			, m_form, CommandMenu);
	CommandHandler(L"Form.DropMode"		, &Main::ProcessDropMode, null, &Main::ObserveDropMode, null);

	m_commands->Alias(L"Form.Zoom"		, L"Form.Maximize");
	m_commands->Alias(L"Form.Minimize"	, L"Form.Show(false)");
	m_commands->Alias(L"Form.Close"		, L"System.Exit");

	m_commands->Alias(L"Window.Show(true)"		, L"Form.Show(true)"	);
	m_commands->Alias(L"Window.Show(false)"		, L"Form.Show(false)"	);
	m_commands->Alias(L"Window.Show(toggle)"	, L"Form.Show(toggle)"	);
	m_commands->Alias(L"Window.Maximize"		, L"Form.Maximize"		);
	m_commands->Alias(L"Window.Restore"			, L"Form.Restore"		);
	m_commands->Alias(L"Window.Resize"			, L"Form.Resize"		);
	m_commands->Alias(L"Window.Move"			, L"Form.Move"			);
	m_commands->Alias(L"Window.Menu"			, L"Form.Menu"			);
	m_commands->Alias(L"Window.Zoom"			, L"Form.Maximize"		);
	m_commands->Alias(L"Window.Minimize"		, L"Form.Show(false)"	);
	m_commands->Alias(L"Window.Close"			, L"System.Exit"		);

	// Address
	CommandToFocus(L"Address.Focus"	, CommandFocusAddress);
	// Header
	CommandToFocus(L"Header.Focus"	, FocusHeaderMessage());
	// Tree
	CommandProcess(L"Tree.Refresh"		, &Main::ProcessTreeRefresh);
	CommandHandler(L"Tree.Sync"			, &Main::ProcessTreeSync	, null, &Main::ObserveTreeSync		, null);
	CommandHandler(L"Tree.Reflect"		, &Main::ProcessTreeReflect	, null, &Main::ObserveTreeReflect	, null);
	CommandHandler(L"Tree.AutoSync"		, &Main::OptionBoolean	, BoolTreeAutoSync		, &Main::ObserveBoolean	, BoolTreeAutoSync);
	CommandHandler(L"Tree.AutoReflect"	, &Main::OptionBoolean	, BoolTreeAutoReflect	, &Main::ObserveBoolean	, BoolTreeAutoReflect);
	CommandProcess(L"Tree.Cut"			, m_tree, CommandCut);
	CommandProcess(L"Tree.Copy"			, m_tree, CommandCopy);
	CommandProcess(L"Tree.Copy.Base"	, m_tree, AVESTA_CopyBase);
	CommandProcess(L"Tree.Copy.Name"	, m_tree, AVESTA_CopyName);
	CommandProcess(L"Tree.Copy.Path"	, m_tree, AVESTA_CopyPath);
	CommandProcess(L"Tree.Copy.Here"	, m_tree, AVESTA_CopyHere);
	CommandProcess(L"Tree.Delete"		, m_tree, CommandDelete);
	CommandProcess(L"Tree.Bury"			, m_tree, CommandBury);
	CommandProcess(L"Tree.Rename"		, m_tree, CommandRename);
	CommandProcess(L"Tree.Paste"		, m_tree, CommandPaste);
	CommandProcess(L"Tree.Property"		, m_tree, CommandProperty);
	CommandProcess(L"Tree.MoveTo"		, m_tree, AVESTA_MoveTo);
	CommandProcess(L"Tree.CopyTo"		, m_tree, AVESTA_CopyTo);

	// Option
	CommandProcess(L"Option.Reload"			, &Main::OptionReload);
	CommandProcess(L"Option.Font"			, &Main::OptionFont);
	CommandProcess(L"FolderOptions.Show"	, &Main::ProcessFolderOptionsShow);

	CommandHandler(L"Option.Thumbnail.64"	, &Main::ProcessThumbSize, 64 , &Main::ObserveThumbSize, 64 );
	CommandHandler(L"Option.Thumbnail.96"	, &Main::ProcessThumbSize, 96 , &Main::ObserveThumbSize, 96 );
	CommandHandler(L"Option.Thumbnail.128"	, &Main::ProcessThumbSize, 128, &Main::ObserveThumbSize, 128);
	CommandHandler(L"Option.Thumbnail.192"	, &Main::ProcessThumbSize, 192, &Main::ObserveThumbSize, 192);
	CommandHandler(L"Option.Thumbnail.256"	, &Main::ProcessThumbSize, 256, &Main::ObserveThumbSize, 256);
	CommandHandler(L"Arrange.Auto"			, &Main::ProcessArrange, ArrangeAuto, &Main::ObserveArrange, ArrangeAuto);
	CommandHandler(L"Arrange.Horz"			, &Main::ProcessArrange, ArrangeHorz, &Main::ObserveArrange, ArrangeHorz);
	CommandHandler(L"Arrange.Vert"			, &Main::ProcessArrange, ArrangeVert, &Main::ObserveArrange, ArrangeVert);
	CommandHandler(L"Keybind.Normal"		, &Main::ProcessKeybind, afx::KeybindNormal , &Main::ObserveKeybind, afx::KeybindNormal );
	CommandHandler(L"Keybind.Atok"			, &Main::ProcessKeybind, afx::KeybindAtok , &Main::ObserveKeybind, afx::KeybindAtok );
	CommandHandler(L"Keybind.Emacs"			, &Main::ProcessKeybind, afx::KeybindEmacs, &Main::ObserveKeybind, afx::KeybindEmacs);
	CommandHandler(L"MiddleClick.Disable"	, &Main::ProcessMiddleClick, ModifierNone   , &Main::ObserveMiddleClick, ModifierNone   );
	CommandHandler(L"MiddleClick.Control"	, &Main::ProcessMiddleClick, ModifierControl, &Main::ObserveMiddleClick, ModifierControl);
	CommandHandler(L"MiddleClick.Shift"		, &Main::ProcessMiddleClick, ModifierShift  , &Main::ObserveMiddleClick, ModifierShift  );
	CommandHandler(L"AutoCopy.None"			, &Main::ProcessAutoCopy, CopyNone, &Main::ObserveAutoCopy, CopyNone);
	CommandHandler(L"AutoCopy.Base"			, &Main::ProcessAutoCopy, CopyBase, &Main::ObserveAutoCopy, CopyBase);
	CommandHandler(L"AutoCopy.Name"			, &Main::ProcessAutoCopy, CopyName, &Main::ObserveAutoCopy, CopyName);
	CommandHandler(L"AutoCopy.Path"			, &Main::ProcessAutoCopy, CopyPath, &Main::ObserveAutoCopy, CopyPath);

	// あとでなくなるもの
	CommandProcess(L"Option.WallPaper"		, &Main::OptionWallPaper);
	CommandHandler(L"Option.Insert.Head"	, &Main::OptionInsert, InsertHead, &Main::ObserveInsert, InsertHead);
	CommandHandler(L"Option.Insert.Tail"	, &Main::OptionInsert, InsertTail, &Main::ObserveInsert, InsertTail);
	CommandHandler(L"Option.Insert.Prev"	, &Main::OptionInsert, InsertPrev, &Main::ObserveInsert, InsertPrev);
	CommandHandler(L"Option.Insert.Next"	, &Main::OptionInsert, InsertNext, &Main::ObserveInsert, InsertNext);
	CommandHandler(L"Option.TaskTray"		, &Main::OptionTaskTray		, null, &Main::ObserveTaskTray		, null);
	CommandHandler(L"Option.AlwaysTray"		, &Main::OptionAlwaysTray	, null, &Main::ObserveAlwaysTray	, null);
	CommandHandler(L"Option.CloseToTray"	, &Main::OptionCloseToTray	, null, &Main::ObserveCloseToTray	, null);
	CommandHandler(L"Option.AlwaysTop"		, &Main::OptionAlwaysTop	, null, &Main::ObserveAlwaysTop		, null);
	CommandHandler(L"Option.CheckBox"			, &Main::OptionCheckBox		, BoolCheckBox			, &Main::ObserveBoolean, BoolCheckBox);
	CommandHandler(L"Option.DnDCopyInterDrive"	, &Main::OptionBoolean		, BoolDnDCopyInterDrv	, &Main::ObserveBoolean, BoolDnDCopyInterDrv);
	CommandHandler(L"Option.DistinguishTab"		, &Main::OptionBoolean		, BoolDistinguishTab	, &Main::ObserveBoolean, BoolDistinguishTab);
	CommandHandler(L"Option.FullRowSelect"		, &Main::OptionFullRowSelect, BoolFullRowSelect		, &Main::ObserveBoolean, BoolFullRowSelect);
	CommandHandler(L"Option.GestureOnName"		, &Main::OptionBoolean		, BoolGestureOnName		, &Main::ObserveBoolean, BoolGestureOnName);
	CommandHandler(L"Option.GridLine"			, &Main::OptionGridLine		, BoolGridLine			, &Main::ObserveBoolean, BoolGridLine);
	CommandHandler(L"Option.OpenDups"			, &Main::OptionBoolean		, BoolOpenDups			, &Main::ObserveBoolean, BoolOpenDups);
	CommandHandler(L"Option.OpenNotify"			, &Main::OptionBoolean		, BoolOpenNotify		, &Main::ObserveBoolean, BoolOpenNotify);
	CommandHandler(L"Option.RestoreConditions"	, &Main::OptionBoolean		, BoolRestoreCond		, &Main::ObserveBoolean, BoolRestoreCond);
	CommandHandler(L"Option.LazyExecute"		, &Main::OptionBoolean		, BoolLazyExecute		, &Main::ObserveBoolean, BoolLazyExecute);
	CommandHandler(L"Option.LockClose"			, &Main::OptionBoolean		, BoolLockClose			, &Main::ObserveBoolean, BoolLockClose);
	CommandHandler(L"Option.LoopCursor"			, &Main::OptionBoolean		, BoolLoopCursor		, &Main::ObserveBoolean, BoolLoopCursor);
	CommandHandler(L"MiddleClick.SingleExecute"	, &Main::OptionBoolean		, BoolMiddleSingle		, &Main::ObserveBoolean, BoolMiddleSingle);
	CommandHandler(L"Option.RenameExtension"	, &Main::OptionRenameExtension, null, &Main::ObserveBoolean, BoolRenameExtension);
	CommandHandler(L"Option.PasteInFolder"		, &Main::OptionBoolean		, BoolPasteInFolder		, &Main::ObserveBoolean, BoolPasteInFolder);
	CommandHandler(L"Option.Python"				, &Main::OptionPython		, BoolPython			, &Main::ObserveBoolean, BoolPython);
	CommandHandler(L"Option.QuietProgress"		, &Main::OptionBoolean		, BoolQuietProgress		, &Main::ObserveBoolean, BoolQuietProgress);
}
int main(int argc, const char ** argv) {
	auto start = std::chrono::high_resolution_clock::now();

	std::cout << "MSAcquisitionSimulator Version " << MSAcquisitionSimulator_VERSION_MAJOR << "." << MSAcquisitionSimulator_VERSION_MINOR << "." << MSAcquisitionSimulator_VERSION_PATCH << std::endl;
	std::cout << "AcquisitionSimulator Version " << AcquisitionSimulator_VERSION_MAJOR << "." << AcquisitionSimulator_VERSION_MINOR << "." << AcquisitionSimulator_VERSION_PATCH << std::endl;

	std::string sqlite_in_path;
	std::string mzml_out_path;
	std::string param_file_path;
	std::string fido_out_path;
	std::string fasta_in_path;
	std::string target_decoy_out_path;
	std::string acquisition_algorithm_name;

	std::vector<std::string> acquisition_param_values;

	double ms1_scan_time;
	double ms2_scan_time;
	double scan_overhead_time;
	int acquisition_length;

	double elution_tau;
	double elution_sigma;

	double resolution;
	double dynamic_range;

	double db_search_min_mass;
	double db_search_max_mass;
	double db_search_mass_tolerance;
	int db_search_max_missed_cleavages;
	int db_search_max_dynamic_mods;
	int db_search_min_enzymatic_termini;
	double null_lambda;

	double max_ms1_injection_time;
	double max_ms2_injection_time;
	double ms1_target_total_ion_count;
	double ms2_target_total_ion_count;

	std::vector<DBPTM> PTMs;
	std::vector<DBEnzyme> enzymes;


	//region Command line specification
	boost::program_options::options_description general("USAGE: AcquisitionSimulator [options] ground_truth.tab\n\nOptions");
	general.add_options()
			("help", "Print usage and exit.")
			("conf,c", boost::program_options::value<std::string>(&param_file_path)->default_value("acquisition.conf"), "Input path to config file.")
			("mzml_out_path,o", boost::program_options::value<std::string>(&mzml_out_path)->default_value("sample.mzML"), "output path for mzML file.")
			("fido_out_path,f", boost::program_options::value<std::string>(&fido_out_path)->default_value("sample.fido"), "output path for fido file.")
			("target_decoy_out_path,d", boost::program_options::value<std::string>(&target_decoy_out_path)->default_value("targetDecoy.txt"), "output path for fido targetDecoy file.")
			;

	boost::program_options::options_description hidden("");
	hidden.add_options()
			("ground_truth_in_path", boost::program_options::value<std::string>(&sqlite_in_path), "input path for ground truth file made by GroundTruthSimulator.")
			;

	boost::program_options::options_description all("Allowed options");
	all.add(general).add(hidden);

	boost::program_options::positional_options_description p;
	p.add("ground_truth_in_path", -1);

	boost::program_options::variables_map vm;
	boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(all).positional(p).run(), vm);
	boost::program_options::notify(vm);
	//endregion

	//region Command line processing
	if (vm.count("help")) {
		std::cout << general << std::endl;
		return 0;
	}

	//region config file specification
	boost::program_options::options_description config("Configuration file options");
	config.add_options()
			("acquisition_algorithm", boost::program_options::value<std::string>(&acquisition_algorithm_name)->default_value("TopN"), "acquisition algorithm")
			("acquisition_algorithm_params", boost::program_options::value<std::vector<std::string>>(&acquisition_param_values)->multitoken(), "acquisition_algorithm_params")
			("ms1_scan_time", boost::program_options::value<double>(&ms1_scan_time)->default_value(0.256), "ms1_scan_time")
			("ms2_scan_time", boost::program_options::value<double>(&ms2_scan_time)->default_value(0.064), "ms2_scan_time")
			("scan_overhead_time", boost::program_options::value<double>(&scan_overhead_time)->default_value(0.015), "scan_overhead_time")
			("acquisition_length", boost::program_options::value<int>(&acquisition_length)->default_value(3600), "acquisition_length")
			("fasta", boost::program_options::value<std::string>(&fasta_in_path), "acquisition fasta_in_path")
			("elution_tau", boost::program_options::value<double>(&elution_tau)->default_value(4), "elution_tau")
			("elution_sigma", boost::program_options::value<double>(&elution_sigma)->default_value(6), "elution_sigma")
			("resolution", boost::program_options::value<double>(&resolution)->default_value(60000), "resolution")
			("dynamic_range", boost::program_options::value<double>(&dynamic_range)->default_value(5000), "dynamic_range")
			("db_search_min_mass", boost::program_options::value<double>(&db_search_min_mass)->default_value(200), "db_search_min_mass")
			("db_search_max_mass", boost::program_options::value<double>(&db_search_max_mass)->default_value(9000), "db_search_max_mass")
			("db_search_max_missed_cleavages", boost::program_options::value<int>(&db_search_max_missed_cleavages)->default_value(0), "db_search_max_missed_cleavages")
			("db_search_max_dynamic_mods", boost::program_options::value<int>(&db_search_max_dynamic_mods)->default_value(0), "db_search_max_dynamic_mods")
			("db_search_min_enzymatic_termini", boost::program_options::value<int>(&db_search_min_enzymatic_termini)->default_value(2), "db_search_min_enzymatic_termini")
			("db_search_mass_tolerance", boost::program_options::value<double>(&db_search_mass_tolerance)->default_value(.05), "db_search_mass_tolerance")
			("db_search_PTM", boost::program_options::value<std::vector<DBPTM> >(&PTMs)->multitoken(), "PTMs")
			("db_search_enzyme", boost::program_options::value<std::vector<DBEnzyme>>(&enzymes)->multitoken(), "enzymes")
			("db_search_null_lambda", boost::program_options::value<double>(&null_lambda)->default_value(6), "db_search_null_lambda")
			("max_ms1_injection_time", boost::program_options::value<double>(&max_ms1_injection_time)->default_value(0.2), "max_ms1_injection_time")
			("max_ms2_injection_time", boost::program_options::value<double>(&max_ms2_injection_time)->default_value(0.5), "max_ms2_injection_time")
			("ms1_target_total_ion_count", boost::program_options::value<double>(&ms1_target_total_ion_count)->default_value(1e6), "ms1_target_total_ion_count")
			("ms2_target_total_ion_count", boost::program_options::value<double>(&ms2_target_total_ion_count)->default_value(1e5), "ms2_target_total_ion_count")
			;
	boost::program_options::variables_map vm_config;
	std::ifstream config_file(param_file_path.c_str());

	if(!config_file.is_open()) {
		std::cerr << "Unable to open configuration file: " << param_file_path << std::endl;
		exit(1);
	}

	boost::program_options::store(boost::program_options::parse_config_file(config_file, config, true), vm_config);
	boost::program_options::notify(vm_config);
	//endregion


	ElutionShapeSimulator elution_shape_simulator(elution_tau, elution_sigma);
	std::unique_ptr<GroundTruthText> db = std::unique_ptr<GroundTruthText>(new GroundTruthText(sqlite_in_path, false));
	std::unique_ptr<Instrument> instrument = std::unique_ptr<Instrument>(new Instrument(resolution, dynamic_range, ms1_scan_time, ms2_scan_time,
																						scan_overhead_time, max_ms1_injection_time,
																						max_ms2_injection_time, ms1_target_total_ion_count,
																						ms2_target_total_ion_count));

	Sequencer sequencer(fasta_in_path, PTMs, enzymes, db_search_mass_tolerance, db_search_max_missed_cleavages, db_search_min_enzymatic_termini, db_search_min_mass, db_search_max_mass, db_search_max_dynamic_mods, null_lambda);
	Oracle oracle(db.get(), instrument.get(), elution_shape_simulator);
	MzMLWriter mzml_writer(mzml_out_path);
	FidoWriter fido_writer(fido_out_path);

	AcquisitionController* controller = get_controller(acquisition_algorithm_name, acquisition_param_values);

	int ms1_count = 0;
	int ms2_count = 0;
	int quality_ms2_count = 0;
	double current_time = 0;

	std::cout << "Simulating Acquisition:" << std::endl;

	while (current_time <= acquisition_length) {
		std::unique_ptr<ScanRequest> scan_request = controller->get_scan_request(current_time);
		std::unique_ptr<Scan> scan = oracle.get_scan_data(scan_request.get(), current_time);

		if (scan->scan_type == Scan::ScanType::MS2) {
			ms2_count++;
			MS2Scan* tmp_scan = static_cast<MS2Scan*>(scan.get());
			sequencer.sequence_ms2_scan(tmp_scan);

			if (tmp_scan->probability >= 0 && tmp_scan->peptide != "DECOY") {
				fido_writer.write_peptide(tmp_scan->probability, tmp_scan->peptide, tmp_scan->proteins);
				if (tmp_scan->probability >= .9) quality_ms2_count++;
			}

			/*double max_int = 0;
			std::string max_pep;
			for (auto itr = tmp_scan->peptide2intensity.begin(); itr != tmp_scan->peptide2intensity.end(); ++itr) {
				if (itr->second > max_int) {
					max_int = itr->second;
					max_pep = itr->first;
				}
			}
			std::cout << tmp_scan->precursor_peak.mz << " " << tmp_scan->precursor_peak.intensity << " " << tmp_scan->elapsed_time << " " << tmp_scan->TIC << " " << max_pep << " " << max_int / tmp_scan->TIC << " " << tmp_scan->peptide << std::endl;
			*/
		} else {
			ms1_count++;
		}

		controller->process_scan(scan.get());
		current_time += scan->elapsed_time;

		if (scan->scan_id % 20 == 0) {
			std::cout << "\rCurrent time: " << current_time << " seconds. MS1 count: " << ms1_count << ". MS2 count: " << ms2_count << ". Num PSMs >= 0.9: " << quality_ms2_count << std::flush;
		}

		mzml_writer.add_to_scan_buffer(std::move(scan));
		if (mzml_writer.buffer.size() > 100) mzml_writer.write_buffer();
	}

	std::cout << "\rCurrent time: " << current_time << " seconds. MS1 count: " << ms1_count << ". MS2 count: " << ms2_count << ". Num PSMs >= 0.9: " << quality_ms2_count << std::endl;

	mzml_writer.write_buffer();
	mzml_writer.output_file_end();

	mzml_writer.close_file();
	fido_writer.close_file();

	sequencer.write_target_decoy_file(target_decoy_out_path);

	auto end = std::chrono::high_resolution_clock::now();

	std::cout << "Simulation Complete." << std::endl;
	std::cout << "Elapsed time: " << std::chrono::duration_cast<std::chrono::seconds>(end-start).count() << " seconds" << std::endl;

	return 0;
}
    void BVH4Intersector8Hybrid<PrimitiveIntersector8>::occluded(avxb* valid_i, BVH4* bvh, Ray8& ray)
    {
      /* load ray */
      const avxb valid = *valid_i;
      avxb terminated = !valid;
      avx3f ray_org = ray.org, ray_dir = ray.dir;
      avxf ray_tnear = ray.tnear, ray_tfar  = ray.tfar;
#if defined(__FIX_RAYS__)
      const avxf float_range = 0.1f*FLT_MAX;
      ray_org = clamp(ray_org,avx3f(-float_range),avx3f(+float_range));
      ray_dir = clamp(ray_dir,avx3f(-float_range),avx3f(+float_range));
      ray_tnear = max(ray_tnear,FLT_MIN); 
      ray_tfar  = min(ray_tfar,float(inf)); 
#endif
      const avx3f rdir = rcp_safe(ray_dir);
      const avx3f org(ray_org), org_rdir = org * rdir;
      ray_tnear = select(valid,ray_tnear,avxf(pos_inf));
      ray_tfar  = select(valid,ray_tfar ,avxf(neg_inf));
      const avxf inf = avxf(pos_inf);
      
      /* allocate stack and push root node */
      avxf    stack_near[stackSizeChunk];
      NodeRef stack_node[stackSizeChunk];
      stack_node[0] = BVH4::invalidNode;
      stack_near[0] = inf;
      stack_node[1] = bvh->root;
      stack_near[1] = ray_tnear; 
      NodeRef* stackEnd = stack_node+stackSizeChunk;
      NodeRef* __restrict__ sptr_node = stack_node + 2;
      avxf*    __restrict__ sptr_near = stack_near + 2;
      
      while (1)
      {
        /* pop next node from stack */
        assert(sptr_node > stack_node);
        sptr_node--;
        sptr_near--;
        NodeRef curNode = *sptr_node;
        if (unlikely(curNode == BVH4::invalidNode)) {
          assert(sptr_node == stack_node);
          break;
        }

        /* cull node if behind closest hit point */
        avxf curDist = *sptr_near;
        const avxb active = curDist < ray_tfar;
        if (unlikely(none(active))) 
          continue;
        
        /* switch to single ray traversal */
#if !defined(__WIN32__) || defined(__X86_64__)
        size_t bits = movemask(active);
        if (unlikely(__popcnt(bits) <= SWITCH_THRESHOLD)) {
          for (size_t i=__bsf(bits); bits!=0; bits=__btc(bits,i), i=__bsf(bits)) {
            if (occluded1(bvh,curNode,i,ray,ray_org,ray_dir,rdir,ray_tnear,ray_tfar))
              terminated[i] = -1;
          }
          if (all(terminated)) break;
          ray_tfar = select(terminated,avxf(neg_inf),ray_tfar);
          continue;
        }
#endif
                
        while (1)
        {
          /* test if this is a leaf node */
          if (unlikely(curNode.isLeaf()))
            break;
          
          const avxb valid_node = ray_tfar > curDist;
          STAT3(shadow.trav_nodes,1,popcnt(valid_node),8);
          const Node* __restrict__ const node = curNode.node();
          
          /* pop of next node */
          assert(sptr_node > stack_node);
          sptr_node--;
          sptr_near--;
          curNode = *sptr_node;
          curDist = *sptr_near;
          
#pragma unroll(4)
          for (unsigned i=0; i<4; i++)
          {
            const NodeRef child = node->children[i];
            if (unlikely(child == BVH4::emptyNode)) break;
            
#if defined(__AVX2__)
            const avxf lclipMinX = msub(node->lower_x[i],rdir.x,org_rdir.x);
            const avxf lclipMinY = msub(node->lower_y[i],rdir.y,org_rdir.y);
            const avxf lclipMinZ = msub(node->lower_z[i],rdir.z,org_rdir.z);
            const avxf lclipMaxX = msub(node->upper_x[i],rdir.x,org_rdir.x);
            const avxf lclipMaxY = msub(node->upper_y[i],rdir.y,org_rdir.y);
            const avxf lclipMaxZ = msub(node->upper_z[i],rdir.z,org_rdir.z);
            const avxf lnearP = maxi(maxi(mini(lclipMinX, lclipMaxX), mini(lclipMinY, lclipMaxY)), mini(lclipMinZ, lclipMaxZ));
            const avxf lfarP  = mini(mini(maxi(lclipMinX, lclipMaxX), maxi(lclipMinY, lclipMaxY)), maxi(lclipMinZ, lclipMaxZ));
            const avxb lhit   = maxi(lnearP,ray_tnear) <= mini(lfarP,ray_tfar);      
#else
            const avxf lclipMinX = (node->lower_x[i] - org.x) * rdir.x;
            const avxf lclipMinY = (node->lower_y[i] - org.y) * rdir.y;
            const avxf lclipMinZ = (node->lower_z[i] - org.z) * rdir.z;
            const avxf lclipMaxX = (node->upper_x[i] - org.x) * rdir.x;
            const avxf lclipMaxY = (node->upper_y[i] - org.y) * rdir.y;
            const avxf lclipMaxZ = (node->upper_z[i] - org.z) * rdir.z;
            const avxf lnearP = max(max(min(lclipMinX, lclipMaxX), min(lclipMinY, lclipMaxY)), min(lclipMinZ, lclipMaxZ));
            const avxf lfarP  = min(min(max(lclipMinX, lclipMaxX), max(lclipMinY, lclipMaxY)), max(lclipMinZ, lclipMaxZ));
            const avxb lhit   = max(lnearP,ray_tnear) <= min(lfarP,ray_tfar);      
#endif
            
            /* if we hit the child we choose to continue with that child if it 
               is closer than the current next child, or we push it onto the stack */
            if (likely(any(lhit)))
            {
              assert(sptr_node < stackEnd);
              assert(child != BVH4::emptyNode);
              const avxf childDist = select(lhit,lnearP,inf);
              sptr_node++;
              sptr_near++;
              
              /* push cur node onto stack and continue with hit child */
              if (any(childDist < curDist))
              {
                *(sptr_node-1) = curNode;
                *(sptr_near-1) = curDist; 
                curDist = childDist;
                curNode = child;
              }
              
              /* push hit child onto stack */
              else {
                *(sptr_node-1) = child;
                *(sptr_near-1) = childDist; 
              }
            }	      
          }
        }
        
        /* return if stack is empty */
        if (unlikely(curNode == BVH4::invalidNode)) {
          assert(sptr_node == stack_node);
          break;
        }
        
        /* intersect leaf */
        const avxb valid_leaf = ray_tfar > curDist;
        STAT3(shadow.trav_leaves,1,popcnt(valid_leaf),8);
        size_t items; const Primitive* prim = (Primitive*) curNode.leaf(items);
        terminated |= PrimitiveIntersector8::occluded(!terminated,ray,prim,items,bvh->geometry);
        if (all(terminated)) break;
        ray_tfar = select(terminated,avxf(neg_inf),ray_tfar);
      }
      store8i(valid & terminated,&ray.geomID,0);
      AVX_ZERO_UPPER();
    }
示例#18
0
            virtual bool run(const string& dbName, BSONObj& cmdObj, string& errmsg, BSONObjBuilder& result, bool) {
                LastError *le = lastError.disableForCommand();
                {
                    assert( le );
                    if ( le->msg.size() && le->nPrev == 1 ){
                        le->appendSelf( result );
                        return true;
                    }
                }
                
                ClientInfo * client = ClientInfo::get();
                set<string> * shards = client->getPrev();
                
                if ( shards->size() == 0 ){
                    result.appendNull( "err" );
                    return true;
                }

                //log() << "getlasterror enter: " << shards->size() << endl;


                vector<OID> writebacks;
                
                // handle single server
                if ( shards->size() == 1 ){
                    string theShard = *(shards->begin() );
                    result.append( "theshard" , theShard.c_str() );
                    ShardConnection conn( theShard , "" );
                    BSONObj res;
                    bool ok = conn->runCommand( dbName , cmdObj , res );
                    //log() << "\t" << res << endl;
                    result.appendElements( res );
                    conn.done();
                    result.append( "singleShard" , theShard );
                    addWriteBack( writebacks , res );
                    
                    // hit other machines just to block
                    for ( set<string>::const_iterator i=client->sinceLastGetError().begin(); i!=client->sinceLastGetError().end(); ++i ){
                        string temp = *i;
                        if ( temp == theShard )
                            continue;
                        
                        ShardConnection conn( temp , "" );
                        addWriteBack( writebacks , conn->getLastErrorDetailed() );
                        conn.done();
                    }
                    client->clearSinceLastGetError();
                    handleWriteBacks( writebacks );
                    return ok;
                }
                
                BSONArrayBuilder bbb( result.subarrayStart( "shards" ) );

                long long n = 0;

                // hit each shard
                vector<string> errors;
                vector<BSONObj> errorObjects;
                for ( set<string>::iterator i = shards->begin(); i != shards->end(); i++ ){
                    string theShard = *i;
                    bbb.append( theShard );
                    ShardConnection conn( theShard , "" );
                    BSONObj res;
                    bool ok = conn->runCommand( dbName , cmdObj , res );
                    addWriteBack( writebacks, res );
                    string temp = DBClientWithCommands::getLastErrorString( res );
                    if ( ok == false || temp.size() ){
                        errors.push_back( temp );
                        errorObjects.push_back( res );
                    }
                    n += res["n"].numberLong();
                    conn.done();
                }
                
                bbb.done();
                
                result.appendNumber( "n" , n );

                // hit other machines just to block
                for ( set<string>::const_iterator i=client->sinceLastGetError().begin(); i!=client->sinceLastGetError().end(); ++i ){
                    string temp = *i;
                    if ( shards->count( temp ) )
                        continue;
                    
                    ShardConnection conn( temp , "" );
                    addWriteBack( writebacks, conn->getLastErrorDetailed() );
                    conn.done();
                }
                client->clearSinceLastGetError();

                if ( errors.size() == 0 ){
                    result.appendNull( "err" );
                    handleWriteBacks( writebacks );
                    return true;
                }
                
                result.append( "err" , errors[0].c_str() );
                
                { // errs
                    BSONArrayBuilder all( result.subarrayStart( "errs" ) );
                    for ( unsigned i=0; i<errors.size(); i++ ){
                        all.append( errors[i].c_str() );
                    }
                    all.done();
                }

                { // errObjects
                    BSONArrayBuilder all( result.subarrayStart( "errObjects" ) );
                    for ( unsigned i=0; i<errorObjects.size(); i++ ){
                        all.append( errorObjects[i] );
                    }
                    all.done();
                }
                handleWriteBacks( writebacks );
                return true;
            }
示例#19
0
void Game()
{
	SDL::Screen screen;
	SDL::GetVideoSurface(screen);
	SDL::Event events;
	SDL::Rect updaterects[6];
	SDL::Rect all(0, 0, 640, 480);
	SDL::Rect ballrect, play1rect, comrect;
	int ballvx, ballvy;
	bool playerwon = false;

	Score score;
	Ball ball(309, 229, 11, 11, ((rand() % 4) + 2), -((rand() % 4) + 2));
	Computer computer(629, 187, 11, 106);

	Paddle playerone(0, 187, 11, 106);
	HandleInput handleinput(playerone);

	while(!handleinput)
	{
		// Update everything
		ball.Update();
		playerone.Update();
		computer.UpdateAI(ball);

		// needed for game logic
		ballrect = ball.Get(ballvx, ballvy);
		play1rect = playerone.Get();
		comrect = computer.Get();

		// check if it hit the paddle for player and then the same for computer
		if((ballrect.x <= 11) &&
				(ballrect.y >= play1rect.y) &&
				((ballrect.y+11) <= play1rect.y + 106))
		{
			ball.SetVel(-ballvx, ballvy);
		}

		if(((ballrect.x + 11) >= 629) &&
				(ballrect.y >= comrect.y) &&
				((ballrect.y+11) <= comrect.y + 106))
		{
			ball.SetVel(-ballvx, ballvy);
		}

		// scoring if it goes past either paddle
		if(ballrect.x+10 < 11)
		{
			ball.Set(309, 229, 11, 11, ((rand() % 4) + 2), ((rand() % 4) + 2));
			score.m_Two++;
		}

		if(ballrect.x+10 > 629)
		{
			ball.Set(309, 229, 11, 11, -((rand() % 4) + 2), -((rand() % 4) + 2));
			score.m_One++;
		}

		// somene's won
		if(score.m_One > 9)
		{
			std::cout << "Congrats, you won." << std::endl;
			playerwon = true;
			break;
		}
		if(score.m_Two > 9)
		{
			std::cout << "Sorry, you lost, try again." << std::endl;
			break;
		}

		// drawing code
		screen.FillRect(all, 0);

		updaterects[0] = ball.Draw(screen);
		updaterects[1] = computer.Draw(screen);
		updaterects[2] = playerone.Draw(screen);
		score.Draw(screen, updaterects[3], updaterects[4]);

		// see if we're double buffering, if so, do a screen Flip
		if((screen.Get()->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF)
			screen.Flip();
		else
		{
			updaterects[5] = all;
			screen.UpdateRects(6, updaterects);
		}

		// Poll for new events, then wait a bit
		events.Poll(handleinput);
		Delay();
	}
}
示例#20
0
    bool ClientInfo::getLastError( const string& dbName,
                                   const BSONObj& options,
                                   BSONObjBuilder& result,
                                   string& errmsg,
                                   bool fromWriteBackListener)
    {

        scoped_ptr<TimerHolder> gleTimerHolder;
        if ( ! fromWriteBackListener ) {
            bool doTiming = false;
            const BSONElement& e = options["w"];
            if ( e.isNumber() ) {
                doTiming = e.numberInt() > 1;
            }
            else if ( e.type() == String ) {
                doTiming = true;
            }
            if ( doTiming ) {
                gleTimerHolder.reset( new TimerHolder( &gleWtimeStats ) );
            }
        }


        set<string> * shards = getPrev();

        if ( shards->size() == 0 ) {
            result.appendNull( "err" );
            return true;
        }

        vector<WBInfo> writebacks;

        //
        // TODO: These branches should be collapsed into a single codepath
        //

        // handle single server
        if ( shards->size() == 1 ) {
            string theShard = *(shards->begin() );

            BSONObj res;
            bool ok = false;
            {
                LOG(5) << "gathering response for gle from: " << theShard << endl;

                ShardConnection conn( theShard , "" );
                try {
                    ok = conn->runCommand( dbName , options , res );
                }
                catch( std::exception &e ) {

                    string message =
                            str::stream() << "could not get last error from shard " << theShard
                                          << causedBy( e );

                    warning() << message << endl;
                    errmsg = message;

                    // Catch everything that happens here, since we need to ensure we return our connection when we're
                    // finished.
                    conn.done();

                    return false;
                }


                res = res.getOwned();
                conn.done();
            }

            _addWriteBack( writebacks, res, true );

            LOG(4) << "gathering writebacks from " << sinceLastGetError().size() << " hosts for"
                   << " gle (" << theShard << ")" << endl;

            // hit other machines just to block
            for ( set<string>::const_iterator i=sinceLastGetError().begin(); i!=sinceLastGetError().end(); ++i ) {
                string temp = *i;
                if ( temp == theShard )
                    continue;

                LOG(5) << "gathering writebacks for single-shard gle from: " << temp << endl;

                try {
                    ShardConnection conn( temp , "" );
                    ON_BLOCK_EXIT_OBJ( conn, &ShardConnection::done );
                    _addWriteBack( writebacks, conn->getLastErrorDetailed(), false );

                }
                catch( std::exception &e ){
                    warning() << "could not clear last error from shard " << temp << causedBy( e ) << endl;
                }

            }
            clearSinceLastGetError();

            // We never need to handle writebacks if we're coming from the wbl itself
            if ( writebacks.size() && !fromWriteBackListener ){

                LOG(4) << "checking " << writebacks.size() << " writebacks for"
                       << " gle (" << theShard << ")" << endl;

                vector<BSONObj> v = _handleWriteBacks( writebacks , false );

                // this will usually be 1
                // it can be greater than 1 if a write to a different shard
                // than the last write op had a writeback
                // all we're going to report is the first
                // since that's the current write
                // but we block for all
                verify( v.size() >= 1 );

                if ( res["writebackSince"].numberInt() > 0 ) {
                    // got writeback from older op
                    // ignore the result from it, just needed to wait
                    result.appendElements( res );
                }
                else if ( writebacks[0].fromLastOperation ) {
                    result.appendElements( v[0] );
                    result.appendElementsUnique( res );
                    result.append( "writebackGLE" , v[0] );
                    result.append( "initialGLEHost" , theShard );
                    result.append( "initialGLE", res );
                }
                else {
                    // there was a writeback
                    // but its from an old operations
                    // so all that's important is that we block, not that we return stats
                    result.appendElements( res );
                }
            }
            else {
                result.append( "singleShard" , theShard );
                result.appendElements( res );
            }

            return ok;
        }

        BSONArrayBuilder bbb( result.subarrayStart( "shards" ) );
        BSONObjBuilder shardRawGLE;

        long long n = 0;

        int updatedExistingStat = 0; // 0 is none, -1 has but false, 1 has true

        // hit each shard
        vector<string> errors;
        vector<BSONObj> errorObjects;
        for ( set<string>::iterator i = shards->begin(); i != shards->end(); i++ ) {
            string theShard = *i;
            bbb.append( theShard );

            LOG(5) << "gathering a response for gle from: " << theShard << endl;

            boost::scoped_ptr<ShardConnection> conn;
            BSONObj res;
            bool ok = false;
            try {
                conn.reset( new ShardConnection( theShard , "" ) ); // constructor can throw if shard is down
                ok = (*conn)->runCommand( dbName , options , res );
                shardRawGLE.append( theShard , res );
            }
            catch( std::exception &e ){

                // Safe to return here, since we haven't started any extra processing yet, just collecting
                // responses.

                string message =
                        str::stream() << "could not get last error from a shard " << theShard
                                      << causedBy( e );

                warning() << message << endl;
                errmsg = message;

                if (conn)
                    conn->done();

                return false;
            }

            _addWriteBack( writebacks, res, true );

            string temp = DBClientWithCommands::getLastErrorString( res );
            if ( (*conn)->type() != ConnectionString::SYNC && ( ok == false || temp.size() ) ) {
                errors.push_back( temp );
                errorObjects.push_back( res );
            }

            n += res["n"].numberLong();
            if ( res["updatedExisting"].type() ) {
                if ( res["updatedExisting"].trueValue() )
                    updatedExistingStat = 1;
                else if ( updatedExistingStat == 0 )
                    updatedExistingStat = -1;
            }

            conn->done();
        }

        bbb.done();
        result.append( "shardRawGLE" , shardRawGLE.obj() );

        result.appendNumber( "n" , n );
        if ( updatedExistingStat )
            result.appendBool( "updatedExisting" , updatedExistingStat > 0 );

        LOG(4) << "gathering writebacks from " << sinceLastGetError().size() << " hosts for"
               << " gle (" << shards->size() << " shards)" << endl;

        // hit other machines just to block
        for ( set<string>::const_iterator i=sinceLastGetError().begin(); i!=sinceLastGetError().end(); ++i ) {
            string temp = *i;
            if ( shards->count( temp ) )
                continue;

            LOG(5) << "gathering writebacks for multi-shard gle from: " << temp << endl;

            ShardConnection conn( temp , "" );
            try {
                _addWriteBack( writebacks, conn->getLastErrorDetailed(), false );
            }
            catch( std::exception &e ){
                warning() << "could not clear last error from a shard " << temp << causedBy( e ) << endl;
            }
            conn.done();
        }
        clearSinceLastGetError();

        LOG(4) << "checking " << writebacks.size() << " writebacks for"
                << " gle (" << shards->size() << " shards)" << endl;

        // Multi-shard results from the writeback listener implicitly means that:
        // A) no versioning was used (multi-update/delete)
        // B) internal GLE was used (bulk insert)

        if ( errors.size() == 0 ) {
            result.appendNull( "err" );
            _handleWriteBacks( writebacks , fromWriteBackListener );
            return true;
        }

        result.append( "err" , errors[0].c_str() );

        {
            // errs
            BSONArrayBuilder all( result.subarrayStart( "errs" ) );
            for ( unsigned i=0; i<errors.size(); i++ ) {
                all.append( errors[i].c_str() );
            }
            all.done();
        }

        {
            // errObjects
            BSONArrayBuilder all( result.subarrayStart( "errObjects" ) );
            for ( unsigned i=0; i<errorObjects.size(); i++ ) {
                all.append( errorObjects[i] );
            }
            all.done();
        }

        _handleWriteBacks( writebacks , fromWriteBackListener );
        return true;
    }
示例#21
0
/*
 * Converts a vector to a boolean: true if all elements are nonzero, false
 * otherwise.
 */
bool MATLAB_NAMESPACE::to_bool(const VECTOR_T* v) {
	return all(v) == 1;
}
示例#22
0
int main(int argc, char** argv) {

	// between
	ok(between('a','z','c'), "c is between a and z");
	fail(between('a','z','C'), "C is not between a and z");

	// num
	ok(num('0'), "0 is a number");
	ok(num('9'), "9 is a number");
	fail(num('/'), "/ is not a number");
	fail(num(':'), "0 is not a number");

	// alpha
	ok(alpha('a'), "a is a letter");	
	ok(alpha('z'), "z is a letter");	
	ok(alpha('A'), "A is a letter");	
	ok(alpha('Z'), "Z is a letter");	
	fail(alpha('@'), "@ is not a letter");	
	fail(alpha('['), "[ is not a letter");	
	fail(alpha('`'), "` is not a letter");	
	fail(alpha('{'), "{ is not a letter");	
	
	// alphanum
	ok(alphanum('a'), "a is alphanum");
	ok(alphanum('z'), "z is alphanum");
	ok(alphanum('A'), "A is alphanum");
	ok(alphanum('Z'), "Z is alphanum");
	ok(alphanum('0'), "0 is alphanum");
	ok(alphanum('9'), "9 is alphanum");
	fail(alpha('@'), "@ is not alphanum ");	
	fail(alpha('['), "[ is not alphanum");	
	fail(alpha('`'), "` is not alphanum");	
	fail(alpha('{'), "{ is not alphanum");	

	// space
	ok(space(' '), "space is space");
	fail(space('\n'), "new line is not space");
	fail(space('\r'), "cr is not space");
	fail(space('\t'), "tab is not space");

	// tab
	ok(tab('\t'), "tab is tab");
	fail(tab(' '), "space is not tab");
	fail(tab('\n'), "new line is not tab");
	fail(tab('\r'), "cr is not tab");
	
	// nl
	ok(nl('\n'), "new line is new line");
	fail(nl('\t'), "tab is not new line");
	fail(nl(' '), "space is not new line");
	fail(nl('\r'), "cr is not new line");
	
	// cr
	fail(cr('\n'), "new line is not cr");
	fail(cr('\t'), "tab is not cr");
	fail(cr(' '), "space is not cr");
	ok(cr('\r'), "cr is cr");
	
	// whitespace
	ok(whitespace('\n'), "new line is whitespace");
	ok(whitespace('\t'), "tab is whitespace");
	ok(whitespace(' '), "space is whitespace");
	ok(whitespace('\r'), "cr is whitespace");
	fail(whitespace('\b'), "backspace is not whitespace");

	// colon
	ok(colon(':'), "colon is colon");
	fail(colon(';'), "semicolon is not colon");

	// semi
	fail(semi(':'), "colon is not semicolon");
	ok(semi(';'), "semicolon is semicolon");

	// slash
	fail(slash('\\'), "\\ is not /");
	ok(slash('/'), "/ is /");

	// dot
	fail(dot('*'), "* is not .");
	ok(dot('.'), ". is .");
	
	// star
	ok(star('*'), "* is *");
	fail(star('.'), ". is not *");
	
	// question
	ok(question('?'), "? is ?");

	// hex
	ok(hex('a'), "a is hex");
	ok(hex('f'), "f is hex");
	ok(hex('A'), "A is hex");
	ok(hex('F'), "F is hex");
	ok(hex('0'), "0 is hex");
	ok(hex('9'), "9 is hex");
	fail(hex('g'), "g is not hex");
	fail(hex('G'), "G is not hex");
	
	// decimal
	ok(decimal('0'), "0 is decimal");
	ok(decimal('9'), "9 is decimal");
	ok(decimal('.'), ". is decimal");
	fail(decimal('a'), "a is not decimal");

	// ctrl
	ok(ctrl('\b'), "Backspace is ctrl");
	ok(ctrl('\a'), "Bell is ctrl");
	ok(ctrl(127), "Del is ctrl");
	fail(ctrl('a'), "a is not ctrl");

	// any 
	value(3,any(alpha,"abc123"), "three letters at abc123");
	value(0,any(num,"abc123"), "no numbers at abc123");
	value(6,any(alphanum,"abc123"), "six alphanum in abc123");
	
	// until
	value(5,until(space,"hello world!"), "5 letters until space");
	value(11,until(question,"hello world?"), "11 letters until question");
	value(12,until(ctrl,"hello world?"), "12 chacters till end");

	// crlf, eol, and upto
	value(6, upto(eol, "line 1\r\nline 1\r\n"), "6 chars upto crlf");
	value(0, upto(eol, "\r\n\r\n"), "0 characters to end of line");
	value(12, upto(eol, "hello world!"), "12 characters to eol");

	// all test
	value(5, all(dot, ".....\r\n"), "there are 5 dots");

	return done("test_parse");
}
示例#23
0
CScript ParseScript(const std::string& s)
{
    CScript result;

    static std::map<std::string, opcodetype> mapOpNames;

    if (mapOpNames.empty())
    {
        for (unsigned int op = 0; op <= MAX_OPCODE; op++)
        {
            // Allow OP_RESERVED to get into mapOpNames
            if (op < OP_NOP && op != OP_RESERVED)
                continue;

            const char* name = GetOpName(static_cast<opcodetype>(op));
            if (strcmp(name, "OP_UNKNOWN") == 0)
                continue;
            std::string strName(name);
            mapOpNames[strName] = static_cast<opcodetype>(op);
            // Convenience: OP_ADD and just ADD are both recognized:
            boost::algorithm::replace_first(strName, "OP_", "");
            mapOpNames[strName] = static_cast<opcodetype>(op);
        }
    }

    std::vector<std::string> words;
    boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"), boost::algorithm::token_compress_on);

    for (std::vector<std::string>::const_iterator w = words.begin(); w != words.end(); ++w)
    {
        if (w->empty())
        {
            // Empty string, ignore. (boost::split given '' will return one word)
        }
        else if (all(*w, boost::algorithm::is_digit()) ||
            (boost::algorithm::starts_with(*w, "-") && all(std::string(w->begin()+1, w->end()), boost::algorithm::is_digit())))
        {
            // Number
            int64_t n = atoi64(*w);
            result << n;
        }
        else if (boost::algorithm::starts_with(*w, "0x") && (w->begin()+2 != w->end()) && IsHex(std::string(w->begin()+2, w->end())))
        {
            // Raw hex data, inserted NOT pushed onto stack:
            std::vector<unsigned char> raw = ParseHex(std::string(w->begin()+2, w->end()));
            result.insert(result.end(), raw.begin(), raw.end());
        }
        else if (w->size() >= 2 && boost::algorithm::starts_with(*w, "'") && boost::algorithm::ends_with(*w, "'"))
        {
            // Single-quoted string, pushed as data. NOTE: this is poor-man's
            // parsing, spaces/tabs/newlines in single-quoted strings won't work.
            std::vector<unsigned char> value(w->begin()+1, w->end()-1);
            result << value;
        }
        else if (mapOpNames.count(*w))
        {
            // opcode, e.g. OP_ADD or ADD:
            result << mapOpNames[*w];
        }
        else
        {
            throw std::runtime_error("script parse error");
        }
    }

    return result;
}
示例#24
0
void AllowedGroupTokensMessageArg::append(MessageBuilder &builder) const
{
  const MessageFragment *fragment[4];
  int nFragments = 0;
  if (allow_.groupToken(GroupToken::dataTagLiteral))
    fragment[nFragments++] = &ParserMessages::parameterLiteral;
  if (allow_.groupToken(GroupToken::dataTagGroup))
    fragment[nFragments++] = &ParserMessages::dataTagGroup;
  switch (allow_.group()) {
  case GroupToken::modelGroup:
    fragment[nFragments++] = &ParserMessages::modelGroup;
    break;
  case GroupToken::dataTagTemplateGroup:
    fragment[nFragments++] = &ParserMessages::dataTagTemplateGroup;
    break;
  default:
    break;
  }
  switch (allow_.nameStart()) {
  case GroupToken::name:
    fragment[nFragments++] = &ParserMessages::name;
    break;
  case GroupToken::nameToken:
    fragment[nFragments++] = &ParserMessages::nameToken;
    break;
  case GroupToken::elementToken:
    fragment[nFragments++] = &ParserMessages::elementToken;
    break;
  default:
    break;
  }
  Boolean first = 1;
  for (int i = 0; i < nFragments; i++) {
    if (!first)
      builder.appendFragment(ParserMessages::listSep);
    else
      first = 0;
    builder.appendFragment(*fragment[i]);
  }
  if (allow_.groupToken(GroupToken::pcdata)) {
    if (!first)
      builder.appendFragment(ParserMessages::listSep);
    StringC pcdata(syntax_->delimGeneral(Syntax::dRNI));
    pcdata += syntax_->reservedName(Syntax::rPCDATA);
    builder.appendChars(pcdata.data(), pcdata.size());
  }
  if (allow_.groupToken(GroupToken::all)) {
    if (!first)
      builder.appendFragment(ParserMessages::listSep);
    StringC all(syntax_->delimGeneral(Syntax::dRNI));
    all += syntax_->reservedName(Syntax::rALL);
    builder.appendChars(all.data(), all.size());
  }
  if (allow_.groupToken(GroupToken::implicit)) {
    if (!first)
      builder.appendFragment(ParserMessages::listSep);
    StringC implicit(syntax_->delimGeneral(Syntax::dRNI));
    implicit += syntax_->reservedName(Syntax::rIMPLICIT);
    builder.appendChars(implicit.data(), implicit.size());
  }
}
示例#25
0
文件: all.hpp 项目: myeisha/libense
constexpr bool all(bool arg1, Rest... rest)
{
	return arg1 && all(rest...);
}
示例#26
0
 bool all(const Container& c, Predicate p)
 {
   return all(begin(c), end(c), p);
 }
示例#27
0
文件: mcd.hpp 项目: gnzlbg/hana
 static constexpr auto equal_impl(X x, Y y) {
     return all(members<R>, [=](auto k_f) {
         return equal(second(k_f)(x), second(k_f)(y));
     });
 }
示例#28
0
int main(int argc, char *argv[])
{
  Teuchos::GlobalMPISession session(&argc, &argv);
  Teuchos::RCP<const Teuchos::Comm<int> > comm =
    Teuchos::DefaultComm<int>::getComm();

  int rank = comm->getRank();

  if (rank > 0)
    return 0;

  // Set a few parameters, and then validate them.

  Teuchos::ParameterList validParameters;

  Teuchos::ParameterList myParams("testParameterList");

  myParams.set("debug_level", "detailed_status");        
  myParams.set("debug_procs", "all");   
  myParams.set("debug_output_stream", "std::cout");

  myParams.set("timer_output_file", "appPerformance.txt");

  // Normally an application would not call this.  The
  // Environment object will validate the entered parameters.
  // Since debug_procs is an IntegerRangeList,
  // this call will convert it to a Teuchos::Array that uses
  // a special flag to indicate "all" or "none".

  try{
    Zoltan2::createValidatorList(myParams, validParameters);
    myParams.validateParametersAndSetDefaults(validParameters);
    Zoltan2::Environment::convertStringToInt(myParams);
  }
  catch(std::exception &e){
    std::cerr << "Validate parameters generated an error:" << std::endl;
    std::cerr << e.what() << std::endl;
    std::cerr << "FAIL" << std::endl;
    return 1;
  }

  validParameters = Teuchos::ParameterList();

  std::cout << std::endl;
  std::cout << "A few parameters after validation: " << std::endl;
  std::cout << myParams << std::endl;

  rangeList_t *a1 = myParams.getPtr<rangeList_t>("debug_procs");
  std::cout << "debug_procs translation: ";
  Zoltan2::printIntegralRangeList(std::cout, *a1);
  std::cout << std::endl;

  // Now let's enter a bad value for a parameter and make sure
  // we get an error.

  Teuchos::ParameterList faultyParams("badParameterList");
  faultyParams.set("debug_procs", "not-even-remotely-an-integer-range");
  bool failed = false;
  try{
    Zoltan2::createValidatorList(faultyParams, validParameters);
    faultyParams.validateParametersAndSetDefaults(validParameters);
  }
  catch(std::exception &e){
    std::cout << std::endl;
    std::cout << "Invalid parameter correctly generated an error:" << std::endl;
    std::cout << e.what() << std::endl;
    failed = true;
  }

  validParameters = Teuchos::ParameterList();

  if (!failed){
    std::cerr << "Bad parameter was not detected in parameter list." << std::endl;
    return 1;
  }

  // Now set every parameter to a reasonable value

  Teuchos::ParameterList all("setAllParametersList");
  all.set("debug_level", "basic_status");

  all.set("debug_procs", "1,2,5-10,2");
  all.set("memory_procs", "1,2,3,4,all");

  all.set("debug_output_stream", "std::cerr");
  all.set("timer_output_stream", "std::cout");
  all.set("memory_output_stream", "/dev/null");


  all.set("debug_output_file", "/home/me/debug.txt");
  all.set("timer_output_file", "/home/me/performance.txt");
  all.set("memory_output_file", "/home/me/memoryUsed.txt");

  all.set("speed_versus_quality", "speed");
  all.set("memory_versus_speed", "memory");

  all.set("error_check_level", "basic_assertions");

  all.set("random_seed", .12121212);

  all.set("topology", "2,6,6");

  all.set("randomize_input", "true");

  all.set("partitioning_objective", "minimize_cut_edge_weight");

  all.set("imbalance_tolerance", 1.2);

  all.set("num_global_parts", 12);
  all.set("num_local_parts", 2);

  all.set("partitioning_approach", "partition");

  all.set("objects_to_partition", "graph_vertices");

  all.set("model", "hypergraph");

  all.set("algorithm", "phg");

  all.set("symmetrize_input", "no");
  all.set("subset_graph", "false");

  try{
    Zoltan2::createValidatorList(all, validParameters);
    all.validateParametersAndSetDefaults(validParameters);
    Zoltan2::Environment::convertStringToInt(all);
  }
  catch(std::exception &e){
    std::cerr << "Validate parameters generated an error:" << std::endl;
    std::cerr << e.what() << std::endl;
    std::cerr << "FAIL" << std::endl;
    return 1;
  }

  std::cout << std::endl;
  std::cout << "All parameters validated and modified: ";
  std::cout << all << std::endl;

  a1 = all.getPtr<rangeList_t>("debug_procs");
  std::cout << "debug_procs translation: ";
  Zoltan2::printIntegralRangeList(std::cout, *a1);
  std::cout << std::endl;

  a1 = all.getPtr<rangeList_t>("memory_procs");
  std::cout << "memory_procs translation: ";
  Zoltan2::printIntegralRangeList(std::cout, *a1);
  std::cout << std::endl;

  // Print out all the documentation

  std::cout << std::endl;
  std::cout << "Parameter documentation:" << std::endl;
  Zoltan2::printListDocumentation(validParameters, std::cout, std::string()); 

  std::cout << "PASS"  << std::endl;
  return 0;
}
示例#29
0
    bool ClientInfo::getLastError( const BSONObj& options , BSONObjBuilder& result , bool fromWriteBackListener ) {
        set<string> * shards = getPrev();

        if ( shards->size() == 0 ) {
            result.appendNull( "err" );
            return true;
        }

        vector<WBInfo> writebacks;

        // handle single server
        if ( shards->size() == 1 ) {
            string theShard = *(shards->begin() );



            BSONObj res;
            bool ok = false;
            {
                ShardConnection conn( theShard , "" );
                try {
                    ok = conn->runCommand( "admin" , options , res );
                }
                catch( std::exception &e ) {

                    warning() << "could not get last error from shard " << theShard << causedBy( e ) << endl;

                    // Catch everything that happens here, since we need to ensure we return our connection when we're
                    // finished.
                    conn.done();

                    return false;
                }


                res = res.getOwned();
                conn.done();
            }

            _addWriteBack( writebacks , res );

            // hit other machines just to block
            for ( set<string>::const_iterator i=sinceLastGetError().begin(); i!=sinceLastGetError().end(); ++i ) {
                string temp = *i;
                if ( temp == theShard )
                    continue;

                try {
                    ShardConnection conn( temp , "" );
                    ON_BLOCK_EXIT_OBJ( conn, &ShardConnection::done );
                    _addWriteBack( writebacks , conn->getLastErrorDetailed() );

                }
                catch( std::exception &e ){
                    warning() << "could not clear last error from shard " << temp << causedBy( e ) << endl;
                }

            }
            clearSinceLastGetError();

            if ( writebacks.size() ){
                vector<BSONObj> v = _handleWriteBacks( writebacks , fromWriteBackListener );
                if ( v.size() == 0 && fromWriteBackListener ) {
                    // ok
                }
                else {
                    // this will usually be 1
                    // it can be greater than 1 if a write to a different shard
                    // than the last write op had a writeback
                    // all we're going to report is the first
                    // since that's the current write
                    // but we block for all
                    verify( v.size() >= 1 );
                    result.appendElements( v[0] );
                    result.appendElementsUnique( res );
                    result.append( "writebackGLE" , v[0] );
                    result.append( "initialGLEHost" , theShard );
                }
            }
            else {
                result.append( "singleShard" , theShard );
                result.appendElements( res );
            }

            return ok;
        }

        BSONArrayBuilder bbb( result.subarrayStart( "shards" ) );
        BSONObjBuilder shardRawGLE;

        long long n = 0;

        int updatedExistingStat = 0; // 0 is none, -1 has but false, 1 has true

        // hit each shard
        vector<string> errors;
        vector<BSONObj> errorObjects;
        for ( set<string>::iterator i = shards->begin(); i != shards->end(); i++ ) {
            string theShard = *i;
            bbb.append( theShard );
            boost::scoped_ptr<ShardConnection> conn;
            BSONObj res;
            bool ok = false;
            try {
                conn.reset( new ShardConnection( theShard , "" ) ); // constructor can throw if shard is down
                ok = (*conn)->runCommand( "admin" , options , res );
                shardRawGLE.append( theShard , res );
            }
            catch( std::exception &e ){

              // Safe to return here, since we haven't started any extra processing yet, just collecting
              // responses.

              warning() << "could not get last error from a shard " << theShard << causedBy( e ) << endl;
                conn->done();

                return false;
            }

            _addWriteBack( writebacks, res );

            string temp = DBClientWithCommands::getLastErrorString( res );
            if ( (*conn)->type() != ConnectionString::SYNC && ( ok == false || temp.size() ) ) {
                errors.push_back( temp );
                errorObjects.push_back( res );
            }

            n += res["n"].numberLong();
            if ( res["updatedExisting"].type() ) {
                if ( res["updatedExisting"].trueValue() )
                    updatedExistingStat = 1;
                else if ( updatedExistingStat == 0 )
                    updatedExistingStat = -1;
            }

            conn->done();
        }

        bbb.done();
        result.append( "shardRawGLE" , shardRawGLE.obj() );

        result.appendNumber( "n" , n );
        if ( updatedExistingStat )
            result.appendBool( "updatedExisting" , updatedExistingStat > 0 );

        // hit other machines just to block
        for ( set<string>::const_iterator i=sinceLastGetError().begin(); i!=sinceLastGetError().end(); ++i ) {
            string temp = *i;
            if ( shards->count( temp ) )
                continue;

            ShardConnection conn( temp , "" );
            try {
                _addWriteBack( writebacks, conn->getLastErrorDetailed() );
            }
            catch( std::exception &e ){
                warning() << "could not clear last error from a shard " << temp << causedBy( e ) << endl;
            }
            conn.done();
        }
        clearSinceLastGetError();

        if ( errors.size() == 0 ) {
            result.appendNull( "err" );
            _handleWriteBacks( writebacks , fromWriteBackListener );
            return true;
        }

        result.append( "err" , errors[0].c_str() );

        {
            // errs
            BSONArrayBuilder all( result.subarrayStart( "errs" ) );
            for ( unsigned i=0; i<errors.size(); i++ ) {
                all.append( errors[i].c_str() );
            }
            all.done();
        }

        {
            // errObjects
            BSONArrayBuilder all( result.subarrayStart( "errObjects" ) );
            for ( unsigned i=0; i<errorObjects.size(); i++ ) {
                all.append( errorObjects[i] );
            }
            all.done();
        }
        _handleWriteBacks( writebacks , fromWriteBackListener );
        return true;
    }
示例#30
0
//=============================================================================
// Function: BuildRemoteList
// Purpose: Append Network Neighborhood items to the list.
// Notes: - Mounted gets transalated into Connected.  FilteredAdd is told
//          to ignore the Mounted flag since we need to handle it in a weird
//          way manually.
//        - The resulting list is sorted alphabetically.
//=============================================================================
static bool BuildRemoteList(wxArrayString& list, NETRESOURCE* pResSrc,
                            unsigned flagsSet, unsigned flagsUnset)
{
    // NN query depends on dynamically loaded library.
    if (!s_pWNetOpenEnum || !s_pWNetEnumResource || !s_pWNetCloseEnum)
    {
        wxLogError(_("Failed to load mpr.dll."));
        return false;
    }

    // Don't waste time doing the work if the flags conflict.
    if (flagsSet & wxFS_VOL_MOUNTED && flagsUnset & wxFS_VOL_MOUNTED)
        return false;

    //----------------------------------------------
    // Generate the list according to the flags set.
    //----------------------------------------------
    BuildListFromNN(list, pResSrc, flagsSet, flagsUnset);
    list.Sort(CompareFcn);

    //-------------------------------------------------------------------------
    // If mounted only is requested, then we only need one simple pass.
    // Otherwise, we need to build a list of all NN volumes and then apply the
    // list of mounted drives to it.
    //-------------------------------------------------------------------------
    if (!(flagsSet & wxFS_VOL_MOUNTED))
    {
        // generate.
        wxArrayString mounted;
        BuildListFromNN(mounted, pResSrc, flagsSet | wxFS_VOL_MOUNTED, flagsUnset & ~wxFS_VOL_MOUNTED);
        mounted.Sort(CompareFcn);

        // apply list from bottom to top to preserve indexes if removing items.
        ssize_t iList = list.GetCount()-1;
        for (ssize_t iMounted = mounted.GetCount()-1; iMounted >= 0 && iList >= 0; iMounted--)
        {
            int compare;
            wxString all(list[iList]);
            wxString mount(mounted[iMounted]);

            while (compare =
                     wxStricmp(list[iList].c_str(), mounted[iMounted].c_str()),
                   compare > 0 && iList >= 0)
            {
                iList--;
                all = list[iList];
            }


            if (compare == 0)
            {
                // Found the element.  Remove it or mark it mounted.
                if (flagsUnset & wxFS_VOL_MOUNTED)
                    list.RemoveAt(iList);
                else
                    s_fileInfo[list[iList]].m_flags |= wxFS_VOL_MOUNTED;

            }

            iList--;
        }
    }

    return true;
} // BuildRemoteList