Exemplo n.º 1
0
int
run_main (int, ACE_TCHAR *[])
{
  ACE_START_TEST (ACE_TEXT ("Bound_Ptr_Test"));


  // =========================================================================
  // The following test uses the ACE_Strong_Bound_Ptr in a single
  // thread of control, hence we use the ACE_Null_Mutex

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%t) performing synchronous test...\n")));

  Parent *parent1 = 0;
  ACE_NEW_RETURN (parent1,
                  Parent,
                  -1);
  ACE_Weak_Bound_Ptr<Parent, ACE_Null_Mutex> p8;
  {
    // Must get the pointer from the parent object's weak_self_ member.
    ACE_Strong_Bound_Ptr<Parent, ACE_Null_Mutex> p(parent1->weak_self_);
    ACE_Strong_Bound_Ptr<Parent, ACE_Null_Mutex> p1(p);
    ACE_Strong_Bound_Ptr<Parent, ACE_Null_Mutex> p2(p);
    ACE_Weak_Bound_Ptr<Parent, ACE_Null_Mutex> p3(p);
    ACE_Strong_Bound_Ptr<Parent, ACE_Null_Mutex> p4(p);
    ACE_Strong_Bound_Ptr<Parent, ACE_Null_Mutex> p5 = p2;
    ACE_Strong_Bound_Ptr<Parent, ACE_Null_Mutex> p6 = p3;
    ACE_Weak_Bound_Ptr<Parent, ACE_Null_Mutex> p7(p1);
    p8 = p2;
    p->child_->do_something ();
  }
  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%t) Parent instance count is %d, expecting 0\n"),
              Parent::instance_count_));
  if (Parent::instance_count_ != 0)
    {
      ACE_ERROR_RETURN ((LM_ERROR,
                         ACE_TEXT ("(%t) parent instance count not 0...\n")),
                         -1);
    }
  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%t) Child instance count is %d, expecting 0\n"),
              Child::instance_count_));
  if (Child::instance_count_ != 0)
    {
      ACE_ERROR_RETURN ((LM_ERROR,
                         ACE_TEXT ("(%t) child instance count not 0...\n")),
                         -1);
    }
  // Weak pointer should now be set to null.
  if(!p8.null ())
    {
      ACE_ERROR_RETURN ((LM_ERROR,
                         ACE_TEXT ("(%t) p8 not nill...\n")),
                         -1);
    }

  Printer *printer1 = 0;
  ACE_NEW_RETURN (printer1,
                  Printer ("I am printer 1"),
                  -1);
  ACE_Weak_Bound_Ptr<Printer, ACE_Null_Mutex> r9;
  {
    ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r(printer1);
    ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r1(r);
    ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r2(r);
    ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r3(r);
    ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r4(r);
    ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r5 = r2;
    ACE_Strong_Bound_Ptr<Printer, ACE_Null_Mutex> r6 = r1;
    ACE_Weak_Bound_Ptr<Printer, ACE_Null_Mutex> r7(r1);
    ACE_Weak_Bound_Ptr<Printer, ACE_Null_Mutex> r8 = r2;
    r9 = r3;
    r9->print ();
  }
  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%t) Printer instance count is %d, expecting 0\n"),
              Printer::instance_count_));
  if (Printer::instance_count_ != 0)
    {
      ACE_ERROR_RETURN ((LM_ERROR,
                         ACE_TEXT ("(%t) Printer instance count not 0...\n")),
                         -1);
    }
  // Weak pointer should now be set to null.
  if (!r9.null ())
    {
      ACE_ERROR_RETURN ((LM_ERROR,
                         ACE_TEXT ("(%t) r9 not nill...\n")),
                         -1);
    }

#if defined (ACE_HAS_THREADS)

  // =========================================================================
  // The following test uses the ACE_Strong_Bound_Ptr in multiple
  // threads of control.

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%t) performing asynchronous test...\n")));

  Scheduler *scheduler_ptr = 0;

  // Create active objects..
  ACE_NEW_RETURN (scheduler_ptr,
                  Scheduler (),
                  -1);

  ACE_Strong_Bound_Ptr<Scheduler, ACE_Null_Mutex> scheduler(scheduler_ptr);

  if (scheduler->open () == -1)
    {
      ACE_ERROR_RETURN ((LM_ERROR,
                         ACE_TEXT ("(%t) Scheduler open failed...\n")),
                         -1);
    }

  {
    Printer *printer2 = 0;
    ACE_NEW_RETURN (printer2,
                    Printer ("I am printer 2"),
                    -1);

    // Ownership is transferred from the auto_ptr to the strong pointer.
    auto_ptr<Printer> a (printer2);
    Printer_var r (a);

    for (int i = 0; i < n_loops; i++)
      // Spawn off the methods, which run in a separate thread as
      // active object invocations.
      scheduler->print (r);
  }

  // Close things down.
  scheduler->end ();

  scheduler->wait ();

  ACE_DEBUG ((LM_DEBUG,
              ACE_TEXT ("(%t) Printer instance count is %d, expecting 0\n"),
              Printer::instance_count_));
  if (Printer::instance_count_ != 0)
    return -1;

#endif /* ACE_HAS_THREADS */
  ACE_END_TEST;

  return 0;
}
Exemplo n.º 2
0
int
test_main(int,char*[])
{
  typedef boost::detail::multi_array::index_range<int,std::size_t> range;

  {
    // typical range creation and extraction
    range r1(-3,5);
    BOOST_CHECK(r1.start() == -3);
    BOOST_CHECK(r1.finish() == 5);
    BOOST_CHECK(r1.stride() == 1);
    BOOST_CHECK(!r1.is_degenerate());
    BOOST_CHECK(r1.get_start(0) == -3);
    BOOST_CHECK(r1.get_finish(100) == 5);
  }

  {
    range r2(-3,5,2);
    BOOST_CHECK(r2.start() == -3);
    BOOST_CHECK(r2.finish() == 5);
    BOOST_CHECK(r2.stride() == 2);
    BOOST_CHECK(!r2.is_degenerate());
  }

  {
    // degenerate creation
    range r3(5);
    BOOST_CHECK(r3.start() == 5);
    BOOST_CHECK(r3.finish() == 6);
    BOOST_CHECK(r3.stride() == 1);
    BOOST_CHECK(r3.is_degenerate());
  }

  {
    // default range creation
    range r4;
    BOOST_CHECK(r4.get_start(0) == 0);
    BOOST_CHECK(r4.get_finish(100) == 100);
    BOOST_CHECK(r4.stride() == 1);
  }

  {
    // create a range using the setter methods
    range r5 = range().stride(2).start(-3).finish(7);
    BOOST_CHECK(r5.start() == -3);
    BOOST_CHECK(r5.stride() == 2);
    BOOST_CHECK(r5.finish() == 7);
  }

  // try out all the comparison operators
  {
    range r6 = -3 <= range().stride(2) < 7;
    BOOST_CHECK(r6.start() == -3);
    BOOST_CHECK(r6.stride() == 2);
    BOOST_CHECK(r6.finish() == 7);
  }

  {
    range r7 = -3 < range() <= 7;
    BOOST_CHECK(r7.start() == -2);
    BOOST_CHECK(r7.stride() == 1);
    BOOST_CHECK(r7.finish() == 8);
  }

  // arithmetic operators
  {
    range r8 = range(0,5) + 2;
    BOOST_CHECK(r8.start() == 2);
    BOOST_CHECK(r8.stride() == 1);
    BOOST_CHECK(r8.finish() == 7);
  }

  {
    range r9 = range(0,5) - 2;
    BOOST_CHECK(r9.start() == -2);
    BOOST_CHECK(r9.stride() == 1);
    BOOST_CHECK(r9.finish() == 3);
  }
#ifdef __SYMBIAN32__
if(boost::minimal_test::errors_counter() != 0)
   assert_failed = true;
   	testResultXml("range1");
	close_log_file();
#endif

  return boost::exit_success;
}
Exemplo n.º 3
0
int main (int arg, char** argv) {
  Ram<uint64_t> r(ADDR_ROW_WIDTH, ADDR_COL_WIDTH, ADDR_BANK_WIDTH,
              SYSTEM_CLK_FREQ, MEM_CLK_FREQ,
              TRCD, TCL, TRP);
  
  // Check initial states
  assert(r.read_ready() == false);
  
  // Fill RAM with data
  for (unsigned int i = 0; i < pow(2, ADDRESS_WIDTH); i++) {
    r.WriteRequest(i, i);
    r.NextClockCycle();
  }    
  for (unsigned int i = 0; i < (TRCD+TCL+TRP)*pow(2, ADDRESS_WIDTH)*10; i++) {
    r.NextClockCycle();
  }
  
  // Full read test interleaving bank requests
  int start_cycle = r.cycle_count();
  assert(r.read_ready() == false);
  for (int row = 0; row < pow(2, ADDR_ROW_WIDTH); row++) {
    for (int col = 0; col < pow(2, ADDR_COL_WIDTH); col++) {
      for (int bank = 0; bank < pow(2, ADDR_BANK_WIDTH); bank++) {
        uint64_t address = (bank << (ADDR_ROW_WIDTH+ADDR_COL_WIDTH)) | (row << (ADDR_COL_WIDTH)) | col;
        r.ReadRequest(address);
        do {
          r.NextClockCycle();          
        } while (r.read_ready() == false);
        assert(r.read_data() == address);
      }
    }  
  }
  std::cout << "Full read test (" << pow(2, ADDRESS_WIDTH) << " reads) took " << r.cycle_count() - start_cycle << " cycles" << std::endl;
  
  //same row, same bank
  r.Reset();
  start_cycle = r.cycle_count();
  r.ReadRequest(0);
  r.NextClockCycle();    
  r.ReadRequest(1);  
  r.NextClockCycle();    
  r.ReadRequest(2);  
  do {
    r.NextClockCycle();          
  } while (r.read_ready() == false);

  assert (r.cycle_count() - start_cycle == TRCD + TCL + TRP+1); //off by 1 to start pipeline to clock into fifo
  start_cycle = r.cycle_count();
  do {
    r.NextClockCycle();          
  } while (r.read_ready() == false);

  assert (r.cycle_count() - start_cycle == Ram<int>::BURST_LENGTH/2);
  start_cycle = r.cycle_count();
  do {
    r.NextClockCycle();          
  } while (r.read_ready() == false);

  assert (r.cycle_count() - start_cycle == Ram<int>::BURST_LENGTH/2);
  
  //different row, same bank
  r.Reset();
  start_cycle = r.cycle_count();
  r.ReadRequest(0);
  r.NextClockCycle();    
  r.ReadRequest((int)pow(2,ADDR_COL_WIDTH));  
  r.NextClockCycle();    
  r.ReadRequest((int)pow(2,ADDR_COL_WIDTH)*2);  
  do {
    r.NextClockCycle();          
  } while (r.read_ready() == false);

  assert (r.cycle_count() - start_cycle == TRCD + TCL + TRP+1); //off by 1 to start pipeline to clock into fifo
  start_cycle = r.cycle_count();
  do {
    r.NextClockCycle();          
  } while (r.read_ready() == false);

  assert (r.cycle_count() - start_cycle == TRCD + TCL + TRP);
  start_cycle = r.cycle_count();
  do {
    r.NextClockCycle();          
  } while (r.read_ready() == false);

  assert (r.cycle_count() - start_cycle == TRCD + TCL + TRP);
  
  //different bank, same row, separated by different bank read
  r.Reset();
  start_cycle = r.cycle_count();
  r.ReadRequest(0);
  r.NextClockCycle();    
  r.ReadRequest((int)pow(2,ADDR_COL_WIDTH+ADDR_ROW_WIDTH));  
  r.NextClockCycle();    
  r.ReadRequest(1);  
  r.NextClockCycle();    
  r.ReadRequest((int)pow(2,ADDR_COL_WIDTH+ADDR_ROW_WIDTH)+1);  
  do {
    r.NextClockCycle();          
  } while (r.read_ready() == false);

  assert (r.cycle_count() - start_cycle == TRCD + TCL + TRP+1); //off by 1 to start pipeline to clock into fifo
  start_cycle = r.cycle_count();
  do {
    r.NextClockCycle();          
  } while (r.read_ready() == false);

  assert (r.cycle_count() - start_cycle == Ram<int>::BURST_LENGTH/2); //check for burst rate limiting
  start_cycle = r.cycle_count();
  do {
    r.NextClockCycle();          
  } while (r.read_ready() == false);

  assert (r.cycle_count() - start_cycle == Ram<int>::BURST_LENGTH/2); 
  start_cycle = r.cycle_count();
  do {
    r.NextClockCycle();          
  } while (r.read_ready() == false);

  assert (r.cycle_count() - start_cycle == Ram<int>::BURST_LENGTH/2);

  //different bank, same row, separated by different bank read
  r.Reset();
  start_cycle = r.cycle_count();
  r.ReadRequest(0);
  r.NextClockCycle();    
  r.ReadRequest((int)pow(2,ADDR_COL_WIDTH+ADDR_ROW_WIDTH));  
  r.NextClockCycle();    
  r.ReadRequest(pow(2,ADDR_COL_WIDTH));  
  r.NextClockCycle();    
  r.ReadRequest((int)pow(2,ADDR_COL_WIDTH+ADDR_ROW_WIDTH)+pow(2,ADDR_COL_WIDTH));  
  do {
    r.NextClockCycle();          
  } while (r.read_ready() == false);

  assert (r.cycle_count() - start_cycle == TRCD + TCL + TRP+1); //off by 1 to start pipeline to clock into fifo
  start_cycle = r.cycle_count();
  do {
    r.NextClockCycle();          
  } while (r.read_ready() == false);

  assert (r.cycle_count() - start_cycle == Ram<int>::BURST_LENGTH/2); //check for burst rate limiting
  start_cycle = r.cycle_count();
  do {
    r.NextClockCycle();          
  } while (r.read_ready() == false);

  assert (r.cycle_count() - start_cycle == TRCD + TCL + TRP - Ram<int>::BURST_LENGTH/2); 
  start_cycle = r.cycle_count();
  do {
    r.NextClockCycle();          
  } while (r.read_ready() == false);

  assert (r.cycle_count() - start_cycle == Ram<int>::BURST_LENGTH/2);
  
  //bank 0, bank 1, bank 2, bank 0
  r.Reset();
  start_cycle = r.cycle_count();
  r.ReadRequest(0);
  r.NextClockCycle();    
  r.ReadRequest((int)pow(2,ADDR_COL_WIDTH+ADDR_ROW_WIDTH));  
  r.NextClockCycle();    
  r.ReadRequest((int)pow(2,ADDR_COL_WIDTH+ADDR_ROW_WIDTH)*2);  
  r.NextClockCycle();    
  r.ReadRequest((int)pow(2,ADDR_COL_WIDTH));  
  do {
    r.NextClockCycle();          
  } while (r.read_ready() == false);

  assert (r.cycle_count() - start_cycle == TRCD + TCL + TRP+1); //off by 1 to start pipeline to clock into fifo
  start_cycle = r.cycle_count();
  do {
    r.NextClockCycle();          
  } while (r.read_ready() == false);

  assert (r.cycle_count() - start_cycle == Ram<int>::BURST_LENGTH/2); //check for burst rate limiting
  start_cycle = r.cycle_count();
  do {
    r.NextClockCycle();          
  } while (r.read_ready() == false);

  assert (r.cycle_count() - start_cycle == Ram<int>::BURST_LENGTH/2); 
  start_cycle = r.cycle_count();
  do {
    r.NextClockCycle();          
  } while (r.read_ready() == false);

  uint64_t expected = Ram<uint64_t>::BURST_LENGTH/2;
  uint64_t expected1 = TRCD + TCL + TRP - Ram<uint64_t>::BURST_LENGTH/2*2;
  if ( expected1 > Ram<uint64_t>::BURST_LENGTH/2) {
    expected = expected1;
  }
  assert (r.cycle_count() - start_cycle == expected);


  // halving system clock frequency

  Ram<uint64_t> r2(ADDR_ROW_WIDTH, ADDR_COL_WIDTH, ADDR_BANK_WIDTH,
              SYSTEM_CLK_FREQ/2, MEM_CLK_FREQ,
              TRCD, TCL, TRP);
  
  // Check initial states
  assert(r2.read_ready() == false);
  
  // Read after Write Test
  for (unsigned int i = 0; i < pow(2, ADDRESS_WIDTH); i++) {
    r2.WriteRequest(i, i);
    r2.NextClockCycle();
  }    
  for (unsigned int i = 0; i < (TRCD+TCL+TRP)*pow(2, ADDRESS_WIDTH)*10; i++) {
    r2.NextClockCycle();
  }
  start_cycle = r2.cycle_count();
  assert(r2.read_ready() == false);
  for (int col = 0; col < pow(2, ADDR_COL_WIDTH); col++) {
    for (int row = 0; row < pow(2, ADDR_ROW_WIDTH); row++) {
      for (int bank = 0; bank < pow(2, ADDR_BANK_WIDTH); bank++) {
        uint64_t address = (bank << (ADDR_ROW_WIDTH+ADDR_COL_WIDTH)) | (row << (ADDR_COL_WIDTH)) | col;
        r2.ReadRequest(address);
        do {
          r2.NextClockCycle();          
        } while (r2.read_ready() == false);
        assert(r2.read_data() == address);
      }
    }  
  }
  
  //same row, same bank
  r2.Reset();
  start_cycle = r2.cycle_count();
  r2.ReadRequest(0);
  r2.NextClockCycle();    
  r2.ReadRequest(1);  
  r2.NextClockCycle();    
  r2.ReadRequest(2);  
  do {
    r2.NextClockCycle();          
  } while (r2.read_ready() == false);

  assert (r2.cycle_count() - start_cycle == (TRCD + TCL + TRP)/2+1); //off by 1 to start pipeline to clock into fifo
  start_cycle = r2.cycle_count();
  do {
    r2.NextClockCycle();          
  } while (r2.read_ready() == false);

  assert (r2.cycle_count() - start_cycle == Ram<int>::BURST_LENGTH/4);
  start_cycle = r2.cycle_count();
  do {
    r2.NextClockCycle();          
  } while (r2.read_ready() == false);

  assert (r2.cycle_count() - start_cycle == Ram<int>::BURST_LENGTH/4);
  
  //different row, same bank
  r2.Reset();
  start_cycle = r2.cycle_count();
  r2.ReadRequest(0);
  r2.NextClockCycle();    
  r2.ReadRequest((int)pow(2,ADDR_COL_WIDTH));  
  r2.NextClockCycle();    
  r2.ReadRequest((int)pow(2,ADDR_COL_WIDTH)*2);  
  do {
    r2.NextClockCycle();          
  } while (r2.read_ready() == false);

  assert (r2.cycle_count() - start_cycle == (TRCD + TCL + TRP)/2+1); //off by 1 to start pipeline to clock into fifo
  start_cycle = r2.cycle_count();
  do {
    r2.NextClockCycle();          
  } while (r2.read_ready() == false);

  assert (r2.cycle_count() - start_cycle == (TRCD + TCL + TRP)/2);
  start_cycle = r2.cycle_count();
  do {
    r2.NextClockCycle();          
  } while (r2.read_ready() == false);

  assert (r2.cycle_count() - start_cycle == (TRCD + TCL + TRP)/2);
  
  //different bank, same row, separated by different bank read
  r2.Reset();
  start_cycle = r2.cycle_count();
  r2.ReadRequest(0);
  r2.NextClockCycle();    
  r2.ReadRequest((int)pow(2,ADDR_COL_WIDTH+ADDR_ROW_WIDTH));  
  r2.NextClockCycle();    
  r2.ReadRequest(1);  
  r2.NextClockCycle();    
  r2.ReadRequest((int)pow(2,ADDR_COL_WIDTH+ADDR_ROW_WIDTH)+1);  
  do {
    r2.NextClockCycle();          
  } while (r2.read_ready() == false);

  assert (r2.cycle_count() - start_cycle == (TRCD + TCL + TRP)/2+1); //off by 1 to start pipeline to clock into fifo
  start_cycle = r2.cycle_count();
  do {
    r2.NextClockCycle();          
  } while (r2.read_ready() == false);

  assert (r2.cycle_count() - start_cycle == Ram<int>::BURST_LENGTH/4); //check for burst rate limiting
  start_cycle = r2.cycle_count();
  do {
    r2.NextClockCycle();          
  } while (r2.read_ready() == false);

  assert (r2.cycle_count() - start_cycle == Ram<int>::BURST_LENGTH/4); 
  start_cycle = r2.cycle_count();
  do {
    r2.NextClockCycle();          
  } while (r2.read_ready() == false);

  assert (r2.cycle_count() - start_cycle == Ram<int>::BURST_LENGTH/4);

  //different bank, same row, separated by different bank read
  r2.Reset();
  start_cycle = r2.cycle_count();
  r2.ReadRequest(0);
  r2.NextClockCycle();    
  r2.ReadRequest((int)pow(2,ADDR_COL_WIDTH+ADDR_ROW_WIDTH));  
  r2.NextClockCycle();    
  r2.ReadRequest(pow(2,ADDR_COL_WIDTH));  
  r2.NextClockCycle();    
  r2.ReadRequest((int)pow(2,ADDR_COL_WIDTH+ADDR_ROW_WIDTH)+pow(2,ADDR_COL_WIDTH));  
  do {
    r2.NextClockCycle();          
  } while (r2.read_ready() == false);

  assert (r2.cycle_count() - start_cycle == (TRCD + TCL + TRP)/2+1); //off by 1 to start pipeline to clock into fifo
  start_cycle = r2.cycle_count();
  do {
    r2.NextClockCycle();          
  } while (r2.read_ready() == false);

  assert (r2.cycle_count() - start_cycle == Ram<int>::BURST_LENGTH/4); //check for burst rate limiting
  start_cycle = r2.cycle_count();
  do {
    r2.NextClockCycle();          
  } while (r2.read_ready() == false);

  assert (r2.cycle_count() - start_cycle == (TRCD + TCL + TRP - Ram<int>::BURST_LENGTH/2)/2); 
  start_cycle = r2.cycle_count();
  do {
    r2.NextClockCycle();          
  } while (r2.read_ready() == false);

  assert (r2.cycle_count() - start_cycle == Ram<int>::BURST_LENGTH/4);
  
  //bank 0, bank 1, bank 2, bank 0
  r2.Reset();
  start_cycle = r2.cycle_count();
  r2.ReadRequest(0);
  r2.NextClockCycle();    
  r2.ReadRequest((int)pow(2,ADDR_COL_WIDTH+ADDR_ROW_WIDTH));  
  r2.NextClockCycle();    
  r2.ReadRequest((int)pow(2,ADDR_COL_WIDTH+ADDR_ROW_WIDTH)*2);  
  r2.NextClockCycle();    
  r2.ReadRequest((int)pow(2,ADDR_COL_WIDTH));  
  do {
    r2.NextClockCycle();          
  } while (r2.read_ready() == false);

  assert (r2.cycle_count() - start_cycle == (TRCD + TCL + TRP)/2+1); //off by 1 to start pipeline to clock into fifo
  start_cycle = r2.cycle_count();
  do {
    r2.NextClockCycle();          
  } while (r2.read_ready() == false);

  assert (r2.cycle_count() - start_cycle == Ram<int>::BURST_LENGTH/4); //check for burst rate limiting
  start_cycle = r2.cycle_count();
  do {
    r2.NextClockCycle();          
  } while (r2.read_ready() == false);

  assert (r2.cycle_count() - start_cycle == Ram<int>::BURST_LENGTH/4); 
  start_cycle = r2.cycle_count();
  do {
    r2.NextClockCycle();          
  } while (r2.read_ready() == false);

  expected = Ram<int>::BURST_LENGTH/4;
  expected1 = (TRCD + TCL + TRP)/2 - Ram<int>::BURST_LENGTH/4*2;
  if ( expected1 > Ram<int>::BURST_LENGTH/4) {
    expected = expected1;
  }
  assert (r2.cycle_count() - start_cycle == expected);
  
  std::cout << "RAM test complete!" << std::endl;
}
void calibrate(const std::vector<TiePoint>& tiePoints,const int gridSize[2],const double tileSize[2],const unsigned int depthFrameSize[2],const unsigned int colorFrameSize[2])
{
    /* Initialize the depth camera's intrinsic parameter matrix: */
    Math::Matrix depthV(6,6,0.0);

    /* Process all tie points: */
    for(std::vector<TiePoint>::const_iterator tpIt=tiePoints.begin(); tpIt!=tiePoints.end(); ++tpIt)
    {
        /* Enter the tie point's depth homography into the intrinsic parameter matrix: */
        Homography::Matrix hm(1.0);
        hm(0,2)=double(depthFrameSize[0]);
        hm*=tpIt->depthHom.getMatrix();
        Homography::Matrix scale(1.0);
        scale(0,0)=1.0/tileSize[0];
        scale(1,1)=1.0/tileSize[1];
        hm*=scale;
        double row[3][6];
        static const int is[3]= {0,0,1};
        static const int js[3]= {1,0,1};
        for(int r=0; r<3; ++r)
        {
            int i=is[r];
            int j=js[r];
            row[r][0]=hm(0,i)*hm(0,j);
            row[r][1]=hm(0,i)*hm(1,j)+hm(1,i)*hm(0,j);
            row[r][2]=hm(0,i)*hm(2,j)+hm(2,i)*hm(0,j);
            row[r][3]=hm(1,i)*hm(1,j);
            row[r][4]=hm(1,i)*hm(2,j)+hm(2,i)*hm(1,j);
            row[r][5]=hm(2,i)*hm(2,j);
        }
        for(int i=0; i<6; ++i)
            row[1][i]-=row[2][i];
        for(int r=0; r<2; ++r)
        {
            for(unsigned int i=0; i<6; ++i)
                for(unsigned int j=0; j<6; ++j)
                    depthV(i,j)+=row[r][i]*row[r][j];
        }
    }

    /* Find the intrinsic parameter linear system's smallest eigenvalue: */
    std::pair<Math::Matrix,Math::Matrix> depthQe=depthV.jacobiIteration();
    unsigned int minEIndex=0;
    double minE=Math::abs(depthQe.second(0));
    for(unsigned int i=1; i<6; ++i)
    {
        if(minE>Math::abs(depthQe.second(i)))
        {
            minEIndex=i;
            minE=Math::abs(depthQe.second(i));
        }
    }
    std::cout<<"Smallest eigenvalue of v = "<<depthQe.second(minEIndex)<<std::endl;

    /* Calculate the intrinsic parameters: */
    Math::Matrix b=depthQe.first.getColumn(minEIndex);
    std::cout<<b(0)<<", "<<b(1)<<", "<<b(2)<<", "<<b(3)<<", "<<b(4)<<", "<<b(5)<<std::endl;
    double v0=(b(1)*b(2)-b(0)*b(4))/(b(0)*b(3)-Math::sqr(b(1)));
    double lambda=b(5)-(Math::sqr(b(2))+v0*(b(1)*b(2)-b(0)*b(4)))/b(0);
    double alpha=Math::sqrt(lambda/b(0));
    double beta=Math::sqrt(lambda*b(0)/(b(0)*b(3)-Math::sqr(b(1))));
    double gamma=-b(1)*Math::sqr(alpha)*beta/lambda;
    double u0=gamma*v0/beta-b(2)*Math::sqr(alpha)/lambda;

    std::cout<<"Intrinsic camera parameters:"<<std::endl;
    std::cout<<alpha<<" "<<gamma<<" "<<u0<<std::endl;
    std::cout<<0.0<<" "<<beta<<" "<<v0<<std::endl;
    std::cout<<0.0<<" "<<0.0<<" "<<1.0<<std::endl;

    /* Create the intrinsic camera parameter matrix: */
    Math::Matrix a(3,3,1.0);
    a.set(0,0,alpha);
    a.set(0,1,gamma);
    a.set(0,2,u0);
    a.set(1,1,beta);
    a.set(1,2,v0);
    Math::Matrix aInv=a.inverse();

    /* Calculate extrinsic parameters for each tie point to get measurements for the depth formula regression: */
    Math::Matrix depthAta(2,2,0.0);
    Math::Matrix depthAtb(2,1,0.0);
    for(std::vector<TiePoint>::const_iterator tpIt=tiePoints.begin(); tpIt!=tiePoints.end(); ++tpIt)
    {
        /* Convert the tie point's depth homography to a matrix: */
        Homography::Matrix hm(1.0);
        hm(0,2)=double(depthFrameSize[0]);
        hm*=tpIt->depthHom.getMatrix();
        Homography::Matrix scale(1.0);
        scale(0,0)=1.0/tileSize[0];
        scale(1,1)=1.0/tileSize[1];
        hm*=scale;
        Math::Matrix h(3,3);
        for(unsigned int i=0; i<3; ++i)
            for(unsigned int j=0; j<3; ++j)
                h(i,j)=hm(i,j);

        /* Calculate the extrinsic parameters: */
        double lambda=0.5/(aInv*h.getColumn(0)).mag()+0.5/(aInv*h.getColumn(1)).mag();
        Math::Matrix r1=lambda*aInv*h.getColumn(0);
        Math::Matrix r2=lambda*aInv*h.getColumn(1);
        Math::Matrix r3(3,1);
        for(unsigned int i=0; i<3; ++i)
            r3.set(i,r1((i+1)%3)*r2((i+2)%3)-r1((i+2)%3)*r2((i+1)%3)); // 'Tis a cross product, in case you're wondering
        Math::Matrix t=lambda*aInv*h.getColumn(2);

        /* Create the extrinsic parameter matrix: */
        Math::Matrix rt(3,4);
        rt.setColumn(0,r1);
        rt.setColumn(1,r2);
        rt.setColumn(2,r3);
        rt.setColumn(3,t);

        Math::Matrix wgc(4,1);
        wgc(0)=tileSize[0]*double(gridSize[0])*0.5;
        wgc(1)=tileSize[1]*double(gridSize[1])*0.5;
        wgc(2)=0.0;
        wgc(3)=1.0;
        Math::Matrix cgc=rt*wgc;
        if(cgc(2)<0.0)
        {
            /* Flip the extrinsic matrix to move the grid to positive z: */
            Math::Matrix flip(3,3,-1.0);
            rt=flip*rt;
            cgc=rt*wgc;
        }
        std::cout<<"Grid center: "<<cgc(0)<<", "<<cgc(1)<<", "<<cgc(2)<<std::endl;

        /* Transform all world grid points with the extrinsic matrix to get their camera-space z values: */
        for(int y=0; y<gridSize[1]; ++y)
            for(int x=0; x<gridSize[0]; ++x)
            {
                /* Create the world point: */
                Math::Matrix wp(4,1);
                wp(0)=tileSize[0]*double(x);
                wp(1)=tileSize[1]*double(y);
                wp(2)=0.0;
                wp(3)=1.0;

                /* Transform the world point to camera space: */
                Math::Matrix cp=rt*wp;
                double dist=cp(2);

                /* Get the depth frame value from the grid's plane in depth image space: */
                Point dip=tpIt->depthHom.transform(Point(x,y));
                const Plane::Vector& n=tpIt->gridPlane.getNormal();
                double o=tpIt->gridPlane.getOffset();
                double depth=(o-dip[0]*n[0]-dip[1]*n[1])/n[2];

                /* Enter the depth / z pair into the depth formula accumulator: */
                depthAta(0,0)+=1.0;
                depthAta(0,1)+=-dist;
                depthAta(1,0)+=-dist;
                depthAta(1,1)+=dist*dist;
                depthAtb(0)+=-dist*depth;
                depthAtb(1)+=dist*dist*depth;
            }
    }

    /* Solve the depth formula least-squares system: */
    Math::Matrix depthX=depthAtb.divideFullPivot(depthAta);
    std::cout<<"Depth conversion formula: dist = "<<depthX(0)<<" / ("<<depthX(1)<<" - depth)"<<std::endl;

    /* Calculate the full depth unprojection matrix: */
    Math::Matrix depthProj(4,4,0.0);
    depthProj(0,0)=1.0/alpha;
    depthProj(0,1)=-gamma/(alpha*beta);
    depthProj(0,3)=-u0/alpha+v0*gamma/(alpha*beta);
    depthProj(1,1)=1.0/beta;
    depthProj(1,3)=-v0/beta;
    depthProj(2,3)=-1.0;
    depthProj(3,2)=-1.0/depthX(0);
    depthProj(3,3)=depthX(1)/depthX(0);

    Math::Matrix colorAta(12,12,0.0);
    for(std::vector<TiePoint>::const_iterator tpIt=tiePoints.begin(); tpIt!=tiePoints.end(); ++tpIt)
    {
        for(int y=0; y<gridSize[1]; ++y)
            for(int x=0; x<gridSize[0]; ++x)
            {
                /* Enter the tie point into the color calibration matrix linear system: */
                Point dip=tpIt->depthHom.transform(Point(x,y));
                const Plane::Vector& n=tpIt->gridPlane.getNormal();
                double o=tpIt->gridPlane.getOffset();
                double depth=(o-dip[0]*n[0]-dip[1]*n[1])/n[2];
                Math::Matrix dwp(4,1);
                dwp(0)=dip[0]+double(depthFrameSize[0]);
                dwp(1)=dip[1];
                dwp(2)=depth;
                dwp(3)=1.0;
                dwp=depthProj*dwp;
                for(int i=0; i<3; ++i)
                    dwp(i)/=dwp(3);
                Point cip=tpIt->colorHom.transform(Point(x,y));
                cip[0]/=double(colorFrameSize[0]);
                cip[1]/=double(colorFrameSize[1]);

                double eq[2][12];
                eq[0][0]=dwp(0);
                eq[0][1]=dwp(1);
                eq[0][2]=dwp(2);
                eq[0][3]=1.0;
                eq[0][4]=0.0;
                eq[0][5]=0.0;
                eq[0][6]=0.0;
                eq[0][7]=0.0;
                eq[0][8]=-cip[0]*dwp(0);
                eq[0][9]=-cip[0]*dwp(1);
                eq[0][10]=-cip[0]*dwp(2);
                eq[0][11]=-cip[0];

                eq[1][0]=0.0;
                eq[1][1]=0.0;
                eq[1][2]=0.0;
                eq[1][3]=0.0;
                eq[1][4]=dwp(0);
                eq[1][5]=dwp(1);
                eq[1][6]=dwp(2);
                eq[1][7]=1.0;
                eq[1][8]=-cip[1]*dwp(0);
                eq[1][9]=-cip[1]*dwp(1);
                eq[1][10]=-cip[1]*dwp(2);
                eq[1][11]=-cip[1];

                for(int row=0; row<2; ++row)
                {
                    for(unsigned int i=0; i<12; ++i)
                        for(unsigned int j=0; j<12; ++j)
                            colorAta(i,j)+=eq[row][i]*eq[row][j];
                }
            }
    }

    /* Find the color calibration system's smallest eigenvalue: */
    std::pair<Math::Matrix,Math::Matrix> colorQe=colorAta.jacobiIteration();
    minEIndex=0;
    minE=Math::abs(colorQe.second(0,0));
    for(unsigned int i=1; i<12; ++i)
    {
        if(minE>Math::abs(colorQe.second(i,0)))
        {
            minEIndex=i;
            minE=Math::abs(colorQe.second(i,0));
        }
    }

    /* Create the normalized color homography: */
    Math::Matrix colorHom(3,4);
    double scale=colorQe.first(11,minEIndex);
    for(int i=0; i<3; ++i)
        for(int j=0; j<4; ++j)
            colorHom(i,j)=colorQe.first(i*4+j,minEIndex)/scale;

    /* Create the full color unprojection matrix by extending the homography: */
    Math::Matrix colorProj(4,4);
    for(unsigned int i=0; i<2; ++i)
        for(unsigned int j=0; j<4; ++j)
            colorProj(i,j)=colorHom(i,j);
    for(unsigned int j=0; j<4; ++j)
        colorProj(2,j)=j==2?1.0:0.0;
    for(unsigned int j=0; j<4; ++j)
        colorProj(3,j)=colorHom(2,j);

    /* Modify the color unprojection matrix by the depth projection matrix: */
    colorProj*=depthProj;

    /* Write the calibration file: */
    IO::FilePtr calibFile(IO::openFile("CameraCalibrationMatrices.dat",IO::File::WriteOnly));
    calibFile->setEndianness(Misc::LittleEndian);
    for(int i=0; i<4; ++i)
        for(int j=0; j<4; ++j)
            calibFile->write<double>(depthProj(i,j));
    for(int i=0; i<4; ++i)
        for(int j=0; j<4; ++j)
            calibFile->write<double>(colorProj(i,j));
}
Exemplo n.º 5
0
void MainGame::initBalls() {

	// Initializes the grid
	_grid = std::make_unique<Grid>(m_screenWidth, m_screenHeight, CELL_SIZE);
	

#define ADD_BALL(p, ...) \
    totalProbability += p; \
    possibleBalls.emplace_back(__VA_ARGS__);

    // Number of balls to spawn
    const int NUM_BALLS = 5000;

    // Random engine stuff
    std::mt19937 randomEngine((unsigned int)time(nullptr));
    std::uniform_real_distribution<float> randX(0.0f, (float)m_screenWidth);
    std::uniform_real_distribution<float> randY(0.0f, (float)m_screenHeight);
    std::uniform_real_distribution<float> randDir(-1.0f, 1.0f);

    // Add all possible balls
    std::vector <BallSpawn> possibleBalls;
    float totalProbability = 0.0f;

	std::uniform_real_distribution<float> r1(2.0f, 6.0f);
	std::uniform_int_distribution<int> r2(0, 255);

    // Adds the balls using a macro
    ADD_BALL(20.0f, Engine::Color(255, 255, 255, 255),
             2.0f, 1.0f, 0.1f, 7.0f, totalProbability);
    ADD_BALL(10.0f, Engine::Color(0, 0, 255, 255),
             3.0f, 2.0f, 0.1f, 3.0f, totalProbability);
	ADD_BALL(1.0f, Engine::Color(255, 0, 0, 255),
			5.0f, 4.0f, 0.0f, 0.0f, totalProbability);
	for (int i = 0; i < 10000; i++){
		ADD_BALL(1.0f, Engine::Color(r2(randomEngine), r2(randomEngine), r2(randomEngine), 255), r1(randomEngine), r1(randomEngine), 0.0f, 0.0f, totalProbability);
	}

    // Random probability for ball spawn
    std::uniform_real_distribution<float> spawn(0.0f, totalProbability);

    // Small optimization that sets the size of the internal array to prevent
    // extra allocations.
    m_balls.reserve(NUM_BALLS);

    // Set up ball to spawn with default value
    BallSpawn* ballToSpawn = &possibleBalls[0];
    for (int i = 0; i < NUM_BALLS; i++) {
        // Get the ball spawn roll
        float spawnVal = spawn(randomEngine);
        // Figure out which ball we picked
        for (size_t j = 0; j < possibleBalls.size(); j++) {
            if (spawnVal <= possibleBalls[j].probability) {
                ballToSpawn = &possibleBalls[j];
                break;
            }
        }

        // Get random starting position
        glm::vec2 pos(randX(randomEngine), randY(randomEngine));

        // Hacky way to get a random direction
        glm::vec2 direction(randDir(randomEngine), randDir(randomEngine));
        if (direction.x != 0.0f || direction.y != 0.0f) { // The chances of direction == 0 are astronomically low
            direction = glm::normalize(direction);
        } else {
            direction = glm::vec2(1.0f, 0.0f); // default direction
        }

        // Add ball
        m_balls.emplace_back(ballToSpawn->radius, ballToSpawn->mass, pos, direction * ballToSpawn->randSpeed(randomEngine),
                             Engine::ResourceManager::getTexture("Textures/circle.png").id,
                             ballToSpawn->color);
		// Add the ball to the grid.
		_grid->addBall(&m_balls.back());
    }
}
Exemplo n.º 6
0
//! Basic usage (simple creation of tracking pointers and destruction of them vs destruction of their targets)
void basic_example() {
	// Create two instances of class C (their lifetime is managed by unique_ptr), name them i1 and i2
	std::unique_ptr<C> i1(new C(1));
	std::unique_ptr<C> i2(new C(2));

	// Create tracking pointer to i1, pass it an "invalidation function" to be called when the instance gets destructed
	tracking_ptr<C> r1_1(*i1, [](tracking_ptr<C>& /*dummy*/){std::cout << "! r1_1: i1 invalidated" << std::endl;});
	
	// Use the pointer to work with the pointed-to instance
	r1_1->print();
	
	// Create another tracking pointer to i1 (the count of tracking pointers is not limited)
	tracking_ptr<C> r1_2(*i1, [](tracking_ptr<C>& /*dummy*/){std::cout << "! r1_2: i1 invalidated" << std::endl;});
	
	// Create a tracking pointer to i2
	tracking_ptr<C> r2(*i2, [](tracking_ptr<C>& /*dummy*/){std::cout << "! r2: i2 invalidated" << std::endl;});
	
	// Work with the pointers "directly"...
	r1_1->print();
	r1_2->print();
	r2->print();
	
	// ... get the raw pointer and work with that instead ...
	{
		C * cp = r2.get();
		cp->print();
	}
	
	// ... or dereference the pointer to get reference to the instance
	(*r2).print();
	
	// Let's kill i1
	// While it gets destroyed, it invalidates all tracking pointers pointing at it
	std::cout << "killing i1" << std::endl;
	i1.reset();
	
	// i1 is now dead, touching invalidated tracking pointers throws
	try {
		r1_1->print();
	} catch (const std::exception & e) {
		std::cout << e.what() << std::endl;
	}
	try {
		r1_2->print();
	} catch (const std::exception & e) {
		std::cout << e.what() << std::endl;
	}
	
	// But i2 is still alive, we may still use the tracking pointer to it
	r2->print();
	
	std::cout << "(end of scope)" << std::endl;
	
	// Local variables will be destructed in the reverse order of construction:
	// ~r2, ~r1_2, ~r1_1, ~i2, ~i1
	
	// Because r2 gets destructed before i2, no invalidation is triggered, only the tracking_ptr gets freed from its tracker (the object it points at)
	
	// Destruction of r1_2 (and r1_1) skips the pointers being freed since the tracker does not exist anymore (i1 is already dead)
	
	// Destruction of i2 does not trigger invalidation of tracking pointer r2, because it has been freed
	
	// Destruction of i1 does nothing since the unique_ptr is already null
}
Exemplo n.º 7
0
rgbColor whittedRayTracer::L(const ray& r) const{
    ray r2(r);
    return _L(r2);
}
void
CoinShallowPackedVectorUnitTest()
{
  CoinRelFltEq eq;
  int i;
  // Test default constructor
  {
    CoinShallowPackedVector r;
    assert( r.indices_==NULL );
    assert( r.elements_==NULL );
    assert( r.nElements_==0 );
  }

  // Test set and get methods
  const int ne = 4;
  int inx[ne] = { 1, 3, 4, 7 };
  double el[ne] = { 1.2, 3.4, 5.6, 7.8 };
  {
    CoinShallowPackedVector r;    
    assert( r.getNumElements()==0 );
    
    // Test setting/getting elements with int* & double* vectors
    r.setVector( ne, inx, el );
    assert( r.getNumElements()==ne );
    for ( i=0; i<ne; i++ ) {
      assert( r.getIndices()[i]  == inx[i] );
      assert( r.getElements()[i] == el[i]  );
    }
    assert ( r.getMaxIndex()==7 );
    assert ( r.getMinIndex()==1 );

    // try to clear it
    r.clear();
    assert( r.indices_==NULL );
    assert( r.elements_==NULL );
    assert( r.nElements_==0 );

    // Test setting/getting elements with indices out of order  
    const int ne2 = 5;
    int inx2[ne2] = { 2, 4, 8, 14, 3 };
    double el2[ne2] = { 2.2, 4.4, 6.6, 8.8, 3.3 };
 
    r.setVector(ne2,inx2,el2);
    
    assert( r.getNumElements()==ne2 );    
    for (i = 0; i < ne2; ++i) {
       assert( r.getIndices()[i]==inx2[i] );
       assert( r.getElements()[i]==el2[i] );
    }
    
    assert ( r.getMaxIndex()==14 );
    assert ( r.getMinIndex()==2 );
    // try to call it once more
    assert ( r.getMaxIndex()==14 );
    assert ( r.getMinIndex()==2 );

    CoinShallowPackedVector r1(ne2,inx2,el2);
    assert( r == r1 );

    // assignment operator
    r1.clear();
    r1 = r;
    assert( r == r1 );

    // assignment from packed vector
    CoinPackedVector pv1(ne2,inx2,el2);
    r1 = pv1;
    assert( r == r1 );

    // construction
    CoinShallowPackedVector r2(r1);
    assert( r2 == r );
    
    // construction from packed vector
    CoinShallowPackedVector r3(pv1);
    assert( r3 == r );

    // test duplicate indices
    {
      const int ne3 = 4;
      int inx3[ne3] = { 2, 4, 2, 3 };
      double el3[ne3] = { 2.2, 4.4, 8.8, 6.6 };
      r.setVector(ne3,inx3,el3, false);
      assert(r.testForDuplicateIndex() == false);
      bool errorThrown = false;
      try {
        r.setTestForDuplicateIndex(true);
      }
      catch (CoinError& e) {
        errorThrown = true;
      }
      assert( errorThrown );

      r.clear();
      errorThrown = false;
      try {
	 r.setVector(ne3,inx3,el3);
      }
      catch (CoinError& e) {
        errorThrown = true;
      }
      assert( errorThrown );
	 
      errorThrown = false;
      try {
	 CoinShallowPackedVector r1(ne3,inx3,el3);
      }
      catch (CoinError& e) {
	 errorThrown = true;
      }
      assert( errorThrown );
    } 
    
  } 

  // Test copy constructor and assignment operator
  {
    CoinShallowPackedVector rhs;
    {
      CoinShallowPackedVector r;
      {
        CoinShallowPackedVector rC1(r);      
        assert( 0==r.getNumElements() );
        assert( 0==rC1.getNumElements() );
        
        r.setVector( ne, inx, el ); 
        
        assert( ne==r.getNumElements() );
        assert( 0==rC1.getNumElements() ); 
      }
      
      CoinShallowPackedVector rC2(r);   
      
      assert( ne==r.getNumElements() );
      assert( ne==rC2.getNumElements() );
      
      for ( i=0; i<ne; i++ ) {
        assert( r.getIndices()[i] == rC2.getIndices()[i] );
        assert( r.getElements()[i] == rC2.getElements()[i] );
      }

      rhs=rC2;
    }
    // Test that rhs has correct values even though lhs has gone out of scope
    assert( rhs.getNumElements()==ne );
    
    for ( i=0; i<ne; i++ ) {
      assert( inx[i] == rhs.getIndices()[i] );
      assert(  el[i] == rhs.getElements()[i] );
    } 
  }

  // Test operator==
  {
    CoinShallowPackedVector v1,v2;
    assert( v1==v2 );
    assert( v2==v1 );
    assert( v1==v1 );
    assert( !(v1!=v2) );
    
    v1.setVector( ne, inx, el );
    assert ( !(v1==v2) );
    assert ( v1!=v2 );

    CoinShallowPackedVector v3(v1);
    assert( v3==v1 );
    assert( v3!=v2 );

    CoinShallowPackedVector v4(v2);
    assert( v4!=v1 );
    assert( v4==v2 );
  }

 

  {
    // Test operator[] and isExistingIndex()
    const int ne = 4;
    int inx[ne] =   {  1,   4,  0,   2 };
    double el[ne] = { 10., 40., 1., 50. };
    CoinShallowPackedVector r;
    assert( r[1]==0. );

    r.setVector(ne,inx,el);

    assert( r[-1]==0. );
    assert( r[ 0]==1. );
    assert( r[ 1]==10.);
    assert( r[ 2]==50.);
    assert( r[ 3]==0. );
    assert( r[ 4]==40.);
    assert( r[ 5]==0. );
    assert(  r.isExistingIndex(2) );
    assert( !r.isExistingIndex(3) );

    assert( !r.isExistingIndex(-1) );
    assert(  r.isExistingIndex(0) );
    assert( !r.isExistingIndex(3) );
    assert(  r.isExistingIndex(4) );
    assert( !r.isExistingIndex(5) );
    
    assert ( r.getMaxIndex()==4 );
    assert ( r.getMinIndex()==0 );
  }
  
  // Test that attemping to get min/max index of a 0,
  // length vector 
  {
    CoinShallowPackedVector nullVec;
    assert( nullVec.getMaxIndex() == -COIN_INT_MAX/*0*/ );
    assert( nullVec.getMinIndex() == COIN_INT_MAX/*0*/ );
  } 

  {
     // test dense vector
     const int ne = 4;
     int inx[ne] =   {  1,   4,  0,   2 };
     double el[ne] = { 10., 40., 1., 50. };
     CoinShallowPackedVector r;
     r.setVector(ne,inx,el);
     double * dense = r.denseVector(6);
     assert(dense[0] == 1.);
     assert(dense[1] == 10.);
     assert(dense[2] == 50.);
     assert(dense[3] == 0.);
     assert(dense[4] == 40.);
     assert(dense[5] == 0.);
     delete[] dense;

     // try once more
     dense = r.denseVector(7);
     assert(dense[0] == 1.);
     assert(dense[1] == 10.);
     assert(dense[2] == 50.);
     assert(dense[3] == 0.);
     assert(dense[4] == 40.);
     assert(dense[5] == 0.);
     assert(dense[6] == 0.);
     delete[] dense;
     
  }
     
     

  
#if 0
  // what happens when someone sets 
  // the number of elements to be a negative number
  {    
    const int ne = 4;
    int inx1[ne] = { 1, 3, 4, 7 };
    double el1[ne] = { 1.2, 3.4, 5.6, 7.8 };
    CoinShallowPackedVector v1;
    v1.setVector(-ne,inx1,el1);
  }
#endif

  
  // Test adding vectors
  {    
    const int ne1 = 5;
    int inx1[ne1]   = { 1,  3,  4,  7,  5  };
    double el1[ne1] = { 1., 5., 6., 2., 9. };
    const int ne2 = 4;
    int inx2[ne2] =   { 7,  4,  2,  1  };
    double el2[ne2] = { 7., 4., 2., 1. };
    CoinShallowPackedVector v1;
    v1.setVector(ne1,inx1,el1);
    CoinShallowPackedVector v2;
    v2.setVector(ne2,inx2,el2);
    CoinPackedVector r = v1 + v2;

    const int ner = 6;
    int inxr[ner] =   {    1,     2,     3,     4,     5,     7  };
    double elr[ner] = { 1.+1., 0.+2., 5.+0., 6.+4., 9.+0., 2.+7. };
    CoinPackedVector rV;
    rV.setVector(ner,inxr,elr);
    assert( rV != r );
    assert( r.isEquivalent(rV) );
    
    CoinPackedVector p1=v1+3.1415;
    for ( i=0; i<p1.getNumElements(); i++ )
      assert( eq( p1.getElements()[i], v1.getElements()[i]+3.1415) );

    CoinPackedVector p2=(-3.1415) + p1;
    assert( p2.isEquivalent(v1) );
  } 
  
  // Test subtracting vectors
  {    
    const int ne1 = 5;
    int inx1[ne1]   = { 1,  3,  4,  7,  5  };
    double el1[ne1] = { 1., 5., 6., 2., 9. };
    const int ne2 = 4;
    int inx2[ne2] =   { 7,  4,  2,  1  };
    double el2[ne2] = { 7., 4., 2., 1. };
    CoinShallowPackedVector v1;
    v1.setVector(ne1,inx1,el1);
    CoinShallowPackedVector v2;
    v2.setVector(ne2,inx2,el2);
    CoinPackedVector r = v1 - v2;

    const int ner = 6;
    int inxr[ner] =   {    1,     2,     3,     4,     5,     7  };
    double elr[ner] = { 1.-1., 0.-2., 5.-0., 6.-4., 9.-0., 2.-7. };
    CoinPackedVector rV;
    rV.setVector(ner,inxr,elr);
    assert( r.isEquivalent(rV) );  
    
    CoinPackedVector p1=v1-3.1415;
    for ( i=0; i<p1.getNumElements(); i++ )
      assert( eq( p1.getElements()[i], v1.getElements()[i]-3.1415) );
  } 
  
  // Test multiplying vectors
  {    
    const int ne1 = 5;
    int inx1[ne1]   = { 1,  3,  4,  7,  5  };
    double el1[ne1] = { 1., 5., 6., 2., 9. };
    const int ne2 = 4;
    int inx2[ne2] =   { 7,  4,  2,  1  };
    double el2[ne2] = { 7., 4., 2., 1. };
    CoinShallowPackedVector v1;
    v1.setVector(ne1,inx1,el1);
    CoinShallowPackedVector v2;
    v2.setVector(ne2,inx2,el2);
    CoinPackedVector r = v1 * v2;

    const int ner = 6;
    int inxr[ner] =   {    1,     2,     3,     4,     5,     7  };
    double elr[ner] = { 1.*1., 0.*2., 5.*0., 6.*4., 9.*0., 2.*7. };
    CoinPackedVector rV;
    rV.setVector(ner,inxr,elr);
    assert( r.isEquivalent(rV) );

    CoinPackedVector p1=v1*3.3;
    for ( i=0; i<p1.getNumElements(); i++ )
      assert( eq( p1.getElements()[i], v1.getElements()[i]*3.3) );
    
    CoinPackedVector p2=(1./3.3) * p1;
    assert( p2.isEquivalent(v1) );
  } 
  
  // Test dividing vectors
  {    
    const int ne1 = 3;
    int inx1[ne1]   = { 1,  4,  7  };
    double el1[ne1] = { 1., 6., 2. };
    const int ne2 = 4;
    int inx2[ne2] =   { 7,  4,  2,  1  };
    double el2[ne2] = { 7., 4., 2., 1. };
    CoinShallowPackedVector v1;
    v1.setVector(ne1,inx1,el1);
    CoinShallowPackedVector v2;
    v2.setVector(ne2,inx2,el2);
    CoinPackedVector r = v1 / v2;

    const int ner = 4;
    int inxr[ner] =   {    1,     2,      4,     7  };
    double elr[ner] = { 1./1., 0./2.,  6./4., 2./7. };
    CoinPackedVector rV;
    rV.setVector(ner,inxr,elr);
    assert( r.isEquivalent(rV) );
        
    CoinPackedVector p1=v1/3.1415;
    for ( i=0; i<p1.getNumElements(); i++ )
      assert( eq( p1.getElements()[i], v1.getElements()[i]/3.1415) );
  }
   
  // Test sum
  { 
    CoinShallowPackedVector s;
    assert( s.sum() == 0 );

    int inx = 25;
    double value = 45.;
    s.setVector(1, &inx, &value);
    assert(s.sum()==45.);

    const int ne1 = 5;
    int inx1[ne1]   = { 10,  3,  4,  7,  5  };
    double el1[ne1] = { 1., 5., 6., 2., 9. };
    s.setVector(ne1,inx1,el1);

    assert(s.sum()==1.+5.+6.+2.+9.);
  }
  
  // Just another interesting test
  {    
    // Create numerator vector
    const int ne1 = 2;
    int inx1[ne1]   = { 1,  4  };
    double el1[ne1] = { 1., 6. };
    CoinShallowPackedVector v1(ne1,inx1,el1);

    // create denominator vector
    const int ne2 = 3;
    int inx2[ne2] =   { 1,  2,  4 };
    double el2[ne2] = { 1., 7., 4.};
    CoinShallowPackedVector v2(ne2,inx2,el2);

    // Compute ratio
    CoinPackedVector ratio = v1 / v2;

    // Sort ratios
    ratio.sortIncrElement();

    // Test that the sort really worked
    assert( ratio.getElements()[0] == 0.0/7.0 );
    assert( ratio.getElements()[1] == 1.0/1.0 );
    assert( ratio.getElements()[2] == 6.0/4.0 );

    // Get numerator of of sorted ratio vector
    assert( v1[ ratio.getIndices()[0] ] == 0.0 );
    assert( v1[ ratio.getIndices()[1] ] == 1.0 );
    assert( v1[ ratio.getIndices()[2] ] == 6.0 );

    // Get denominator of of sorted ratio vector
    assert( v2[ ratio.getIndices()[0] ] == 7.0 );
    assert( v2[ ratio.getIndices()[1] ] == 1.0 );
    assert( v2[ ratio.getIndices()[2] ] == 4.0 );
  }

  {
    // Test that sample usage works

    const int ne = 4;
    int inx[ne] =   {  1,   4,  0,   2 };
    double el[ne] = { 10., 40., 1., 50. };
    CoinShallowPackedVector r(ne,inx,el);

    assert( r.getIndices()[0]== 1  );
    assert( r.getElements()[0]==10. );
    assert( r.getIndices()[1]== 4  );
    assert( r.getElements()[1]==40. );
    assert( r.getIndices()[2]== 0  );
    assert( r.getElements()[2]== 1. );
    assert( r.getIndices()[3]== 2  );
    assert( r.getElements()[3]==50. );

    assert( r[ 0]==1. );
    assert( r[ 1]==10.);
    assert( r[ 2]==50.);
    assert( r[ 3]==0. );
    assert( r[ 4]==40.);

    CoinShallowPackedVector r1;
    r1=r;
    assert( r==r1 );

    CoinPackedVector add = r + r1;
    assert( add[0] ==  1.+ 1. );
    assert( add[1] == 10.+10. );
    assert( add[2] == 50.+50. );
    assert( add[3] ==  0.+ 0. );
    assert( add[4] == 40.+40. );

    assert( r.sum() == 10.+40.+1.+50. );
  }
  
  {
    // Test findIndex
    const int ne = 4;
    int inx[ne] =   {  1,  -4,  0,   2 };
    double el[ne] = { 10., 40., 1., 50. };
    CoinShallowPackedVector r(ne,inx,el);

    assert( r.findIndex(2)  == 3 );
    assert( r.findIndex(0)  == 2 );
    assert( r.findIndex(-4) == 1 );
    assert( r.findIndex(1)  == 0 );
    assert( r.findIndex(3)  == -1 );
  }  
  {
    // Test construction with testing for duplicates as false
    const int ne = 4;
    int inx[ne] =   {  1,  -4,  0,   2 };
    double el[ne] = { 10., 40., 1., 50. };
    CoinShallowPackedVector r(ne,inx,el,false);

    assert( r.isExistingIndex(1) );
    assert( r.isExistingIndex(-4) );
    assert( r.isExistingIndex(0) );
    assert( r.isExistingIndex(2) );
    assert( !r.isExistingIndex(3) );
    assert( !r.isExistingIndex(-3) );
  }
}
Exemplo n.º 9
0
vector<HOG_BLOCK> compute_hog_features(Mat image, int kernel_cell_size, int block_size, int gaussian_blur_kernel) 
{
  int height = image.rows;
  int width = image.cols;

  vector<Mat> block_matrix;

  Mat gradient_image;

  Mat grad_x, grad_y;

  vector<HOG_BLOCK> hog_blocks;

  // Check for proper kernel size
  if(height % kernel_cell_size > 0 || width % kernel_cell_size > 0) {
    cerr << "Invalid kernel cell size." << endl;
    
    return hog_blocks;
  }

  // Check for proper block size
  int num_cells_height = height / kernel_cell_size;
  int num_cells_width = width / kernel_cell_size;
  if(num_cells_height % block_size > 0 || num_cells_width % block_size > 0) {
    cerr << "Invalid block size." << endl;
    
    return hog_blocks;
  }

  image.copyTo(gradient_image);

  // Equalize histogram
  equalizeHist(gradient_image, gradient_image);

  // Gaussian blur kernel size
  GaussianBlur(gradient_image, gradient_image, Size(gaussian_blur_kernel, gaussian_blur_kernel), 0, 0);

  // Compute for gradient x-wise using Sobel operator
  Sobel(gradient_image, grad_x, CV_32F, 1, 0, 3);

  // Compute for graident y-wise using Sobel operator
  Sobel(gradient_image, grad_y, CV_32F, 0, 1, 3);

  // Compute for gradient orientation.
  // Store in new gradient matrix.
  Mat orientation_matrix(gradient_image.rows, gradient_image.cols, DataType<float>::type);
  for(int i = 0; i < gradient_image.rows; i++) {
    for(int j = 0; j < gradient_image.cols; j++) {
      float gx = grad_x.at<float>(i,j);
      float gy = grad_y.at<float>(i,j);
      float orientation = atan(gy / (gx + 0.00001)) * (180 / 3.14) + 90;
      orientation_matrix.at<float>(i, j) = orientation;
    }
  }

  // Divide cells according to block size
  for(int i = 0; i < width - (kernel_cell_size * block_size) + 1; i += (kernel_cell_size * block_size) / 2) {
    for(int j = 0; j < height - (kernel_cell_size * block_size) + 1; j += (kernel_cell_size * block_size) / 2) {
      
      Rect r(i, j, kernel_cell_size * block_size, kernel_cell_size * block_size);
      Mat b_matrix = orientation_matrix(r);

      block_matrix.push_back(b_matrix);

      HOG_BLOCK hg;
      hg.rect_block = r;
      for(int row = 0; row < (kernel_cell_size * block_size); row += kernel_cell_size) {
        for(int col = 0; col < (kernel_cell_size * block_size); col += kernel_cell_size) {
          Rect r2(row, col, kernel_cell_size, kernel_cell_size);
          Mat c_matrix = b_matrix(r2);

          hg.cell_matrices.push_back(c_matrix);
        }
      }

      hog_blocks.push_back(hg);
    }
  }

  // Store histogram of oriented gradients per block
  // Loop through each hog_block
  //    Loop through each cell of hog_block
  //      Get orientation of each pixel position in cell and increment corresponding bin
  for(int i = 0; i < hog_blocks.size(); i++) {
    for(int j = 0; j < hog_blocks.at(i).cell_matrices.size(); j++) {
      vector<int> histogram_of_oriented_gradient;
      histogram_of_oriented_gradient.resize(BIN_COUNT);
      for(int row = 0; row < hog_blocks.at(i).cell_matrices.at(j).rows; row++) {
        for(int col = 0; col < hog_blocks.at(i).cell_matrices.at(j).cols; col++) {
          float o = hog_blocks.at(i).cell_matrices.at(j).at<float>(row, col);
          if(o <= 20) {
            histogram_of_oriented_gradient.at(0)++;
          } else if(o > 20 && o <= 40) {
            histogram_of_oriented_gradient.at(1)++;
          } else if(o > 40 && o <= 60) {
            histogram_of_oriented_gradient.at(2)++;
          } else if(o > 60 && o <= 80) {
            histogram_of_oriented_gradient.at(3)++;
          } else if(o > 80 && o <= 100) {
            histogram_of_oriented_gradient.at(4)++;
          } else if(o > 100 && o <= 120) {
            histogram_of_oriented_gradient.at(5)++;
          } else if(o > 120 && o <= 140) {
            histogram_of_oriented_gradient.at(6)++;
          } else if(o > 140 && o <= 160) {
            histogram_of_oriented_gradient.at(7)++;
          } else if(o > 160 && o <= 180) {
            histogram_of_oriented_gradient.at(8)++;
          }
        }
      }

      hog_blocks.at(i).hogs.push_back(histogram_of_oriented_gradient);
    }
  }

  // Normalize the hogs
  for(int i = 0; i < hog_blocks.size(); i++) {
    float norm = 0;
    for(int x = 0; x < hog_blocks.at(i).hogs.size(); x++) {
      for(int y = 0; y < hog_blocks.at(i).hogs.at(x).size(); y++) {
        norm += pow(hog_blocks.at(i).hogs.at(x).at(y), 2);
      }
    }

    norm += sqrt(norm);
    
    for(int j = 0; j < hog_blocks.at(i).hogs.size(); j++) {
      vector<float> normalized_hogs;
      normalized_hogs.resize(BIN_COUNT);

      for(int b = 0; b < BIN_COUNT; b++) {
        normalized_hogs.at(b) = hog_blocks.at(i).hogs.at(j).at(b) / norm;
      }

      hog_blocks.at(i).normalized_hogs.push_back(normalized_hogs);
    }
  }

  return hog_blocks;
}
Exemplo n.º 10
0
Collision::Collision(PObject* obj1, PObject* obj2)
{
	trueCollision = false;
	
	objects = new PObject*[2];
	objects[0] = obj1;
	objects[1] = obj2;
	
	/*
	 * the following was written before the Vect2D class was written
	 * (and that's why it's so messy)
	 */
	Vect2D norm;
	Point p1,p2;
	
	const Point* obj1vertices = objects[0]->getVertices();
	const Point* obj2vertices = objects[1]->getVertices();
	int numPoints=0;
	float sumx=0;
	float sumy=0;
	float parametric;
	float parametric2;
	float denominator;
	
	float vec1x;
	float vec1y;
	float vec1deltax;//between this point and the next one in the shape (going counterclockwise)
	float vec1deltay;
	
	float vec2x;
	float vec2y;
	float vec2deltax;
	float vec2deltay;
	
	float deltax, deltay; //between the two points on different shapes
	
	/*
	 * x1+k*t = x2+c*k
	 * y1+b*t = y2+d*k
	 */
	
	for (int i = 0; i < objects[0]->getNumVertices(); i++)
	{
		vec1x = obj1vertices[i].x;//x1
		vec1y = obj1vertices[i].y;//y1
		
		vec1deltax = obj1vertices[(i + 1) % objects[0]->getNumVertices()].x - vec1x;//a
		vec1deltay = obj1vertices[(i + 1) % objects[0]->getNumVertices()].y - vec1y;//b
		
		for (int j = 0; j < objects[1]->getNumVertices(); j++)
		{
			vec2x = obj2vertices[j].x;//x2
			vec2y = obj2vertices[j].y;//y2
			
			vec2deltax = obj2vertices[(j + 1) % objects[1]->getNumVertices()].x - vec2x;//c
			vec2deltay = obj2vertices[(j + 1) % objects[1]->getNumVertices()].y - vec2y;//d
			
			denominator = (vec1deltax * vec2deltay) - (vec2deltax * vec1deltay);//ad-bc
			if (denominator != 0)
			{
				deltax = vec1x-vec2x;//x1-x2
				deltay = vec1y-vec2y;//y1-y2
				
				parametric = ((vec2deltax * (deltay)) - vec2deltay * (deltax)) / (denominator);//t
				parametric2 = ((vec1deltax * (deltay)) - vec1deltay * (deltax)) / (denominator);//k

				if (parametric <= 1 && parametric >= 0 && parametric2 <= 1 && parametric2 >= 0)
				{
					numPoints++;
					sumx += vec1x + (parametric * vec1deltax);//x = x1+a*t
					sumy += vec1y + (parametric * vec1deltay);//y = y1+b*t
					//uses the normal vector of the first collision
					if (!trueCollision){
						/* old way of finding
						//figure out which one collided on the corner
						if (abs(parametric2-.5) < abs(parametric-.5)){
							//vector1's point of collision was closer to the corner
							norm.set(vec2deltay,-vec2deltax);
						}
						else
						{
							norm.set(vec2deltax,-vec2deltay);
						}*/
						//VERY crude approximation for normal vector at collision point
						norm.set(objects[1]->get_centerx()-objects[0]->get_centerx(), objects[1]->get_centery()-objects[0]->get_centery());
						norm.normalize();
					}
					trueCollision = true;
				}
			}
		}
	}
	if (trueCollision)
	{
		intersection.x = sumx/numPoints;
		intersection.y = sumy/numPoints;
		//calculate impulse here
		float e = objects[0]->get_elasticity()*objects[1]->get_elasticity();
		Vect2D r1(intersection.x-objects[0]->get_centerx(), intersection.y-objects[0]->get_centery());
		Vect2D r2(intersection.x-objects[1]->get_centerx(), intersection.y-objects[1]->get_centery());
		//vap = vcenter + w x r1 where w is angular velocity vector that points into screen
		//vap = velocity of point of collision on each object
		Vect2D vap(objects[0]->get_vx()-objects[0]->get_dtheta()*r1.y, objects[0]->get_vy()+objects[0]->get_dtheta()*r1.x);
		Vect2D vbp(objects[1]->get_vx()-objects[1]->get_dtheta()*r2.y, objects[1]->get_vy()+objects[1]->get_dtheta()*r2.x);
		Vect2D& vabp = vap-vbp;
		float ran = r1.cross(norm);
		float rbn = r2.cross(norm);
		//source: http://www.myphysicslab.com/collision.html
		float j= (-(1+e)*vabp.dot(norm))/(1/objects[0]->get_mass() + 1/objects[1]->get_mass() + ran*ran/objects[0]->get_momentInertia() + rbn*rbn/objects[1]->get_momentInertia());
		
		impulse.set(norm);
		impulse.scale(j);
	}
}
Exemplo n.º 11
0
void tile(int neXindex, int neYindex, int N, int holeX, int holeY)
{
  if(N==2)
   {
      Color c=rColor();
      if(flag==0)
        c=COLOR("White");
      if(holeX!=neXindex || holeY!=neYindex)
      {
        Rectangle r3(neXindex*W + W/2,neYindex*W + W/2,W,W);
        r3.setFill();
        r3.setColor(c);
        r3.imprint();
      }
      if(holeX!=neXindex || holeY!=neYindex+1)
      {
        Rectangle r1(neXindex*W + W/2,neYindex*W + 3*W/2,W,W);
        r1.setFill();
        r1.setColor(c);
        r1.imprint();
      }
      if(holeX!=neXindex+1 || holeY!=neYindex+1)
      {
        Rectangle r2(neXindex*W + 3*W/2,neYindex*W + 3*W/2,W,W);
        r2.setFill();
        r2.setColor(c);
        r2.imprint();
      }
      if(holeX!=neXindex+1 || holeY!=neYindex)
      {
        Rectangle r3(neXindex*W + 3*W/2,neYindex*W + W/2,W,W);
        r3.setFill();
        r3.setColor(c);
        r3.imprint();
      }
   } 
  else
  {
    if(neXindex<=holeX && holeX<neXindex+N/2 && neYindex<=holeY && holeY<neYindex+N/2)    //Bottom Left
    {
      tile(neXindex,neYindex,N/2,holeX,holeY);
      tile(neXindex,neYindex+N/2,N/2,neXindex-1+N/2,neYindex+N/2);
      tile(neXindex+N/2,neYindex+N/2,N/2,neXindex+N/2,neYindex+N/2);
      tile(neXindex+N/2,neYindex,N/2,neXindex+N/2,neYindex-1+N/2);
      flag=0;
      tile(neXindex-1+N/2,neYindex-1+N/2,2,neXindex-1+N/2,neYindex-1+N/2);
      flag=1;
    }
    else if(neXindex<=holeX && holeX<neXindex+N/2 && holeY>=neYindex+N/2 && holeY<neYindex+N) //Top Left
    {
      tile(neXindex,neYindex+N/2,N/2,holeX,holeY);
      tile(neXindex,neYindex,N/2,neXindex-1+N/2,neYindex-1+N/2);
      tile(neXindex+N/2,neYindex+N/2,N/2,neXindex+N/2,neYindex+N/2);
      tile(neXindex+N/2,neYindex,N/2,neXindex+N/2,neYindex-1+N/2);
      flag=0;
      tile(neXindex-1+N/2,neYindex-1+N/2,2,neXindex-1+N/2,neYindex+N/2);
      flag=1;
    }
    else if(holeX>=neXindex+N/2 && holeX<neXindex+N && holeY>=neYindex+N/2 && holeY<neYindex+N) //Top Right
    {
      tile(neXindex+N/2,neYindex+N/2,N/2,holeX,holeY);
      tile(neXindex,neYindex,N/2,neXindex-1+N/2,neYindex-1+N/2);
      tile(neXindex,neYindex+N/2,N/2,neXindex-1+N/2,neYindex+N/2);
      tile(neXindex+N/2,neYindex,N/2,neXindex+N/2,neYindex-1+N/2);
      flag=0;
      tile(neXindex-1+N/2,neYindex-1+N/2,2,neXindex+N/2,neYindex+N/2);
      flag=1;
    }
    else //if(holeX>=neXindex+N/2 && holeX<neXindex+N && neYindex<=holeY && holeY<neYindex+N/2) //Bottom Right
    {
      tile(neXindex+N/2,neYindex,N/2,holeX,holeY);
      tile(neXindex,neYindex,N/2,neXindex-1+N/2,neYindex-1+N/2);
      tile(neXindex,neYindex+N/2,N/2,neXindex-1+N/2,neYindex+N/2);
      tile(neXindex+N/2,neYindex+N/2,N/2,neXindex+N/2,neYindex+N/2);
      flag=0;
      tile(neXindex-1+N/2,neYindex-1+N/2,2,neXindex+N/2,neYindex-1+N/2);
      flag=1;
    }
  }
}
Exemplo n.º 12
0
static void k951_connect ( PIA *pi  )

{ 	pi->saved_r0 = r0();
        pi->saved_r2 = r2();
        w2(4); 
}
Exemplo n.º 13
0
 std::vector<int> reorder(MatrixType const & matrix,
                          advanced_cuthill_mckee_tag const & tag)
 {
   std::size_t n = matrix.size();
   double a = tag.starting_node_param();
   std::size_t gmax = tag.max_root_nodes();
   std::vector<int> r;
   std::vector<int> r_tmp;
   std::vector<int> r_best;
   std::vector<int> r2(n);
   std::vector<bool> inr(n, false);
   std::vector<bool> inr_tmp(n);
   std::vector<bool> inr_best(n);
   std::deque<int> q;
   std::vector< std::vector<int> > nodes;
   std::vector<int> nodes_p;
   std::vector<int> tmp(2);
   std::vector< std::vector<int> > l;
   int deg_min;
   int deg_max;
   int deg_a;
   int deg;
   int bw;
   int bw_best;
   std::vector<int> comb;
   std::size_t g;
   int c;
   
   r.reserve(n);
   r_tmp.reserve(n);
   r_best.reserve(n);
   nodes.reserve(n);
   nodes_p.reserve(n);
   comb.reserve(n);
   
   do
   {   
       // add to nodes_p all nodes not yet in r which are candidates for the root node layer  
       // search unnumbered node and generate layering 
       for (std::size_t i = 0; i < n; i++)
       {
           if (!inr[i])
           {
               detail::generate_layering(matrix, l, i);
               break;
           }
       }
       nodes.resize(0);
       for (std::vector< std::vector<int> >::iterator it = l.begin();
         it != l.end(); it++)
       {
           for (std::vector<int>::iterator it2 = it->begin();
             it2 != it->end(); it2++)
           {
               tmp[0] = *it2;
               tmp[1] = matrix[*it2].size() - 1;
               nodes.push_back(tmp);
           }
       }
       // determine minimum and maximum node degree
       deg_min = -1;
       deg_max = -1;
       for (std::vector< std::vector<int> >::iterator it = nodes.begin(); 
         it != nodes.end(); it++)
       {
           deg = (*it)[1];
           if (deg_min < 0 || deg < deg_min)
           {
               deg_min = deg;
           }
           if (deg_max < 0 || deg > deg_max)
           {
               deg_max = deg;
           }
       }
       deg_a = deg_min + (int) (a * (deg_max - deg_min));
       nodes_p.resize(0);
       for (std::vector< std::vector<int> >::iterator it = nodes.begin(); 
         it != nodes.end(); it++)
       {
           if ((*it)[1] <= deg_a)
           {
               nodes_p.push_back((*it)[0]);
           }
       }
       
       inr_tmp = inr;
       g = 1;
       comb.resize(1);
       comb[0] = 1;
       bw_best = -1;
       
       for (;;) // for all combinations of g <= gmax root nodes repeat
       {
           inr = inr_tmp;
           r_tmp.resize(0);
           
           // add the selected root nodes according to actual combination comb to q
           for (std::vector<int>::iterator it = comb.begin(); 
             it != comb.end(); it++)
           {
               q.push_back(nodes_p[(*it)-1]);
           }
 
           do // perform normal CutHill-McKee algorithm for given root nodes with 
           // resulting numbering stored in r_tmp
           {
               c = q.front();
               q.pop_front();
               if (!inr[c])
               {
                   r_tmp.push_back(c);
                   inr[c] = true;
                   
                   nodes.resize(0);
                   for (typename MatrixType::value_type::const_iterator it = matrix[c].begin(); it != matrix[c].end(); it++)
                   {
                       if (it->first == c) continue;
                       if (inr[it->first]) continue;
                       
                       tmp[0] = it->first;
                       tmp[1] = matrix[it->first].size() - 1;
                       nodes.push_back(tmp);
                   }
                   std::sort(nodes.begin(), nodes.end(), detail::cuthill_mckee_comp_func);
                   for (std::vector< std::vector<int> >::iterator it = 
                     nodes.begin(); it != nodes.end(); it++)
                   {
                       q.push_back((*it)[0]);
                   }
               }
           } while (q.size() != 0);
           
           // calculate resulting bandwith for root node combination
           // comb for current numbered component of the node graph
           for (std::size_t i = 0; i < r_tmp.size(); i++)
           {
               r2[r_tmp[i]] = r.size() + i;
           }
           bw = 0;
           for (std::size_t i = 0; i < r_tmp.size(); i++)
           {
               for (typename MatrixType::value_type::const_iterator it  = matrix[r_tmp[i]].begin(); 
                                                                    it != matrix[r_tmp[i]].end();
                                                                    it++)
               {
                   bw = std::max(bw, std::abs(static_cast<int>(r.size() + i) - r2[it->first]));
               }
           }
           
           // remember ordering r_tmp in r_best for smallest bandwith
           if (bw_best < 0 || bw < bw_best)
           {
               r_best = r_tmp;
               bw_best = bw;
               inr_best = inr;
           }
           
           // calculate next combination comb, if not existing
           // increment g if g stays <= gmax, or else terminate loop
           if (!detail::comb_inc(comb, nodes_p.size()))
           {
               g++;
               if ( (gmax > 0 && g > gmax) || g > nodes_p.size())
               {
                   break;
               }
               comb.resize(g);
               for (std::size_t i = 0; i < g; i++)
               {
                   comb[i] = i + 1;
               }
           }
       }
       
       // store best order r_best in result array r
       for (std::vector<int>::iterator it = r_best.begin(); 
         it != r_best.end(); it++)
       {
           r.push_back((*it));
       }
       inr = inr_best;
       
   } while (r.size() < n);
   
   return r;
 }
Exemplo n.º 14
0
/*! This method does the same as PP_AttrProp::isEquivalent(const PP_AttrProp *) except
	 that instead of being passed another AP to be compared to, it is passed sets of
	 attributes and properties which only virtually comprise another AP.
	 \retval TRUE if equivalent (regardless of order) to given Attrs and Props, FALSE otherwise.
*/
bool PP_AttrProp::isEquivalent(const gchar ** attrs, const gchar ** props) const
{
	UT_uint32 iAttrsCount  = 0;
	UT_uint32 iPropsCount = 0;

	const gchar ** p = attrs;

	while(p && *p)
	{
		iAttrsCount++;
		p += 2;
	}
	
	p = props;

	while(p && *p)
	{
		iPropsCount++;
		p += 2;
	}

	
	if(   getAttributeCount() != iAttrsCount
	   || getPropertyCount()  != iPropsCount)
		return false;
	
	UT_uint32 i;
	const gchar * pName, * pValue, * pValue2;
	
	for(i =  0; i < getAttributeCount(); ++i)
	{
		pName = attrs[2*i];
		pValue = attrs[2*i + 1];

		if(!getAttribute(pName,pValue2))
			return false;

		// ignore property attribute
		if(0 == strcmp(pValue, PT_PROPS_ATTRIBUTE_NAME))
			continue;

		// handle revision attribute correctly
		if(0 == strcmp(pValue, PT_REVISION_ATTRIBUTE_NAME))
		{
			// requires special treatment
			PP_RevisionAttr r1(pValue);
			PP_RevisionAttr r2 (pValue2);

			if(!(r1 == r2))
			{
				return false;
			}
		}
		else if(0 != strcmp(pValue,pValue2))
			return false;
	}

	for(i =  0; i < getPropertyCount(); ++i)
	{
		pName = props[2*i];
		pValue = props[2*i + 1];

		if(!getProperty(pName,pValue2))
			return false;

		if(0 != strcmp(pValue,pValue2))
			return false;
	}

	return true;
}
void scnreader_model::createRail()
{
    QString noms=this->nomFile;
    noms.push_back("_switch.txt");
    //open the file
    QFile file(noms);

    if(!this->nuage.isEmpty())
    {
        if(this->cfs || !file.exists())
        {
            //            //---------------JJ
            //            if(ftpf>this->ftpd+500)
            //            ftpf=this->ftpd+500;
            //            //-----------------

            //---------------initialize footpulses which determine the beginning and the end of window-----------
            int dw=this->ftpd+1;
            int fw;
            if(this->ftpf-this->ftpd<workWindows)
                fw=this->ftpf;
            else
                fw=this->ftpd+workWindows;


            std::cout << dw << " - " << fw<<std::endl;
            //-------------------------------we initialize Listerail----------------------------------------------
            //create rails with the first footpulse
            RailCluster  r (0.18,0.08,1.5,*this->nuage.value(this->ftpd));
            RailCluster rc=r;
            this->lesRails.addRail(r);
            //and we add the others until the footpulse fw, so window is ftpd - (fw-1)
            for(int i=dw; i<fw;i++)
            {
                RailCluster r2(0.18,0.08,1.5,* (this->nuage.value(i)), rc);
                rc=r2;
                this->lesRails.addRail(r2);
            }
            //cleanNoise(fw);
            this->optimization();
            //we keep detected switch in this window
            int nbswitch=this->lesRailsOptimize.getSwitchDetected().size();
            for(int i=0; i<nbswitch;i++)
            {
                int ftp=this->lesRailsOptimize.getSwitchDetected().at(i);
                if(!this->LesSwitchs.contains(ftp))
                {
                    this->LesSwitchs.push_back(ftp);
                }
            }
            //we reinit lesRailsOptimize et resultRansac
            this->lesRailsOptimize.clear();
            this->resultRANSAC->clear();

            //we continue to cover all the cloud with a window which we move footpulse by footpulse
            while(fw<=this->ftpd+3)//this->ftpf
            {
                //we add a new track and remove the first in track in window
                RailCluster r2(0.18,0.08,1.5,* (this->nuage.value(fw)), rc);
                rc=r2;
                this->lesRails.addRail(r2);

                //we do the treatment to detect switchs in this window
                this->optimization();
                //we keep detected switch in this window
                nbswitch=this->lesRailsOptimize.getSwitchDetected().size();
                for(int i=0; i<nbswitch;i++)
                {
                    int ftp=this->lesRailsOptimize.getSwitchDetected().at(i);
                    //we verify that the size of vector doesn't exceed the cvector's capacity
                    if(this->LesSwitchs.size()<this->capacity)
                    {
                        if(!this->LesSwitchs.contains(ftp))
                            this->LesSwitchs.push_back(ftp);
                    }
                    //if it exceeds
                    else
                    {
                        //----------------we write footpulses in a text file

                        VideEtEnregistre(noms);
                    }

                }

                //we reinit lesRailsOptimize et resultRansac
                //this->lesRailsOptimize.clear();
                //this->resultRANSAC->clear();

                //we move the window
                dw++;
                fw++;
            }

            //----------------we write footpulses of switch in a text file
            this->enregistre(noms);
        }
    }
    else throw Erreur("Les rails n'ont pas pu etre crees car le nuage de points est vide.");
}
Exemplo n.º 16
0
void WorkPlaceWidget::drawEntitie(Entitie* e, bool focus, bool isAbstract){
    this->calculateEntitie(e);
    int x = ((IntField*)e->fieldByID("X"))->getValue();
    int y = ((IntField*)e->fieldByID("Y"))->getValue();
    int w = ((IntField*)e->fieldByID("W"))->getValue();
    int h = ((IntField*)e->fieldByID("H"))->getValue();
    int t = ((IntField*)e->fieldByID("T"))->getValue();

    bool mov = true;
    for(int i=0; i<this->core->getEntitieCount(); i++){
       Entitie* e0 = this->core->getEntitieAt(i);
       int xe = ((IntField*)e0->fieldByID("X"))->getValue();
       int ye = ((IntField*)e0->fieldByID("Y"))->getValue();
       int we = ((IntField*)e0->fieldByID("W"))->getValue();
       int he = ((IntField*)e0->fieldByID("H"))->getValue();
       if((xe-w-15<x)&&(ye-h-15<y)&&(we+xe+15>x)&&(he+ye+15>y)&&(e0!=e)){
           mov = false;
       }
    }
    int alpha =  (((isAbstract)||(!mov)) ? 20 : 250);
    int alpha0 = (((isAbstract)||(!mov)) ? 0 : 25);
    int alpha1 = (((isAbstract)||(!mov)) ? 0 : 100);
    if(isAbstract){
        ((IntField*)e->fieldByID("X"))->setValue(this->curX);
        ((IntField*)e->fieldByID("Y"))->setValue(this->curY);
    }
    QPainter painter(this);
    QColor color(255,200,125,alpha);
    QColor color1(255,170,100,alpha);
    QColor color2(215,215,255,alpha);
    QColor colorRed(252,139,130,alpha);
    QColor colorGreen(125,220,125,alpha);
    QColor colorGreenAlpha(55,155,55,alpha0);
    QColor colorBlackAlpha(0,0,0,alpha1);
    QPen pen1 = QPen(Qt::black, 1, Qt::SolidLine);
    QPen pen2 = QPen(colorBlackAlpha, 1, Qt::SolidLine);
    painter.setPen(pen1);

    if(this->core->getState()==10 && this->core->getWeightOfSolution()!=-1){
        bool green = false;
        for(int i=0; i<this->core->getBestWay()->size(); i++){
            if(e->getID()==this->core->getBestWay()->at(i)){
                green = true;
            }
        }
        if(t!=1){
            if(green){
                painter.setBrush(QBrush(colorGreen));
            }else{
                painter.setBrush(QBrush(colorRed));
            }
        }else{
           painter.setBrush(QBrush(color2));
        }
    }else{
        if(t==0){
            painter.setBrush(QBrush(color1));
        }else if(t==1){
            painter.setBrush(QBrush(color2));
        }else{
            painter.setBrush(QBrush(color));
        }
    }

    if(x>max_width-w-5){
        ((IntField*)e->fieldByID("X"))->setValue(max_width-w-5);
        x=max_width-w-5;
    }
    if(y>max_height-h-5){
        ((IntField*)e->fieldByID("Y"))->setValue(max_height-h-5);
        y=max_height-h-5;
    }
    if(x<5){
        ((IntField*)e->fieldByID("X"))->setValue(5);
        x=5;
    }
    if(y<5){
        ((IntField*)e->fieldByID("Y"))->setValue(5);
        y=5;
    }
    string label = e->getID();
    QRect r1(x,y,w,h);
    QRect r12(x+5,y+5,w-10,h-10);
    QRect r2(x,y,w,20);
    if(focus){
        QRect rf(x-2,y-2,w+4,h+4);
        painter.drawRect(rf);
    }
    painter.drawRect(r1);
    painter.drawRect(r2);
    painter.drawText(r12,label.c_str());
    for(int i=work_count; i<e->fieldCount(); i++){
       string field = e->fieldAt(i)->getID();
       QRect tr(x+5,y+5+(i+1-work_count)*24,w-10,h-10);
       painter.drawText(tr,field.c_str());
    }
    if(t!=1){
        double distance = this->core->getDistanceOf(e);
        painter.setBrush(QBrush(Qt::black));
        painter.drawEllipse(QPoint(x-1,y-1), 2, 2);
        if(focus){
            painter.setBrush(QBrush(colorGreenAlpha));
            painter.setPen(pen2);
            painter.drawEllipse(QPoint(x-1,y-1), (int)qRound(distance), (int)qRound(distance));
        }
    }
}
Exemplo n.º 17
0
int main(int ac, char **av){
   FILE *outlist = NULL;

   register int a = 48;
   int r = 0, inc = 0, ct = 0, op;

   printf("FTP Explorer's Criptography v%s - by Nelson Brito\n", VERSION);

   if(ac != 9) usage(av[0]); 

   while(1){
        static struct option long_options[] = {
           {"length",        1, 0, 'l'},
           {"ratio",         1, 0, 'r'},
           {"increment",     1, 0, 'i'},
           {"output",        1, 0, 'o'},
           {0,               0, 0, 0}
        };

        int option_index = 0;
        op = getopt_long(ac, av, "l:r:i:o:", long_options, &option_index);

        if (op == -1) break; 

        switch(op){
              case 'l':
                    ct = atoi(optarg);
                    break;
              case 'r':
                    r = atoi(optarg);
                    break;
              case 'i':
                    inc = atoi(optarg);
                    break;
             case 'o':
                    if(!(outlist=fopen(optarg, "w"))){
                       printf("unable to open %s\n", optarg);
                       exit(0);
                    }
                    break;
              default:
                    usage(av[0]);
                    break;
        }
   }
    
   while(a < 123){ 

        if((a >= 58) && (a <= 64)){
             printf("%c", (char)0);
             a++;
        } 

        else if((a >= 91) && (a <= 96)){
             printf("%c", (char)0);
             a++; 
        }

        else{
              register int c;

              fprintf(outlist, "%c ", (char)a);
              for(c = 0 ; c < ct ; c++) r2(a, c, r, inc, outlist); 
              fprintf(outlist, "\n");
              a++; 
        }

   }

   fclose(outlist);

   return(1);
} 
Exemplo n.º 18
0
static void epat_read_block( PIA *pi, char * buf, int count )

{	int  k, ph, a, b;

	switch (pi->mode) {

	case 0:	w0(7); w2(1); w2(3); w0(0xff);
		ph = 0;
		for(k=0;k<count;k++) {
			if (k == count-1) w0(0xfd);
			w2(6+ph); a = r1();
			if (a & 8) b = a; 
			  else { w2(4+ph); b = r1(); }
			buf[k] = j44(a,b);
			ph =  1 - ph;
		}
		w0(0); w2(4);
		break;

	case 1: w0(0x47); w2(1); w2(5); w0(0xff);
		ph = 0;
		for(k=0;k<count;k++) {
			if (k == count-1) w0(0xfd); 
			w2(4+ph);
			a = r1(); b = r2();
			buf[k] = j53(a,b);
			ph = 1 - ph;
		}
		w0(0); w2(4);
		break;

	case 2: w0(0x27); w2(1); w2(0x25); w0(0);
		ph = 0;
		for(k=0;k<count-1;k++) {
			w2(0x24+ph);
			buf[k] = r0();
			ph = 1 - ph;
		}
		w2(0x26); w2(0x27); buf[count-1] = r0(); 
		w2(0x25); w2(4);
		break;

	case 3: w3(0x80); w2(0x24);
		for(k=0;k<count-1;k++) buf[k] = r4();
		w2(4); w3(0xa0); w2(0x24); buf[count-1] = r4();
		w2(4);
		break;

	case 4: w3(0x80); w2(0x24);
		for(k=0;k<(count/2)-1;k++) ((u16 *)buf)[k] = r4w();
		buf[count-2] = r4();
		w2(4); w3(0xa0); w2(0x24); buf[count-1] = r4();
		w2(4);
		break;

	case 5: w3(0x80); w2(0x24);
		for(k=0;k<(count/4)-1;k++) ((u32 *)buf)[k] = r4l();
		for(k=count-4;k<count-1;k++) buf[k] = r4();
		w2(4); w3(0xa0); w2(0x24); buf[count-1] = r4();
		w2(4);
		break;

	}
}
Exemplo n.º 19
0
static void dymax_point(int tri, int lcd,
		 double x, double y, double z,
                 double *px, double *py)
{
  int axis, v1 = 0;
  double hlng, hlat, h0x, h0y, h0z, h1x, h1y, h1z;

  double gs;
  double gx, gy, gz, ga1,ga2,ga3,ga1p,ga2p,ga3p,gxp,gyp/*,gzp*/;


  /* In order to rotate the given point into the template spherical */
  /* triangle, we need the spherical polar coordinates of the center */
  /* of the face and one of the face vertices. So set up which vertex */
  /* to use.                                                          */

   switch (tri)
   {
    case 1:  v1 =  1;  break;
    case 2:  v1 =  1;  break;
    case 3:  v1 =  1;  break;
    case 4:  v1 =  1;  break;
    case 5:  v1 =  1;  break;
    case 6:  v1 =  2;  break;
    case 7:  v1 =  3;  break;
    case 8:  v1 =  3;  break;
    case 9:  v1 =  4;  break;
    case 10: v1 =  4;  break;
    case 11: v1 =  5;  break;
    case 12: v1 =  5;  break;
    case 13: v1 =  6;  break;
    case 14: v1 =  2;  break;
    case 15: v1 =  2;  break;
    case 16: v1 =  8;  break;
    case 17: v1 =  9;  break;
    case 18: v1 = 10;  break;
    case 19: v1 = 11;  break;
    case 20: v1 =  8;  break;
   } /* end of switch statement */

   h0x = x;
   h0y = y;
   h0z = z;

   h1x = v_x[v1];
   h1y = v_y[v1];
   h1z = v_z[v1];

   c_to_s(&hlng, &hlat, center_x[tri], center_y[tri], center_z[tri]);

   axis = 3;
   r2(axis,hlng,&h0x,&h0y,&h0z);
   r2(axis,hlng,&h1x,&h1y,&h1z);

   axis = 2;
   r2(axis,hlat,&h0x,&h0y,&h0z);
   r2(axis,hlat,&h1x,&h1y,&h1z);

   c_to_s(&hlng,&hlat,h1x,h1y,h1z);
   hlng = hlng - radians(90.0);

   axis = 3;
   r2(axis,hlng,&h0x,&h0y,&h0z);

   /* exact transformation equations */

   gz = sqrt(1 - h0x * h0x - h0y * h0y);
   gs = sqrt( 5 + 2 * sqrt(5) ) / ( gz * sqrt(15) );

   gxp = h0x * gs ;
   gyp = h0y * gs ;

   ga1p = 2.0 * gyp / sqrt(3.0) + (gel / 3.0) ;
   ga2p = gxp - (gyp / sqrt(3)) +  (gel / 3.0) ;
   ga3p = (gel / 3.0) - gxp - (gyp / sqrt(3));

   ga1 = gt + atan( (ga1p - 0.5 * gel) / gdve);
   ga2 = gt + atan( (ga2p - 0.5 * gel) / gdve);
   ga3 = gt + atan( (ga3p - 0.5 * gel) / gdve);

   gx = 0.5 * (ga2 - ga3) ;

   gy = (1.0 / (2.0 * sqrt(3)) ) * (2 * ga1 - ga2 - ga3);

   /* Re-scale so plane triangle edge length is 1. */

   x = gx / garc;
   y = gy / garc;

  /* rotate and translate to correct position          */

  switch (tri)
   {
     case  1: rotate(240.0,&x, &y);
	      *px = x + 2.0; *py = y + 7.0 / (2.0 * sqrt(3.0)) ; break;
     case  2: rotate(300.0, &x, &y); *px = x + 2.0;
              *py = y + 5.0 / (2.0 * sqrt(3.0)) ; break;
     case  3: rotate(0.0, &x, &y);
             *px = x + 2.5; *py = y + 2.0 / sqrt(3.0); break;
     case  4: rotate(60.0, &x, &y);
              *px = x + 3.0; *py = y + 5.0 / (2.0 * sqrt(3.0)) ; break;
     case  5: rotate(180.0, &x, &y);
	      *px = x + 2.5; *py = y + 4.0 * sqrt(3.0) / 3.0; break;
     case  6: rotate(300.0, &x, &y);
              *px = x + 1.5; *py = y + 4.0 * sqrt(3.0) / 3.0; break;
     case  7: rotate(300.0, &x, &y);
              *px = x + 1.0; *py = y + 5.0 / (2.0 * sqrt(3.0)) ; break;
     case  8: rotate(0.0, &x, &y);
              *px = x + 1.5; *py = y + 2.0 / sqrt(3.0); break;
     case  9: if (lcd > 2)
	      {
	      rotate(300.0, &x, &y);
	      *px = x + 1.5; *py = y + 1.0 / sqrt(3.0);
	      }
	      else
	      {
	      rotate(0.0, &x, &y);
	      *px = x + 2.0; *py = y + 1.0 / (2.0 * sqrt(3.0));
	      }
	      break;

     case 10: rotate(60.0, &x, &y);
              *px = x + 2.5; *py = y + 1.0 / sqrt(3.0); break;
     case 11: rotate(60.0, &x, &y);
              *px = x + 3.5; *py = y + 1.0 / sqrt(3.0); break;
     case 12: rotate(120.0, &x, &y);
              *px = x + 3.5; *py = y + 2.0 / sqrt(3.0); break;
     case 13: rotate(60.0, &x, &y);
              *px = x + 4.0; *py = y + 5.0 / (2.0 * sqrt(3.0)); break;
     case 14: rotate(0.0, &x, &y);
	      *px = x + 4.0; *py = y + 7.0 / (2.0 * sqrt(3.0)) ; break;
     case 15: rotate(0.0, &x, &y);
	      *px = x + 5.0; *py = y + 7.0 / (2.0 * sqrt(3.0)) ; break;
     case 16: if (lcd < 4)
	      {
		rotate(60.0, &x, &y);
		*px = x + 0.5; *py = y + 1.0 / sqrt(3.0);
	       }
	       else
	       {
		rotate(0.0, &x, &y);
		*px = x + 5.5; *py = y + 2.0 / sqrt(3.0);
	       }
	       break;
     case 17: rotate(0.0, &x, &y);
	      *px = x + 1.0; *py = y + 1.0 / (2.0 * sqrt(3.0)); break;
     case 18: rotate(120.0, &x, &y);
              *px = x + 4.0; *py = y + 1.0 / (2.0 * sqrt(3.0)); break;
     case 19: rotate(120.0, &x, &y);
              *px = x + 4.5; *py = y + 2.0 / sqrt(3.0); break;
     case 20: rotate(300.0, &x, &y);
              *px = x + 5.0; *py = y + 5.0 / (2.0 * sqrt(3.0)); break;

   } /* end switch statement */

} /* end of dymax_point */
Exemplo n.º 20
0
void QtGradientWidget::mousePressEvent(QMouseEvent *e)
{
    if (e->button() != Qt::LeftButton)
        return;

    QPoint p = e->pos();
    if (d_ptr->m_gradientType == QGradient::LinearGradient) {
        QPointF startPoint = d_ptr->toViewport(d_ptr->m_startLinear);
        double x = p.x() - startPoint.x();
        double y = p.y() - startPoint.y();

        if ((d_ptr->m_handleSize * d_ptr->m_handleSize / 4) > (x * x + y * y)) {
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::StartLinearHandle;
            d_ptr->m_dragOffset = QPointF(x, y);
            update();
            return;
        }

        QPointF endPoint = d_ptr->toViewport(d_ptr->m_endLinear);
        x = p.x() - endPoint.x();
        y = p.y() - endPoint.y();

        if ((d_ptr->m_handleSize * d_ptr->m_handleSize / 4) > (x * x + y * y)) {
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::EndLinearHandle;
            d_ptr->m_dragOffset = QPointF(x, y);
            update();
            return;
        }
    } else if (d_ptr->m_gradientType == QGradient::RadialGradient) {
        QPointF focalPoint = d_ptr->toViewport(d_ptr->m_focalRadial);
        double x = p.x() - focalPoint.x();
        double y = p.y() - focalPoint.y();

        if ((d_ptr->m_handleSize * d_ptr->m_handleSize / 9) > (x * x + y * y)) {
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::FocalRadialHandle;
            d_ptr->m_dragOffset = QPointF(x, y);
            update();
            return;
        }

        QPointF centralPoint = d_ptr->toViewport(d_ptr->m_centralRadial);
        x = p.x() - centralPoint.x();
        y = p.y() - centralPoint.y();

        if ((d_ptr->m_handleSize * d_ptr->m_handleSize / 4) > (x * x + y * y)) {
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::CentralRadialHandle;
            d_ptr->m_dragOffset = QPointF(x, y);
            update();
            return;
        }

        QPointF central = d_ptr->toViewport(d_ptr->m_centralRadial);
        QRectF r = d_ptr->pointRect(central, 2 * d_ptr->m_handleSize / 3);
        QRectF r1(0, r.y(), size().width(), r.height());
        QRectF r2(r.x(), 0, r.width(), r.y());
        QRectF r3(r.x(), r.y() + r.height(), r.width(), size().height() - r.y() - r.height());
        QPointF pF(p.x(), p.y());
        if (r1.contains(pF) || r2.contains(pF) || r3.contains(pF)) {
            x = pF.x() / size().width() - d_ptr->m_centralRadial.x();
            y = pF.y() / size().height() - d_ptr->m_centralRadial.y();
            double clickRadius = sqrt(x * x + y * y);
            //d_ptr->m_radiusOffset = d_ptr->m_radiusRadial - clickRadius;
            d_ptr->m_radiusFactor = d_ptr->m_radiusRadial / clickRadius;
            if (d_ptr->m_radiusFactor == 0)
                d_ptr->m_radiusFactor = 1;
            d_ptr->m_dragRadius = d_ptr->m_radiusRadial;
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::RadiusRadialHandle;
            mouseMoveEvent(e);
            update();
            return;
        }
    } else if (d_ptr->m_gradientType == QGradient::ConicalGradient) {
        QPointF centralPoint = d_ptr->toViewport(d_ptr->m_centralConical);
        double x = p.x() - centralPoint.x();
        double y = p.y() - centralPoint.y();

        if ((d_ptr->m_handleSize * d_ptr->m_handleSize / 4) > (x * x + y * y)) {
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::CentralConicalHandle;
            d_ptr->m_dragOffset = QPointF(x, y);
            update();
            return;
        }
        double radius = size().width();
        if (size().height() < radius)
            radius = size().height();
        radius /= 2;
        double corr = d_ptr->m_handleSize / 3;
        radius -= corr;
        QPointF vp = d_ptr->toViewport(d_ptr->m_centralConical);
        x = p.x() - vp.x();
        y = p.y() - vp.y();
        if (((radius - corr) * (radius - corr) < (x * x + y * y)) &&
            ((radius + corr) * (radius + corr) > (x * x + y * y))) {
            QPointF central = d_ptr->toViewport(d_ptr->m_centralConical);
            QPointF current(e->pos().x(), e->pos().y());
            x = current.x() - central.x();
            y = current.y() - central.y();
            x /= size().width() / 2;
            y /= size().height() / 2;
            double r = sqrt(x * x + y * y);

            double arcSin = asin(y / r);
            double arcCos = acos(x / r);

            double angle = arcCos * 180 / M_PI;
            if (arcSin > 0) {
                angle = -angle;
            }

            d_ptr->m_angleOffset = d_ptr->m_angleConical - angle;
            d_ptr->m_dragAngle = d_ptr->m_angleConical;
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::AngleConicalHandle;
            update();
            return;
        }
    }
}
Exemplo n.º 21
0
rgbColor whittedRayTracer::_L(ray& r, const int& depth) const{
    if(depth > MAX_DEPTH){
        return rgbColor(0.f);
    }

    const intersection isect = parent.intersect(r);
    //return rgbColor(0, isect.debugInfo / 1e8, 0);

    if(!isect.hit){
        return rgbColor(0.f);
    }else if(isect.li != NULL){
        return isect.li->L(r);
    }

    material& mat = isect.li ? *isect.li->getMaterial().get() : *isect.s->getMaterial().get();
    const vec3& normal = isect.shadingNormal;
    const bsdf& bsdf = mat.getBsdf(isect.uv);
    const vec3 wo = worldToBsdf(-r.direction, isect);

    bxdfType sampledType;
    rgbColor colorSum(0.f);

    if(isect.s->getMaterial()->isEmissive()){
        return mat.Le();
    }

    // Diffuse calculations.
    float lightPdf = 0.f;
    for(int i=0; i<parent.numLights(); ++i){
        const light& li = parent.getLight(i);
        if(li.isPointSource()){
            vec3 lightDir;
            const rgbColor Li = li.sampleL(r.origin, lightDir, sampleUniform(), sampleUniform(), lightPdf);
            const float lightDist = norm(lightDir);
            lightDir = normalize(lightDir);

            // Test for shadowing early.
            ray shadowRay(r.origin, lightDir);
            shadowRay.tMax = lightDist;
            if(!parent.intersectB(shadowRay)){
                const vec3 wi = worldToBsdf(lightDir, isect);
                const rgbColor f = bsdf.f(wo, wi, bxdfType(DIFFUSE | GLOSSY | REFLECTION)) + mat.Le();
                colorSum += f * dot(normal, lightDir) * (Li / lightPdf);
            }
        }else{
            rgbColor areaContrib(0.f);

            for(int j=0; j<areaSamples; ++j){
                vec3 lightDir;

                const rgbColor Li = li.sampleL(r.origin, lightDir, sampleUniform(), sampleUniform(), lightPdf);

                ray shadowRay(r.origin, normalize(lightDir));
                shadowRay.tMax = norm(lightDir) + EPSILON;

                if(!parent.intersectB(shadowRay) && li.intersect(shadowRay).hit){
                    lightDir = normalize(lightDir);
                    const vec3 wi = worldToBsdf(lightDir, isect);

                    const rgbColor f = bsdf.f(wo, wi, bxdfType(DIFFUSE | GLOSSY | REFLECTION)) + mat.Le();
                    areaContrib += f * dot(normal, lightDir) * (Li / lightPdf);
                }
            }
            colorSum += areaContrib / (float)areaSamples;
        }
    }

    // Trace specular rays.
    vec3 specDir;
    float pdf;
    const rgbColor fr =
        bsdf.sampleF(sampleUniform(), sampleUniform(), sampleUniform(),
                wo, specDir, bxdfType(GLOSSY | SPECULAR | REFLECTION), sampledType, pdf);

    if(!fr.isBlack()){
        specDir = bsdfToWorld(specDir, isect);
        ray r2(r.origin, specDir);
        colorSum += (fr / pdf) * _L(r2, depth+1) * abs(dot(specDir, normal));
    }

    const rgbColor ft =
        bsdf.sampleF(sampleUniform(), sampleUniform(), sampleUniform(),
                wo, specDir, bxdfType(GLOSSY | SPECULAR | TRANSMISSION), sampledType, pdf);

    if(!ft.isBlack()){
        specDir = bsdfToWorld(specDir, isect);
        ray r2(r.origin, specDir);
        colorSum += (ft / pdf) * _L(r2, depth+1) * abs(dot(specDir, normal));
    }

    if(!isFinite(colorSum.avg())) {
        return ERROR_COLOR;
    } else {
        return colorSum;
    }
}
Exemplo n.º 22
0
void QtGradientWidget::paintEvent(QPaintEvent *e)
{
    Q_UNUSED(e)

    QPainter p(this);

    if (d_ptr->m_backgroundCheckered) {
        int pixSize = 40;
        QPixmap pm(2 * pixSize, 2 * pixSize);

        QPainter pmp(&pm);
        pmp.fillRect(0, 0, pixSize, pixSize, Qt::white);
        pmp.fillRect(pixSize, pixSize, pixSize, pixSize, Qt::white);
        pmp.fillRect(0, pixSize, pixSize, pixSize, Qt::black);
        pmp.fillRect(pixSize, 0, pixSize, pixSize, Qt::black);

        p.setBrushOrigin((size().width() % pixSize + pixSize) / 2, (size().height() % pixSize + pixSize) / 2);
        p.fillRect(rect(), pm);
        p.setBrushOrigin(0, 0);
    }

    QGradient *gradient = 0;
    switch (d_ptr->m_gradientType) {
        case QGradient::LinearGradient:
            gradient = new QLinearGradient(d_ptr->m_startLinear, d_ptr->m_endLinear);
            break;
        case QGradient::RadialGradient:
            gradient = new QRadialGradient(d_ptr->m_centralRadial, d_ptr->m_radiusRadial, d_ptr->m_focalRadial);
            break;
        case QGradient::ConicalGradient:
            gradient = new QConicalGradient(d_ptr->m_centralConical, d_ptr->m_angleConical);
            break;
        default:
            break;
    }
    if (!gradient)
        return;

    gradient->setStops(d_ptr->m_gradientStops);
    gradient->setSpread(d_ptr->m_gradientSpread);

    p.save();
    p.scale(size().width(), size().height());
    p.fillRect(QRect(0, 0, 1, 1), *gradient);
    p.restore();

    p.setRenderHint(QPainter::Antialiasing);

    QColor c = QColor::fromRgbF(0.5, 0.5, 0.5, 0.5);
    QBrush br(c);
    p.setBrush(br);
    QPen pen(Qt::white);
    pen.setWidthF(1);
    p.setPen(pen);
    QPen dragPen = pen;
    dragPen.setWidthF(2);
    if (d_ptr->m_gradientType == QGradient::LinearGradient) {
        p.save();
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::StartLinearHandle)
            p.setPen(dragPen);
        d_ptr->paintPoint(&p, d_ptr->m_startLinear, d_ptr->m_handleSize);
        p.restore();

        p.save();
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::EndLinearHandle)
            p.setPen(dragPen);
        d_ptr->paintPoint(&p, d_ptr->m_endLinear, d_ptr->m_handleSize);
        p.restore();
    } else if (d_ptr->m_gradientType == QGradient::RadialGradient) {
        QPointF central = d_ptr->toViewport(d_ptr->m_centralRadial);

        p.save();
        QRectF r = d_ptr->pointRect(central, 2 * d_ptr->m_handleSize / 3);
        QRectF r1(0, r.y(), size().width(), r.height());
        QRectF r2(r.x(), 0, r.width(), r.y());
        QRectF r3(r.x(), r.y() + r.height(), r.width(), size().height() - r.y() - r.height());
        p.fillRect(r1, c);
        p.fillRect(r2, c);
        p.fillRect(r3, c);
        p.setBrush(Qt::NoBrush);
        p.save();
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::CentralRadialHandle)
            p.setPen(dragPen);
        d_ptr->paintPoint(&p, d_ptr->m_centralRadial, d_ptr->m_handleSize);
        p.restore();

        QRectF rect = QRectF(central.x() - d_ptr->m_radiusRadial * size().width(),
                        central.y() - d_ptr->m_radiusRadial * size().height(),
                        2 * d_ptr->m_radiusRadial * size().width(),
                        2 * d_ptr->m_radiusRadial * size().height());
        p.setClipRect(r1);
        p.setClipRect(r2, Qt::UniteClip);
        p.setClipRect(r3, Qt::UniteClip);
        p.drawEllipse(rect);
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::RadiusRadialHandle) {
            p.save();
            p.setPen(dragPen);
            QRectF rect = QRectF(central.x() - d_ptr->m_radiusRadial / d_ptr->m_radiusFactor * size().width(),
                    central.y() - d_ptr->m_radiusRadial / d_ptr->m_radiusFactor * size().height(),
                    2 * d_ptr->m_radiusRadial / d_ptr->m_radiusFactor * size().width(),
                    2 * d_ptr->m_radiusRadial / d_ptr->m_radiusFactor * size().height());
            p.drawEllipse(rect);

            p.restore();
        }
        p.restore();

        p.save();
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::FocalRadialHandle)
            p.setPen(dragPen);
        d_ptr->paintPoint(&p, d_ptr->m_focalRadial, 2 * d_ptr->m_handleSize / 3);
        p.restore();
    } else if (d_ptr->m_gradientType == QGradient::ConicalGradient) {
        double radius = size().width();
        if (size().height() < radius)
            radius = size().height();
        radius /= 2;
        double corr = d_ptr->m_handleSize / 3;
        radius -= corr;
        QPointF central = d_ptr->toViewport(d_ptr->m_centralConical);

        p.save();
        p.setBrush(Qt::NoBrush);
        QPen pen2(c);
        pen2.setWidthF(2 * d_ptr->m_handleSize / 3);
        p.setPen(pen2);
        p.drawEllipse(d_ptr->pointRect(central, 2 * radius));
        p.restore();

        p.save();
        p.setBrush(Qt::NoBrush);
        int pointCount = 2;
        for (int i = 0; i < pointCount; i++) {
            QPointF ang(cos(M_PI * (i * 180.0 / pointCount + d_ptr->m_angleConical) / 180) * size().width() / 2,
                    -sin(M_PI * (i * 180.0 / pointCount + d_ptr->m_angleConical) / 180) * size().height() / 2);
            double mod = sqrt(ang.x() * ang.x() + ang.y() * ang.y());
            p.drawLine(QPointF(central.x() + ang.x() * (radius - corr) / mod,
                        central.y() + ang.y() * (radius - corr) / mod),
                    QPointF(central.x() + ang.x() * (radius + corr) / mod,
                        central.y() + ang.y() * (radius + corr) / mod));
            p.drawLine(QPointF(central.x() - ang.x() * (radius - corr) / mod,
                        central.y() - ang.y() * (radius - corr) / mod),
                    QPointF(central.x() - ang.x() * (radius + corr) / mod,
                        central.y() - ang.y() * (radius + corr) / mod));
        }
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::AngleConicalHandle) {
            p.save();
            p.setPen(dragPen);
            QPointF ang(cos(M_PI * (d_ptr->m_angleConical - d_ptr->m_angleOffset) / 180) * size().width() / 2,
                    -sin(M_PI * (d_ptr->m_angleConical - d_ptr->m_angleOffset) / 180) * size().height() / 2);
            double mod = sqrt(ang.x() * ang.x() + ang.y() * ang.y());
            p.drawLine(QPointF(central.x() + ang.x() * (radius - corr) / mod,
                        central.y() + ang.y() * (radius - corr) / mod),
                    QPointF(central.x() + ang.x() * (radius + corr) / mod,
                        central.y() + ang.y() * (radius + corr) / mod));
            p.restore();
        }

        p.restore();

        p.save();
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::CentralConicalHandle)
            p.setPen(dragPen);
        d_ptr->paintPoint(&p, d_ptr->m_centralConical, d_ptr->m_handleSize);
        p.restore();

    }

    delete gradient;
}
Exemplo n.º 23
0
void runScenario()
{
    // set codec for C strings to 0, enforcing Latin1
    QTextCodec::setCodecForCStrings(0);
    QVERIFY(!QTextCodec::codecForCStrings());

    QLatin1Literal l1literal(LITERAL);
    QLatin1String l1string(LITERAL);
    QString string(l1string);
    QStringRef stringref(&string, 2, 10);
    QLatin1Char achar('c');
    QString r2(QLatin1String(LITERAL LITERAL));
    QString r;

    r = l1literal Q l1literal;
    QCOMPARE(r, r2);
    r = string P string;
    QCOMPARE(r, r2);
    r = stringref Q stringref;
    QCOMPARE(r, QString(stringref.toString() + stringref.toString()));
    r = string Q l1literal;
    QCOMPARE(r, r2);
    r = string P l1string;
    QCOMPARE(r, r2);
    r = string + achar;
    QCOMPARE(r, QString(string P achar));
    r = achar + string;
    QCOMPARE(r, QString(achar P string));
#ifndef QT_NO_CAST_FROM_ASCII
    r = string P LITERAL;
    QCOMPARE(r, r2);
    r = LITERAL P string;
    QCOMPARE(r, r2);

    QByteArray ba = QByteArray(LITERAL);
    r = ba P string;
    QCOMPARE(r, r2);
    r = string P ba;
    QCOMPARE(r, r2);

    static const char badata[] = LITERAL_EXTRA;
    ba = QByteArray::fromRawData(badata, LITERAL_LEN);
    r = ba P string;
    QCOMPARE(r, r2);
    r = string P ba;
    QCOMPARE(r, r2);

    // now test with codec for C strings set
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
    QVERIFY(QTextCodec::codecForCStrings());
    QCOMPARE(QTextCodec::codecForCStrings()->name(), QByteArray("UTF-8"));

    string = QString::fromUtf8(UTF8_LITERAL);
    r2 = QString::fromUtf8(UTF8_LITERAL UTF8_LITERAL);
    ba = UTF8_LITERAL;

    r = string P UTF8_LITERAL;
    QCOMPARE(r.size(), r2.size());
    QCOMPARE(r, r2);
    r = UTF8_LITERAL P string;
    QCOMPARE(r, r2);
    r = ba P string;
    QCOMPARE(r, r2);
    r = string P ba;
    QCOMPARE(r, r2);

    ba = QByteArray::fromRawData(UTF8_LITERAL_EXTRA, UTF8_LITERAL_LEN);
    r = ba P string;
    QCOMPARE(r, r2);
    r = string P ba;
    QCOMPARE(r, r2);

    ba = QByteArray(); // empty
    r = ba P string;
    QCOMPARE(r, string);
    r = string P ba;
    QCOMPARE(r, string);

    const char *zero = 0;
    r = string P zero;
    QCOMPARE(r, string);
    r = zero P string;
    QCOMPARE(r, string);
#endif

    string = QString::fromLatin1(LITERAL);
    QCOMPARE(QByteArray(qPrintable(string P string)), QByteArray(string.toLatin1() + string.toLatin1()));



    //QByteArray
    {
        QByteArray ba = LITERAL;
        QByteArray superba = ba P ba P LITERAL;
        QCOMPARE(superba, QByteArray(LITERAL LITERAL LITERAL));

        QByteArray testWith0 = ba P "test\0with\0zero" P ba;
        QCOMPARE(testWith0, QByteArray(LITERAL "test" LITERAL));

        QByteArray ba2 = ba P '\0' + LITERAL;
        QCOMPARE(ba2, QByteArray(LITERAL "\0" LITERAL, ba.size()*2+1));

        const char *mmh = "test\0foo";
        QCOMPARE(QByteArray(ba P mmh P ba), testWith0);

        QByteArray raw = QByteArray::fromRawData(UTF8_LITERAL_EXTRA, UTF8_LITERAL_LEN);
        QByteArray r = "hello" P raw;
        QByteArray r2 = "hello" UTF8_LITERAL;
        QCOMPARE(r, r2);
        r2 = QByteArray("hello\0") P UTF8_LITERAL;
        QCOMPARE(r, r2);

        const char *zero = 0;
        r = ba P zero;
        QCOMPARE(r, ba);
        r = zero P ba;
        QCOMPARE(r, ba);
    }

    //operator QString  +=
    {
        QString str = QString::fromUtf8(UTF8_LITERAL);
        str +=  QLatin1String(LITERAL) P str;
        QCOMPARE(str, QString::fromUtf8(UTF8_LITERAL LITERAL UTF8_LITERAL));
#ifndef QT_NO_CAST_FROM_ASCII
        str = (QString::fromUtf8(UTF8_LITERAL) += QLatin1String(LITERAL) P UTF8_LITERAL);
        QCOMPARE(str, QString::fromUtf8(UTF8_LITERAL LITERAL UTF8_LITERAL));
#endif
    }

    //operator QByteArray  +=
    {
        QByteArray ba = UTF8_LITERAL;
        ba +=  QByteArray(LITERAL) P UTF8_LITERAL;
        QCOMPARE(ba, QByteArray(UTF8_LITERAL LITERAL UTF8_LITERAL));
        ba += LITERAL P QByteArray::fromRawData(UTF8_LITERAL_EXTRA, UTF8_LITERAL_LEN);
        QCOMPARE(ba, QByteArray(UTF8_LITERAL LITERAL UTF8_LITERAL LITERAL UTF8_LITERAL));
        QByteArray withZero = QByteArray(LITERAL "\0" LITERAL, LITERAL_LEN*2+1);
        QByteArray ba2 = withZero;
        ba2 += ba2 P withZero;
        QCOMPARE(ba2, QByteArray(withZero + withZero + withZero));
#ifndef QT_NO_CAST_TO_ASCII
        ba = UTF8_LITERAL;
        ba2 = (ba += QLatin1String(LITERAL) + QString::fromUtf8(UTF8_LITERAL));
        QCOMPARE(ba2, ba);
        QCOMPARE(ba, QByteArray(UTF8_LITERAL LITERAL UTF8_LITERAL));
#endif
    }

}
Exemplo n.º 24
0
void runScenario()
{
    // this code is latin1. TODO: replace it with the utf8 block below, once
    // strings default to utf8.
    QLatin1String l1string(LITERAL);
    QString string(l1string);
    QStringRef stringref(&string, 2, 10);
    QLatin1Char achar('c');
    QChar::SpecialCharacter special(QChar::Nbsp);
    QString r2(QLatin1String(LITERAL LITERAL));
    QString r3 = QString::fromUtf8(UTF8_LITERAL UTF8_LITERAL);
    QString r;

    r = string P string;
    QCOMPARE(r, r2);
    r = stringref Q stringref;
    QCOMPARE(r, QString(stringref.toString() + stringref.toString()));
    r = string P l1string;
    QCOMPARE(r, r2);
    r = string Q QStringLiteral(LITERAL);
    QCOMPARE(r, r2);
    r = QStringLiteral(LITERAL) Q string;
    QCOMPARE(r, r2);
    r = l1string Q QStringLiteral(LITERAL);
    QCOMPARE(r, r2);
    r = string + achar;
    QCOMPARE(r, QString(string P achar));
    r = achar + string;
    QCOMPARE(r, QString(achar P string));
    r = special + string;
    QCOMPARE(r, QString(special P string));

#ifdef Q_COMPILER_UNICODE_STRINGS
    r = QStringLiteral(UNICODE_LITERAL);
    r = r Q QStringLiteral(UNICODE_LITERAL);
    QCOMPARE(r, r3);
#endif

#ifndef QT_NO_CAST_FROM_ASCII
    r = string P LITERAL;
    QCOMPARE(r, r2);
    r = LITERAL P string;
    QCOMPARE(r, r2);

    QByteArray ba = QByteArray(LITERAL);
    r = ba P string;
    QCOMPARE(r, r2);
    r = string P ba;
    QCOMPARE(r, r2);

    r = string P QByteArrayLiteral(LITERAL);
    QCOMPARE(r, r2);
    r = QByteArrayLiteral(LITERAL) P string;
    QCOMPARE(r, r2);

    static const char badata[] = LITERAL_EXTRA;
    ba = QByteArray::fromRawData(badata, LITERAL_LEN);
    r = ba P string;
    QCOMPARE(r, r2);
    r = string P ba;
    QCOMPARE(r, r2);

    string = QString::fromUtf8(UTF8_LITERAL);
    ba = UTF8_LITERAL;

    r = string P UTF8_LITERAL;
    QCOMPARE(r.size(), r3.size());
    QCOMPARE(r, r3);
    r = UTF8_LITERAL P string;
    QCOMPARE(r, r3);
    r = ba P string;
    QCOMPARE(r, r3);
    r = string P ba;
    QCOMPARE(r, r3);

    ba = QByteArray::fromRawData(UTF8_LITERAL_EXTRA, UTF8_LITERAL_LEN);
    r = ba P string;
    QCOMPARE(r, r3);
    r = string P ba;
    QCOMPARE(r, r3);

    ba = QByteArray(); // empty
    r = ba P string;
    QCOMPARE(r, string);
    r = string P ba;
    QCOMPARE(r, string);

    const char *zero = 0;
    r = string P zero;
    QCOMPARE(r, string);
    r = zero P string;
    QCOMPARE(r, string);
#endif

    string = QString::fromLatin1(LITERAL);
    QCOMPARE(QByteArray(qPrintable(string P string)), QByteArray(string.toLatin1() + string.toLatin1()));



    //QByteArray
    {
        QByteArray ba = LITERAL;
        QByteArray superba = ba P ba P LITERAL;
        QCOMPARE(superba, QByteArray(LITERAL LITERAL LITERAL));

        ba = QByteArrayLiteral(LITERAL);
        QCOMPARE(ba, QByteArray(LITERAL));
        superba = ba P QByteArrayLiteral(LITERAL) P LITERAL;
        QCOMPARE(superba, QByteArray(LITERAL LITERAL LITERAL));

        QByteArray testWith0 = ba P "test\0with\0zero" P ba;
        QCOMPARE(testWith0, QByteArray(LITERAL "test" LITERAL));

        QByteArray ba2 = ba P '\0' + LITERAL;
        QCOMPARE(ba2, QByteArray(LITERAL "\0" LITERAL, ba.size()*2+1));

        const char *mmh = "test\0foo";
        QCOMPARE(QByteArray(ba P mmh P ba), testWith0);

        QByteArray raw = QByteArray::fromRawData(UTF8_LITERAL_EXTRA, UTF8_LITERAL_LEN);
        QByteArray r = "hello" P raw;
        QByteArray r2 = "hello" UTF8_LITERAL;
        QCOMPARE(r, r2);
        r2 = QByteArray("hello\0") P UTF8_LITERAL;
        QCOMPARE(r, r2);

        const char *zero = 0;
        r = ba P zero;
        QCOMPARE(r, ba);
        r = zero P ba;
        QCOMPARE(r, ba);
    }

    //operator QString  +=
    {
        QString str = QString::fromUtf8(UTF8_LITERAL);
        str +=  QLatin1String(LITERAL) P str;
        QCOMPARE(str, QString::fromUtf8(UTF8_LITERAL LITERAL UTF8_LITERAL));
#ifndef QT_NO_CAST_FROM_ASCII
        str = (QString::fromUtf8(UTF8_LITERAL) += QLatin1String(LITERAL) P UTF8_LITERAL);
        QCOMPARE(str, QString::fromUtf8(UTF8_LITERAL LITERAL UTF8_LITERAL));
#endif

        QString str2 = QString::fromUtf8(UTF8_LITERAL);
        QString str2_e = QString::fromUtf8(UTF8_LITERAL);
        const char * nullData = 0;
        str2 += QLatin1String(nullData) P str2;
        str2_e += QLatin1String("") P str2_e;
        QCOMPARE(str2, str2_e);
    }

    //operator QByteArray  +=
    {
        QByteArray ba = UTF8_LITERAL;
        ba +=  QByteArray(LITERAL) P UTF8_LITERAL;
        QCOMPARE(ba, QByteArray(UTF8_LITERAL LITERAL UTF8_LITERAL));
        ba += LITERAL P QByteArray::fromRawData(UTF8_LITERAL_EXTRA, UTF8_LITERAL_LEN);
        QCOMPARE(ba, QByteArray(UTF8_LITERAL LITERAL UTF8_LITERAL LITERAL UTF8_LITERAL));
        QByteArray withZero = QByteArray(LITERAL "\0" LITERAL, LITERAL_LEN*2+1);
        QByteArray ba2 = withZero;
        ba2 += ba2 P withZero;
        QCOMPARE(ba2, QByteArray(withZero + withZero + withZero));
#ifndef QT_NO_CAST_TO_ASCII
        ba = UTF8_LITERAL;
        ba2 = (ba += QLatin1String(LITERAL) + QString::fromUtf8(UTF8_LITERAL));
        QCOMPARE(ba2, ba);
        QCOMPARE(ba, QByteArray(UTF8_LITERAL LITERAL UTF8_LITERAL));
#endif
    }

}
int main(int argc, char* argv[])
{
  int q; //q*q will be all the process we have
  int mypid,mysize;
    int i,j,k,l;
  int my_row,my_col;
  int myIdInRowGroup, myIdInColGroup;
    int rows=pow(2,10);
    int cols=pow(2,10);
    int blockSize; //this will store the size of each submatrix that is on each process
    double *localSubmatrixM;
    double *localSubmatrixN;
    double **localM;
    double **localN;
    double **subMatrixToSendM;  // this is the data to be scattered to each process
    double **subMatrixToSendN;
    double **localSubmatrixNNew; // this is the data to be received on the local.
    double **localSubmatrixMNew;
    double **localTempMNew;
    double *localTempM;
    double *localTempN;
  MPI_Init(&argc,&argv);
  MPI_Comm_size(MPI_COMM_WORLD,&mysize);
  MPI_Comm_rank(MPI_COMM_WORLD,&mypid);
  q=(int)sqrt(mysize);
    //this will will be submatrix on each process that store the Result.
    double **subResult;
    double **M;
    double **N;
    double **R;
    double *bigArrayForM;
    double *bigArrayForN;
    double sstart,sfinish,pstart,pfinish,dstart,dfinish;//store serialized multiplication and parallel multiplication time and distribution time of the data.
    
  //printf("this is my q: %d",q);
  MPI_Comm my_row_comm;
  MPI_Comm my_col_comm;


    
    //mypid is the pif in mpi_Comm_world
    my_row=mypid/q;
    my_col=mypid%q;
    blockSize=rows/q;
  MPI_Comm_split(MPI_COMM_WORLD,my_row,mypid,&my_row_comm);
    MPI_Comm_split(MPI_COMM_WORLD,my_col,mypid,&my_col_comm);
    double randomNumber;
   
   //to make the subresult matrix that reside on each process.
    subResult=(double **) malloc(blockSize*sizeof(double*));
    for(l=0;l<blockSize;l++)
    {
        subResult[l]=(double *)malloc(blockSize*sizeof(double));
    }
    for(i=0;i<blockSize;i++){
         for(j=0;j<blockSize;j++)
         {
            subResult[i][j]=0;
         }           
    }

    localSubmatrixM=(double *)malloc(blockSize*blockSize*sizeof(double));
    localSubmatrixN=(double *)malloc(blockSize*blockSize*sizeof(double));
    localTempM=(double *)malloc(blockSize*blockSize*sizeof(double));
    localTempN=(double *)malloc(blockSize*blockSize*sizeof(double));
    localM=(double **)malloc(blockSize*sizeof(double *));
    localN=(double **)malloc(blockSize*sizeof(double *));
    localTempMNew=(double **)malloc(blockSize*sizeof(double *));
    for(i=0;i<blockSize;i++)
    {
      localTempMNew[i]=(double*)malloc(blockSize*sizeof(double));
    }
    for(i=0;i<blockSize;i++)
    {
      localM[i]=(double *)malloc(blockSize*sizeof(double));
      localN[i]=(double *)malloc(blockSize*sizeof(double));
    }
    for(i=0;i<blockSize;i++)
    {
      for(j=0;j<blockSize;j++)
      {
        localM[i][j]=0;
        localN[i][j]=0;
      }
    }
    //trying to change the way of doing this, trying to scatetr the big matrix row by row hopefully
    subMatrixToSendM=(double **)malloc(blockSize*sizeof(double *));
    subMatrixToSendN=(double **)malloc(blockSize*sizeof(double *));
    for(i=0;i<blockSize;i++)
    {
      subMatrixToSendM[i]=(double *)malloc(blockSize*sizeof(double));
      subMatrixToSendN[i]=(double *)malloc(blockSize*sizeof(double));
    }
    for(i=0;i<blockSize;i++)
    {
      for(j=0;j<blockSize;j++)
      {
        subMatrixToSendM[i][j]=0;
        subMatrixToSendN[i][j]=0;
      }
    }

    localSubmatrixMNew=(double **)malloc(blockSize*sizeof(double *));
    localSubmatrixNNew=(double **)malloc(blockSize*sizeof(double *));
    for(i=0;i<blockSize;i++)
    {
      localSubmatrixMNew[i]=(double *)malloc(blockSize*sizeof(double));
      localSubmatrixNNew[i]=(double *)malloc(blockSize*sizeof(double));
    }
    for(i=0;i<blockSize;i++)
    {
      for(j=0;j<blockSize;j++)
      {
        localSubmatrixMNew[i][j]=0;
        localSubmatrixNNew[i][j]=0;
      }
    }
  /*  if(mypid<q*q)
    {
      MPI_Comm_rank(my_row_comm,&myIdInRowGroup);
      MPI_Comm_rank(my_col_comm,&myIdInColGroup);
      printf("my comm world Id: %d \n",mypid);
      printf("my row Id: %d \n",myIdInRowGroup);
      printf("my col Id: %d \n",myIdInColGroup);
      printf("\n");
    }*/
       
        if(mypid==0) //make the first process generete the M,N matrix but not timing this, and make process0 scatter the result but not timing the scatter time.
        {
          
          int step;
          //just need to malloc in proceess1 other process don't need to malloc this.
          bigArrayForM=(double*) malloc(rows*rows*sizeof(double));
          bigArrayForN=(double*) malloc(rows*rows*sizeof(double));
          
            M=(double **) malloc(rows*sizeof(double *));
            for(i=0;i<rows;i++)
            {
                M[i]=(double *) malloc(cols*sizeof(double));
            }
            N=(double **) malloc(rows*sizeof(double *));
            for(i=0;i<rows;i++)
            {
                N[i]=(double *) malloc(cols*sizeof(double));
            }

             for(i=0;i<rows;i++){
                 for(j=0;j<cols;j++)
                 {
                    N[i][j]=r1()+r2();
                    //printf(" N%lf ",N[i][j]);
                 }
                 //printf("\n"); 
             }
              for(i=0;i<rows;i++){
                 for(j=0;j<cols;j++)
                 {
                    M[i][j]=r1()+r2();
                    //printf(" M%lf ",M[i][j]);

                 }
                  //printf("\n"); 
             }
            //this only allocate on first process to test the time of the serialized multiplication
            R=(double **) malloc(rows*sizeof(double *));
            for(i=0;i<rows;i++)
            {
                R[i]=(double *) malloc(cols*sizeof(double));
            }
             for(i=0;i<rows;i++){
                 for(j=0;j<cols;j++)
                 {
                    R[i][j]=0.0;

                 }
             }
             sstart=MPI_Wtime();
              for(i=0;i<rows;i++)
              {
                for(j=0;j<cols;j++)
                {
                  for(k=0;k<cols;k++) //here can be cols or rows it does not matter ,since teh matrix is a square here
                  {
                    R[i][j]=R[i][j]+M[i][k]*N[k][j];
                    
                  }
                  //printf(" %lf ",R[i][j]);
                }
                //printf("\n");
              }
              sfinish=MPI_Wtime();
              //after caculate the serilized version free the memory,but still need to keep it there for testing.
          /*     for(i=0;i<rows;i++)
            {
                free(R[i]);
            }
            free(R);*/
            //free the memory

              printf("time took for serialized multiplication of size %d * %d matrix is: %lf \n",rows,cols,sfinish-sstart);
             //this will put M,N in contiguous manner, so we can send them off to other process using MPI_Scatter, this part is pretty tricky but beautiful.
              dstart=MPI_Wtime();
            for(step=0;step<q*q;step++)
            {
                for(i=0;i<blockSize*blockSize;i++)
                {
                    bigArrayForM[blockSize*blockSize*step+i]=M[blockSize*(step/q)+i/blockSize][blockSize*(step%q)+i%blockSize];
                }
            }
              for(step=0;step<q*q;step++)
            {
                for(i=0;i<blockSize*blockSize;i++)
                {
                   bigArrayForN[blockSize*blockSize*step+i]=N[blockSize*(step/q)+i/blockSize][blockSize*(step%q)+i%blockSize];
                }
            }  
        /*     for(step=0;step<q*q;step++)
             {
              for(i=0;i<blockSize;i++)
              {
                for(j=0;j<blockSize;j++)
                {
                  subMatrixToSendM[i][j]=M[blockSize*(step/q)+i][blockSize*(step%q)+j];
                }
              }
             }
            for(step=0;step<q*q;step++)
             {
              for(i=0;i<blockSize;i++)
              {
                for(j=0;j<blockSize;j++)
                {
                  subMatrixToSendN[i][j]=N[blockSize*(step/q)+i][blockSize*(step%q)+j];
                }
              }
             }*/

          /*  for(i=0;i<q;i++)
            {
              MPI_Scatter(subMatrixToSendM[i],blockSize,MPI_DOUBLE,localSubmatrixMNew[i],blockSize,MPI_DOUBLE,0,MPI_COMM_WORLD);
              MPI_Scatter(subMatrixToSendN[i],blockSize,MPI_DOUBLE,localSubmatrixNNew[i],blockSize,MPI_DOUBLE,0,MPI_COMM_WORLD);
            }*/
            //scatter M and N
            MPI_Scatter(bigArrayForM,blockSize*blockSize,MPI_DOUBLE,localSubmatrixM,blockSize*blockSize,MPI_DOUBLE,0,MPI_COMM_WORLD);
            MPI_Scatter(bigArrayForN,blockSize*blockSize,MPI_DOUBLE,localSubmatrixN,blockSize*blockSize,MPI_DOUBLE,0,MPI_COMM_WORLD);
           /* for(i=0;i<blockSize*blockSize;i++)
            {
                printf("%lf in process ID: %d: \n",localSubmatrixM[i],mypid);
            }*/
           //the above block is the most delicate part to make it successful!

           }
        else
        {

            MPI_Scatter(bigArrayForM,blockSize*blockSize,MPI_DOUBLE,localSubmatrixM,blockSize*blockSize,MPI_DOUBLE,0,MPI_COMM_WORLD);
            MPI_Scatter(bigArrayForN,blockSize*blockSize,MPI_DOUBLE,localSubmatrixN,blockSize*blockSize,MPI_DOUBLE,0,MPI_COMM_WORLD);
       /*   for(i=0;i<q;i++)
            {
              MPI_Scatter(subMatrixToSendM[i],blockSize,MPI_DOUBLE,localSubmatrixMNew[i],blockSize,MPI_DOUBLE,0,MPI_COMM_WORLD);
              MPI_Scatter(subMatrixToSendN[i],blockSize,MPI_DOUBLE,localSubmatrixNNew[i],blockSize,MPI_DOUBLE,0,MPI_COMM_WORLD);
            }*/
    
          /*  for(i=0;i<blockSize*blockSize;i++)
            {
                printf("%lf in process ID: %d: \n",localSubmatrixM[i],mypid);
            }*/
        }
        MPI_Barrier(MPI_COMM_WORLD);
        dfinish=MPI_Wtime();
        
   /*     if(mypid==1)
        {
          for(i=0;i<blockSize*blockSize;i++)
          {
            
              printf("subM is %lf ",localSubmatrixN[i]);
            
            printf("\n");
          }
        }*/
       
       //beginning of the fox algorithms, call MPI_BARRIER make sure each process is on the same page
        MPI_Comm_rank(my_row_comm,&myIdInRowGroup);
        MPI_Comm_rank(my_col_comm,&myIdInColGroup);

        //we need to q step to finish the calculation, which q is how many process we have on each row, and also it is how many process we have on each column.
        //now for each of the process, do the regular matrix multiplication
        MPI_Barrier(MPI_COMM_WORLD);
        int transferStep;
         
        
         pstart=MPI_Wtime();
        
        for(transferStep=0;transferStep<q;transferStep++)
        {
          
            //BroadCast M and keep N as what it is. I think for N we don't need a localTempNForIt, it should record all the data by itself
              if(myIdInRowGroup==((mypid/q)+transferStep)%q)
              {
                for(i=0;i<blockSize;i++)
                {
                  //in this way you will still keep the data youw want on each process
                   //localTempMNew[i]=localSubmatrixMNew[i];
                  for(j=0;j<blockSize;j++)
                  {
                    localTempMNew[i][j]=localSubmatrixM[i*blockSize+j];
                  }
                  MPI_Bcast(localTempMNew[i],blockSize,MPI_DOUBLE,myIdInRowGroup,my_row_comm);

                }
         
                
              }
               else
               {
                for(i=0;i<blockSize;i++)
                {
                   for(j=0;j<blockSize;j++)
                  {
                    localTempMNew[i][j]=localSubmatrixM[i*blockSize+j];
                  }
                  MPI_Bcast(localTempMNew[i],blockSize,MPI_DOUBLE,((mypid/q)+transferStep)%q,my_row_comm);

                   //MPI_Bcast(localTempMNew[i],blockSize,MPI_DOUBLE,((mypid/q)+transferStep)%q,my_row_comm);
                }
               }
         /*   if(mypid/q==1)
            {
                printf("this is the local temp pid %d in step %d: \n",mypid,transferStep);
                for(i=0;i<blockSize*blockSize;i++)
                {
                    printf(" %lf ",localTempM[i]);
                }
                printf("\n");
            }*/
        /*    if(mypid/q==0)
            {
                printf("this is the local temp pid %d in step %d: \n",mypid,transferStep);
                for(i=0;i<blockSize*blockSize;i++)
                {
                    printf(" %lf ",localSubmatrixN[i]);
                }
                printf("\n");

            }*/

           //now make serialize multiplication
      /*     for(i=0;i<blockSize;i++)
              {
                
                for(j=0;j<blockSize;j++)
                {*/
                    //so need the ith row of subA and jth col of subB multiply together
                  if(transferStep==0) //only do this at the first step since need to initialize the localSubMatrixNNew with the localSubmatixN
                  {
                     for(k=0;k<blockSize;k++)
                    { //and k will be used as a tag
                     for(i=0;i<blockSize;i++)
                        {
                        localSubmatrixNNew[k][i]=localSubmatrixN[k*blockSize+i];
                        }
                    }
                   }
                  for(i=0;i<blockSize*blockSize;i++)
                  {
                    
                        for(l=0;l<blockSize;l++)
                        {
                            //this step is very delicate.
                  
                         //subResult[i/blockSize][i%blockSize] =subResult[i/blockSize][i%blockSize]+localTempM[(i/blockSize)*blockSize+l]*localSubmatrixN[l*blockSize+(i%blockSize)];
                          subResult[i/blockSize][i%blockSize]=subResult[i/blockSize][i%blockSize]+localTempMNew[i/blockSize][l]*localSubmatrixNNew[l][i%blockSize];
                         /* printf(" %lf \n",subResult[i/q][i%q]);*/
                        }
                    
                    
                  }
             
            /*    }
              }*/
              

/*
        if(mypid==0)
        {
            printf("Here is the result: \n");
        for(i=0;i<blockSize;i++)
        {
            for(j=0;j<blockSize;j++)
            {
               printf(" %lf ",subResult[i][j]);
            }
            printf("\n");
        }
        }*/

    /*             if(mypid==0)
        {
            printf("Here is the result: \n");
        for(i=0;i<blockSize;i++)
        {
            for(j=0;j<blockSize;j++)
            {
               printf(" %lf ",subResult[i][j]);
            }
            printf("\n");
        }
        }*/
            //for matrix N we can use BroadCasting, we have to use send receive, since now the all the process in the same column get the same data
          for(k=0;k<blockSize;k++)
          { //and k will be used as a tag
       
            if(myIdInColGroup!=0)
            {
                //0 here is the tag for send and receive
            //MPI_Send(localSubmatrixN,blockSize*blockSize,MPI_DOUBLE,myIdInColGroup-1,0,my_col_comm);
              MPI_Send(localSubmatrixNNew[k],blockSize,MPI_DOUBLE,myIdInColGroup-1,k,my_col_comm);
             }
             else
            {
             //MPI_Send(localSubmatrixN,blockSize*blockSize,MPI_DOUBLE,q-1,0,my_col_comm);
              MPI_Send(localSubmatrixNNew[k],blockSize,MPI_DOUBLE,q-1,k,my_col_comm);
            }
            //now need to receive
            if(myIdInColGroup!=q-1)
            {
                //MPI_Recv(localSubmatrixN,blockSize*blockSize,MPI_DOUBLE,myIdInColGroup+1,0,my_col_comm,MPI_STATUS_IGNORE);
              MPI_Recv(localSubmatrixNNew[k],blockSize,MPI_DOUBLE,myIdInColGroup+1,k,my_col_comm,MPI_STATUS_IGNORE);
            }
            else
            {
                //MPI_Recv(localSubmatrixN,blockSize*blockSize,MPI_DOUBLE,0,0,my_col_comm,MPI_STATUS_IGNORE);
              MPI_Recv(localSubmatrixNNew[k],blockSize,MPI_DOUBLE,0,k,my_col_comm,MPI_STATUS_IGNORE);
            }
          }
      /*    if(mypid==2&&transferStep==1)
          {
            for(j=0;j<blockSize;j++)
            {
              printf("test: %lf",localSubmatrixNNew[0][j]);
            }
            printf("\n");
          }*/

 
           MPI_Barrier(MPI_COMM_WORLD);
        }
        //ok now, after all the multiplication, we should print out the local result
        MPI_Barrier(MPI_COMM_WORLD);
        pfinish=MPI_Wtime();

        if(mypid==0)
        {
           /* printf("Here is the result: \n");
        for(i=0;i<blockSize;i++)
        {
            for(j=0;j<blockSize;j++)
            {
               printf(" %lf ",subResult[i][j]);
            }
            printf("\n");
        }*/printf("distribution time for parallel multiplication of size %d * %d matrix to %d processes is : %lf seconds\n",rows,cols,mysize,dfinish-dstart);
            printf("calculation time took for parallel multiplication of size %d * %d matrix with %d processes is : %lf seconds\n",rows,cols,mysize,pfinish-pstart);
            printf("total  time of size %d * %d matrix to %d processes is: %lf seconds\n",rows,cols,mysize,dfinish-dstart+pfinish-pstart);

            for(i=0;i<blockSize;i++)
            {
              for(j=0;j<blockSize;j++)
              {
                if(R[i][j]-subResult[i][j]>=0.1)
                {

                  printf("the value not match on row %d, column %d ,%lf \n",i,j,subResult[i][j]);
                }
              }
            }

            printf("if there is no sentence like the value not match printed here, it means our parallel result is correct!! \n");
          
             

        }

        //only test the first block in process 0 and I think it should be good enough to see if we did in a good way.


      
 /*     if(myIdInRowGroup==0)
      {
           srand(time(NULL)+mypid);
           randomNumber=r2();
           
         printf("grouprow: %d ,the number I generated is : %lf \n",my_row,randomNumber);
           MPI_Bcast(&randomNumber,1,MPI_DOUBLE,0,my_row_comm);
           
      }
      else
      {
        MPI_Bcast(&randomNumber,1,MPI_DOUBLE,0,my_row_comm);
      }
      if(myIdInRowGroup!=0)
      {
      printf("my rowGroup is : %d the number I have is : %lf \n",my_row,randomNumber);
      
        }
*/


    MPI_Finalize();
    exit(0);

}
doublevar Molecular_system::calcLoc(Sample_point * sample) {
  int nions=sample->ionSize();
  int nelectrons=sample->electronSize();

  //cout << "Calculating local energy\n";

  Array1 <doublevar> R(5);
  doublevar pot=0;
  
  doublevar elecIon=0;
  sample->updateEIDist();
  sample->updateEEDist();

  for(int e=0; e< nelectrons; e++)
  {
    for(int i=0; i < nions; i++)
    {

      sample->getEIDist(e,i, R);
      elecIon+=sample->getIonCharge(i)/R(0);
    }
  }
  elecIon*=-1;
  pot+=elecIon;

  //cout << "elec-ion: " << elecIon << endl;
  Array1 <doublevar> r1(3), r2(3);
  doublevar IonIon=0;
  for(int i=0; i< nions; i++)
  {
    sample->getIonPos(i,r1);
    //cout << i << "   " << r1(2) << endl;
    for(int j=0; j<i; j++)
    {
      sample->getIonPos(j,r2);
      doublevar r=sqrt( (r1(0)-r2(0))*(r1(0)-r2(0))
                        + (r1(1)-r2(1))*(r1(1)-r2(1))
                        + (r1(2)-r2(2))*(r1(2)-r2(2)));
      IonIon+=sample->getIonCharge(i)*sample->getIonCharge(j)/r;
    }
  }
  pot+=IonIon;
  
  //cout << "Ion-ion: " << IonIon << endl;

  doublevar elecElec=0;
  Array1 <doublevar> R2(5);
  for(int i=0; i< nelectrons; i++)
  {
    for(int j=0; j<i; j++)
    {
      sample->getEEDist(j,i,R2);
      elecElec+= 1/R2(0);
    }
  }
  pot+=elecElec;
  //cout << "elec-elec: " << elecElec << endl;
  //cout << "pot " << pot << endl;

  doublevar fieldPot=0;
  Array1 <doublevar> pos(3);
  for(int e=0; e< nelectrons; e++) {
    sample->getElectronPos(e,pos);
    for(int d=0; d< 3; d++) 
      fieldPot-=electric_field(d)*pos(d);
  }
  for(int i=0; i< nions; i++) {
    sample->getIonPos(i,pos);
    for(int d=0; d< 3; d++) 
      fieldPot+=sample->getIonCharge(i)*electric_field(d)*pos(d);
  }

  pot+=fieldPot;

  return pot;
}
Exemplo n.º 27
0
void eval(Plan_t *plan){
    PhysicalOp_t * root = plan->Root();
    
    cout<<"\nPhysical Operator tree:\n\n";
    PrintOps(root,0 );
    cout<<endl<<endl;
    
//Mubase initialisation

    cout << "\n STARTING MUBASE\n";

    DiskManager::createDB("mydb.txt", 20);
    StorageManager::initDB("mydb.txt");
    DiskManager::openDB("mydb.txt");

    //Create Relations
    cout << "\nCreating Relations\n";
    const short int numAttrs1 = 4;
    short int attrType1[numAttrs1] = {1, 4, 4, 2};
    short int sizeAttrs1[numAttrs1] = {sizeof(int), 30, 30, sizeof(float)};
    char *attrName1[numAttrs1] = {"r1c1", "r1c2", "r1c3", "r1c4"}; //Column Names for relation r1
    Schema sch1(numAttrs1, attrType1, attrName1, sizeAttrs1);
    Relation r1("mydb.txt", "r1", true, &sch1);

    const short int numAttrs2 = 3;
    short int attrType2[numAttrs2] = {1, 4, 1};
    short int sizeAttrs2[numAttrs2] = {sizeof(int), 30, sizeof(int)};
    char* attrName2[numAttrs2] = {"r2c1", "r2c2", "r2c3"};  //Column Names for relation r2
    Schema sch2(numAttrs2, attrType2, attrName2, sizeAttrs2);
    Relation r2("mydb.txt", "r2", true, &sch2);
    
    const short int numAttrs3 = 2;
    short int attrType3[numAttrs3] = {1, 4};
    short int sizeAttrs3[numAttrs3] = { sizeof(int), 30};
    char* attrName3[numAttrs3] = {"r3c1", "r3c2"};  //Column Names for relation r3
    Schema sch3(numAttrs3, attrType3, attrName3, sizeAttrs3);
    Relation r3("mydb.txt", "r3", true, &sch3);
    
    
    
    //creating records
    string recString1[numAttrs1] = {"29", "sachin", "rathod", "11.11"};
    Record* recp1 = new Record(recString1, &sch1, numAttrs1);
    string recString2[numAttrs1] = {"09", "aniket", "deshmukh", "22.22"};
    Record* recp2 = new Record(recString2, &sch1, numAttrs1);
    
    string recString3[numAttrs2] = {"08", "chirag", "33"};
    Record* recp3 = new Record(recString3, &sch2, numAttrs2);
    string recString4[numAttrs2] = {"17", "manish", "44"};
    Record* recp4 = new Record(recString4, &sch2, numAttrs2);
    
    string recString5[numAttrs3] = { "431122", "beed"};
    Record* recp5 = new Record(recString5, &sch3, numAttrs3);
    string recString6[numAttrs3] = { "411004", "pune"};
    Record* recp6 = new Record(recString6, &sch3, numAttrs3);
    string recString7[numAttrs3] = { "431100", "abad"};
    Record* recp7 = new Record(recString7, &sch3, numAttrs3);
    
    //adding records to relations
    r1.addRecord(*recp1);
    //for (int i = 0; i < 10; i++) r1.addRecord(*recp1);
    r1.addRecord(*recp2);
    r1.addRecord(*recp2);
    r1.addRecord(*recp2);

    r2.addRecord(*recp3);
    r2.addRecord(*recp4);
    r2.addRecord(*recp3);
    r2.addRecord(*recp3);
    r2.addRecord(*recp4);
    
    r3.addRecord(*recp5);
    r3.addRecord(*recp6);
    r3.addRecord(*recp7);
    

//End- Mubase initialisation
    
    //Evaluation
    cout<<"\nQuery Result:\n\n";
    int rno = 1;
    root->open();
    Record* rec;
    
    rec = root->next();
    while(rec){
        cout<<"Record["<<rno<<"]: ";
        rec->print();
        rec = root->next();
        rno++;
    }
    
    root->close();
    //End Evaluation
    
//close Mubase db
    DiskManager::closeDB("mydb.txt");    
    cout << "\nTHE END\n";
}
Exemplo n.º 28
0
void World::update(float timeStep)
{
    for(BodyList::iterator it = m_bodies.begin(); it != m_bodies.end(); ++it){
        if(!(*it)->getBodyDef().isStatic()){
            (*it)->acceleration(m_gravitation*timeStep);
            (*it)->update(timeStep);
        }
    }


    for(BodyList::iterator it = m_bodies.begin(); it != m_bodies.end(); ++it){
        BodyList::iterator ith = it;
        ith++;
        for(BodyList::iterator it2 = ith; it2 != m_bodies.end(); ++it2){
            if(!((*it)->getBodyDef().isStatic()) or !((*it2)->getBodyDef().isStatic())){
                if((*it)->getShape()->collide((*it2)->getShape().get())){
                    Polygon *p1 = static_cast<Polygon *>((*it)->getShape().get());
                    Polygon *p2 = static_cast<Polygon *>((*it2)->getShape().get());

                    bool b = true;
                    Line cl;

                    Vector2f point1 = p1->getTransformedPoint(p1->getNumberOfPoints()-1);
                    Vector2f point2 = p2->getTransformedPoint(p2->getNumberOfPoints()-1);

                    for(size_t i = 0; i < p1->getNumberOfPoints(); ++i){
                        Line line1(p1->getTransformedPoint(i), point1-p1->getTransformedPoint(i));
                        point1 = p1->getTransformedPoint(i);
                        for(size_t j = 0; j < p2->getNumberOfPoints(); ++j){
                            Line line2(p2->getTransformedPoint(j), point2-p2->getTransformedPoint(j));
                            point2 = p2->getTransformedPoint(j);

                            float t1 = line1.intersects(line2);
                            float t2 = line2.intersects(line1);

                            if(0.f < t1 and t1 < 1.f and 0.f < t2 and t2 < 1.f){
                                Vector2f vec = line1.getPoint() + t1 * line1.getDirectionVector();
                                if(b){
                                    cl.setPoint(vec);
                                    b = false;
                                } else {
                                    cl.setDirectionVector(vec - cl.getPoint());
                                }
                            }
                        }
                    }
                    Vector2f n = cl.getDirectionVector().normal();
                    //n.normalize();
                    Vector2f p = cl.getPoint()+(cl.getDirectionVector()/2.f);
                    Body::Ptr b1 = (*it);
                    Body::Ptr b2 = (*it2);

                    mx::Vector2f r1(p - b1->getShape()->getPosition());
                    mx::Vector2f r2(p - b2->getShape()->getPosition());

                    mx::Vector2f rap = r1.normal();
                    mx::Vector2f rbp = r2.normal();

                    float rapn = dot(rap, n);
                    float rbpn = dot(rbp, n);

                    mx::Vector2f vp1(b1->getVelocity()+b1->getAngularVelocity()*rap);
                    mx::Vector2f vp2(b2->getVelocity()+b2->getAngularVelocity()*rbp);
                    mx::Vector2f vab(vp2 - vp1);

                    float M1Inv = 0;
                    float M2Inv = 0;
                    float I1Inv = 0;
                    float I2Inv = 0;

                    if(!b1->getBodyDef().isStatic()){
                        M1Inv = 1.f / b1->getBodyDef().getMass();
                        I1Inv = 1.f / b1->getBodyDef().getMomentOfInertia();
                    }
                    if(!b2->getBodyDef().isStatic()){
                        M2Inv = 1.f / b2->getBodyDef().getMass();
                        I2Inv = 1.f / b2->getBodyDef().getMomentOfInertia();
                    }


                    float j = -(1+(b1->getBodyDef().getElasticity()+b2->getBodyDef().getElasticity())/2.f) * dot(vab, n);
                    j /= dot(n, n)*(M1Inv+M2Inv) + rapn*rapn*I1Inv + rbpn*rbpn*I2Inv;

                    b1->acceleration(-(j*M1Inv) * n);
                    b2->acceleration( (j*M2Inv) * n);

                    b1->angularAcceleration(-j*I1Inv * rapn);
                    b2->angularAcceleration( j*I2Inv * rbpn);

                    Shape::Ptr s1 = b1->getShape();
                    Shape::Ptr s2 = b2->getShape();

                    mx::Vector2f MTD = s1->MTD(s2.get());

                    float MInv = M1Inv + M2Inv;

                    s1->setPosition(s1->getPosition()+MTD*(M1Inv/MInv));
                    s2->setPosition(s2->getPosition()-MTD*(M2Inv/MInv));
                }
            }
        }
    }
}
void random_test()
{
  typedef typename K::Point_3 Point;
  typedef typename K::Segment_3 Segment;
  typedef typename K::Ray_3 Ray;
  typedef typename K::Line_3 Line;
  typedef typename K::Triangle_3 Triangle;
  typedef typename K::Plane_3 Plane;
  
  typename K::Is_degenerate_3 is_degenerate = K().is_degenerate_3_object();
  
  Checker<K> check;
  
  double box_size = 1e12;
  CGAL::Bbox_3 bbox(-box_size,-box_size,-box_size,box_size,box_size,box_size);
  
  // Use 10 triangles, 100 queries for each triangle
  for ( int i=0 ; i<10 ; ++i )
  {
    Triangle t(random_point_in<K>(bbox),
               random_point_in<K>(bbox),
               random_point_in<K>(bbox));
    
    if ( is_degenerate(t) )
      continue;
    
    Plane p = t.supporting_plane();
    
    for ( int j=0 ; j<100 ; ++j )
    {
      Point a = random_point_in<K>(bbox);
      Point b = random_point_in<K>(bbox);
      
      Segment s (a,b);
      Ray r(a,b);
      Line l (a,b);
      
      if ( ! is_degenerate(s) )
        check(s,t);
      if ( ! is_degenerate(r) )
        check(r,t);
      if ( ! is_degenerate(l) )
        check(l,t);
      
      // Project points on triangle plane to have degenerate queries
      Point c = p.projection(a);
      Point d = p.projection(b);
      
      Segment s2 (c,d);
      Ray r2 (c,d);
      Line l2 (c,d);
      
      if ( ! is_degenerate(s2) )
        check(s2,t);
      if ( ! is_degenerate(r2) )
        check(r2,t);
      if ( ! is_degenerate(l2) )
        check(l2,t);
    }
  }
}
/*************************************************************************
Test
*************************************************************************/
bool testfft(bool silent)
{
    bool result;
    int n;
    int i;
    int k;
    ap::complex_1d_array a1;
    ap::complex_1d_array a2;
    ap::complex_1d_array a3;
    ap::real_1d_array r1;
    ap::real_1d_array r2;
    ap::real_1d_array buf;
    ftplan plan;
    int maxn;
    double bidierr;
    double bidirerr;
    double referr;
    double refrerr;
    double reinterr;
    double errtol;
    bool referrors;
    bool bidierrors;
    bool refrerrors;
    bool bidirerrors;
    bool reinterrors;
    bool waserrors;

    maxn = 128;
    errtol = 100*pow(double(maxn), double(3)/double(2))*ap::machineepsilon;
    bidierrors = false;
    referrors = false;
    bidirerrors = false;
    refrerrors = false;
    reinterrors = false;
    waserrors = false;
    
    //
    // Test bi-directional error: norm(x-invFFT(FFT(x)))
    //
    bidierr = 0;
    bidirerr = 0;
    for(n = 1; n <= maxn; n++)
    {
        
        //
        // Complex FFT/invFFT
        //
        a1.setlength(n);
        a2.setlength(n);
        a3.setlength(n);
        for(i = 0; i <= n-1; i++)
        {
            a1(i).x = 2*ap::randomreal()-1;
            a1(i).y = 2*ap::randomreal()-1;
            a2(i) = a1(i);
            a3(i) = a1(i);
        }
        fftc1d(a2, n);
        fftc1dinv(a2, n);
        fftc1dinv(a3, n);
        fftc1d(a3, n);
        for(i = 0; i <= n-1; i++)
        {
            bidierr = ap::maxreal(bidierr, ap::abscomplex(a1(i)-a2(i)));
            bidierr = ap::maxreal(bidierr, ap::abscomplex(a1(i)-a3(i)));
        }
        
        //
        // Real
        //
        r1.setlength(n);
        r2.setlength(n);
        for(i = 0; i <= n-1; i++)
        {
            r1(i) = 2*ap::randomreal()-1;
            r2(i) = r1(i);
        }
        fftr1d(r2, n, a1);
        ap::vmul(&r2(0), ap::vlen(0,n-1), 0);
        fftr1dinv(a1, n, r2);
        for(i = 0; i <= n-1; i++)
        {
            bidirerr = ap::maxreal(bidirerr, ap::abscomplex(r1(i)-r2(i)));
        }
    }
    bidierrors = bidierrors||bidierr>errtol;
    bidirerrors = bidirerrors||bidirerr>errtol;
    
    //
    // Test against reference O(N^2) implementation
    //
    referr = 0;
    refrerr = 0;
    for(n = 1; n <= maxn; n++)
    {
        
        //
        // Complex FFT
        //
        a1.setlength(n);
        a2.setlength(n);
        for(i = 0; i <= n-1; i++)
        {
            a1(i).x = 2*ap::randomreal()-1;
            a1(i).y = 2*ap::randomreal()-1;
            a2(i) = a1(i);
        }
        fftc1d(a1, n);
        reffftc1d(a2, n);
        for(i = 0; i <= n-1; i++)
        {
            referr = ap::maxreal(referr, ap::abscomplex(a1(i)-a2(i)));
        }
        
        //
        // Complex inverse FFT
        //
        a1.setlength(n);
        a2.setlength(n);
        for(i = 0; i <= n-1; i++)
        {
            a1(i).x = 2*ap::randomreal()-1;
            a1(i).y = 2*ap::randomreal()-1;
            a2(i) = a1(i);
        }
        fftc1dinv(a1, n);
        reffftc1dinv(a2, n);
        for(i = 0; i <= n-1; i++)
        {
            referr = ap::maxreal(referr, ap::abscomplex(a1(i)-a2(i)));
        }
        
        //
        // Real forward/inverse FFT:
        // * calculate and check forward FFT
        // * use precalculated FFT to check backward FFT
        //   fill unused parts of frequencies array with random numbers
        //   to ensure that they are not really used
        //
        r1.setlength(n);
        r2.setlength(n);
        for(i = 0; i <= n-1; i++)
        {
            r1(i) = 2*ap::randomreal()-1;
            r2(i) = r1(i);
        }
        fftr1d(r1, n, a1);
        refinternalrfft(r2, n, a2);
        for(i = 0; i <= n-1; i++)
        {
            refrerr = ap::maxreal(refrerr, ap::abscomplex(a1(i)-a2(i)));
        }
        a3.setlength(ap::ifloor(double(n)/double(2))+1);
        for(i = 0; i <= ap::ifloor(double(n)/double(2)); i++)
        {
            a3(i) = a2(i);
        }
        a3(0).y = 2*ap::randomreal()-1;
        if( n%2==0 )
        {
            a3(ap::ifloor(double(n)/double(2))).y = 2*ap::randomreal()-1;
        }
        for(i = 0; i <= n-1; i++)
        {
            r1(i) = 0;
        }
        fftr1dinv(a3, n, r1);
        for(i = 0; i <= n-1; i++)
        {
            refrerr = ap::maxreal(refrerr, fabs(r2(i)-r1(i)));
        }
    }
    referrors = referrors||referr>errtol;
    refrerrors = refrerrors||refrerr>errtol;
    
    //
    // test internal real even FFT
    //
    reinterr = 0;
    for(k = 1; k <= maxn/2; k++)
    {
        n = 2*k;
        
        //
        // Real forward FFT
        //
        r1.setlength(n);
        r2.setlength(n);
        for(i = 0; i <= n-1; i++)
        {
            r1(i) = 2*ap::randomreal()-1;
            r2(i) = r1(i);
        }
        ftbasegeneratecomplexfftplan(n/2, plan);
        buf.setlength(n);
        fftr1dinternaleven(r1, n, buf, plan);
        refinternalrfft(r2, n, a2);
        reinterr = ap::maxreal(reinterr, fabs(r1(0)-a2(0).x));
        reinterr = ap::maxreal(reinterr, fabs(r1(1)-a2(n/2).x));
        for(i = 1; i <= n/2-1; i++)
        {
            reinterr = ap::maxreal(reinterr, fabs(r1(2*i+0)-a2(i).x));
            reinterr = ap::maxreal(reinterr, fabs(r1(2*i+1)-a2(i).y));
        }
        
        //
        // Real backward FFT
        //
        r1.setlength(n);
        for(i = 0; i <= n-1; i++)
        {
            r1(i) = 2*ap::randomreal()-1;
        }
        a2.setlength(ap::ifloor(double(n)/double(2))+1);
        a2(0) = r1(0);
        for(i = 1; i <= ap::ifloor(double(n)/double(2))-1; i++)
        {
            a2(i).x = r1(2*i+0);
            a2(i).y = r1(2*i+1);
        }
        a2(ap::ifloor(double(n)/double(2))) = r1(1);
        ftbasegeneratecomplexfftplan(n/2, plan);
        buf.setlength(n);
        fftr1dinvinternaleven(r1, n, buf, plan);
        fftr1dinv(a2, n, r2);
        for(i = 0; i <= n-1; i++)
        {
            reinterr = ap::maxreal(reinterr, fabs(r1(i)-r2(i)));
        }
    }
    reinterrors = reinterrors||reinterr>errtol;
    
    //
    // end
    //
    waserrors = bidierrors||bidirerrors||referrors||refrerrors||reinterrors;
    if( !silent )
    {
        printf("TESTING FFT\n");
        printf("FINAL RESULT:                             ");
        if( waserrors )
        {
            printf("FAILED\n");
        }
        else
        {
            printf("OK\n");
        }
        printf("* BI-DIRECTIONAL COMPLEX TEST:            ");
        if( bidierrors )
        {
            printf("FAILED\n");
        }
        else
        {
            printf("OK\n");
        }
        printf("* AGAINST REFERENCE COMPLEX FFT:          ");
        if( referrors )
        {
            printf("FAILED\n");
        }
        else
        {
            printf("OK\n");
        }
        printf("* BI-DIRECTIONAL REAL TEST:               ");
        if( bidirerrors )
        {
            printf("FAILED\n");
        }
        else
        {
            printf("OK\n");
        }
        printf("* AGAINST REFERENCE REAL FFT:             ");
        if( refrerrors )
        {
            printf("FAILED\n");
        }
        else
        {
            printf("OK\n");
        }
        printf("* INTERNAL EVEN FFT:                      ");
        if( reinterrors )
        {
            printf("FAILED\n");
        }
        else
        {
            printf("OK\n");
        }
        if( waserrors )
        {
            printf("TEST FAILED\n");
        }
        else
        {
            printf("TEST PASSED\n");
        }
    }
    result = !waserrors;
    return result;
}