void Dialog::PrimarySkillInfo(const std::string &header, const std::string &message, const Skill::Primary::skill_t skill)
{
    Display & display = Display::Get();
    const ICN::icn_t system = Settings::Get().EvilInterface() ? ICN::SYSTEME : ICN::SYSTEM;

    // preload
    AGG::PreloadObject(system);

    // cursor
    Cursor & cursor = Cursor::Get();

    cursor.Hide();
    cursor.SetThemes(cursor.POINTER);

    u8 index = 0;
    std::string skill_name;

    switch(skill)
    {
    case Skill::Primary::ATTACK:
        index = 0;
        skill_name = _("Attack Skill");
        break;

    case Skill::Primary::DEFENCE:
        index = 1;
        skill_name = _("Defense Skill");
        break;

    case Skill::Primary::POWER:
        index = 2;
        skill_name = _("Spell Power");
        break;

    case Skill::Primary::KNOWLEDGE:
        index = 3;
        skill_name = _("Knowledge");
        break;

    default:
        break;
    }

    TextBox box1(header, Font::BIG, BOXAREA_WIDTH);
    TextBox box2(message, Font::BIG, BOXAREA_WIDTH);
    const Sprite & border = AGG::GetICN(ICN::PRIMSKIL, 4);
    const u8 spacer = Settings::Get().QVGA() ? 5 : 10;

    Box box(box1.h() + spacer + box2.h() + spacer + border.h(), Dialog::OK);
    Rect pos = box.GetArea();

    if(header.size()) box1.Blit(pos);
    pos.y += box1.h() + spacer;

    if(message.size()) box2.Blit(pos);
    pos.y += box2.h() + spacer;

    // blit sprite
    pos.x = box.GetArea().x + (pos.w - border.w()) / 2;
    display.Blit(border, pos.x, pos.y);
    const Sprite & sprite = AGG::GetICN(ICN::PRIMSKIL, index);
    pos.x = box.GetArea().x + (pos.w - sprite.w()) / 2;
    display.Blit(sprite, pos.x, pos.y + 6);

    Text text;

    text.Set(skill_name, Font::SMALL);
    pos.x = box.GetArea().x + (pos.w - text.w()) / 2;
    text.Blit(pos.x, pos.y + 8);

    text.Set("+1", Font::BIG);
    pos.x = box.GetArea().x + (pos.w - text.w()) / 2;
    text.Blit(pos.x, pos.y + 80);

    LocalEvent & le = LocalEvent::Get();

    Point pt;

    pt.x = box.GetArea().x + (box.GetArea().w - AGG::GetICN(system, 1).w()) / 2;
    pt.y = box.GetArea().y + box.GetArea().h - AGG::GetICN(system, 1).h();
    Button button(pt, system, 1, 2);

    button.Draw();

    cursor.Show();
    display.Flip();

    // message loop
    while(le.HandleEvents())
    {
        le.MousePressLeft(button) ? button.PressDraw() : button.ReleaseDraw();

        if(le.MouseClickLeft(button)) {
            break;
        }

        if(le.KeyPress(KEY_RETURN) || le.KeyPress(KEY_ESCAPE)) {
            break;
        }
    }

    cursor.Hide();
}
void Dialog::SecondarySkillInfo(const std::string &header, const std::string &message, const Skill::Secondary::skill_t skill, const Skill::Level::type_t level, const bool ok_button)
{
    Display & display = Display::Get();
    const ICN::icn_t system = Settings::Get().EvilInterface() ? ICN::SYSTEME : ICN::SYSTEM;

    // preload
    AGG::PreloadObject(system);

    // cursor
    Cursor & cursor = Cursor::Get();

    cursor.Hide();
    cursor.SetThemes(cursor.POINTER);

    TextBox box1(header, Font::YELLOW_BIG, BOXAREA_WIDTH);
    TextBox box2(message, Font::BIG, BOXAREA_WIDTH);
    const Sprite & border = AGG::GetICN(ICN::SECSKILL, 15);
    const u8 spacer = Settings::Get().QVGA() ? 5 : 10;

    Box box(box1.h() + spacer + box2.h() + spacer + border.h(), ok_button);
    Rect pos = box.GetArea();

    if(header.size()) box1.Blit(pos);
    pos.y += box1.h() + spacer;

    if(message.size()) box2.Blit(pos);
    pos.y += box2.h() + spacer;

    // blit sprite
    pos.x = box.GetArea().x + (pos.w - border.w()) / 2;
    display.Blit(border, pos.x, pos.y);
    const Sprite & sprite = AGG::GetICN(ICN::SECSKILL, Skill::Secondary::GetIndexSprite1(skill));
    pos.x = box.GetArea().x + (pos.w - sprite.w()) / 2;
    display.Blit(sprite, pos.x, pos.y + 3);

    Text text;

    // small text
    text.Set(Skill::Secondary::String(skill), Font::SMALL);
    pos.x = box.GetArea().x + (pos.w - text.w()) / 2;
    text.Blit(pos.x, pos.y + 3);

    text.Set(Skill::Level::String(level));
    pos.x = box.GetArea().x + (pos.w - text.w()) / 2;
    text.Blit(pos.x, pos.y + 55);

    LocalEvent & le = LocalEvent::Get();

    Button *button = NULL;
    Point pt;

    if(ok_button)
    {
        pt.x = box.GetArea().x + (box.GetArea().w - AGG::GetICN(system, 1).w()) / 2;
        pt.y = box.GetArea().y + box.GetArea().h - AGG::GetICN(system, 1).h();
        button = new Button(pt, system, 1, 2);
    }

    if(button) (*button).Draw();

    cursor.Show();
    display.Flip();

    // message loop
    while(le.HandleEvents())
    {
        if(!ok_button && !le.MousePressRight()) break;

        if(button) le.MousePressLeft(*button) ? button->PressDraw() : button->ReleaseDraw();

        if(button && le.MouseClickLeft(*button)) {
            break;
        }

        if(le.KeyPress(KEY_RETURN) || le.KeyPress(KEY_ESCAPE)) {
            break;
        }
    }

    cursor.Hide();
    if(button) delete button;
}
示例#3
0
bool Dialog::SelectGoldOrExp(const std::string & header, const std::string & message, u32 gold, u32 expr, const  Heroes & hero)
{
    Display & display = Display::Get();
    const int system = Settings::Get().ExtGameEvilInterface() ? ICN::SYSTEME : ICN::SYSTEM;

    // cursor
    Cursor & cursor = Cursor::Get();

    cursor.Hide();
    cursor.SetThemes(cursor.POINTER);

    const Sprite & sprite_gold = AGG::GetICN(ICN::RESOURCE, 6);
    const Sprite & sprite_expr = AGG::GetICN(ICN::EXPMRL, 4);

    Point pt;
    TextBox box1(header, Font::YELLOW_BIG, BOXAREA_WIDTH);
    TextBox box2(message, Font::BIG, BOXAREA_WIDTH);

    Text text;
    text.Set(GetString(gold) + " " + "(" + "total: " + GetString(world.GetKingdom(hero.GetColor()).GetFunds().Get(Resource::GOLD)) + ")", Font::SMALL);

    const int spacer = Settings::Get().QVGA() ? 5 : 10;
    FrameBox box(box1.h() + spacer + box2.h() + spacer + sprite_expr.h() + 2 + text.h(), true);

    pt.x = box.GetArea().x + box.GetArea().w / 2 - AGG::GetICN(system, 9).w() - 20;
    pt.y = box.GetArea().y + box.GetArea().h - AGG::GetICN(system, 5).h();
    Button button_yes(pt.x, pt.y, system, 5, 6);

    pt.x = box.GetArea().x + box.GetArea().w / 2 + 20;
    pt.y = box.GetArea().y + box.GetArea().h - AGG::GetICN(system, 7).h();
    Button button_no(pt.x, pt.y, system, 7, 8);

    Rect pos = box.GetArea();

    if(header.size()) box1.Blit(pos);
    pos.y += box1.h() + spacer;

    if(message.size()) box2.Blit(pos);
    pos.y += box2.h() + spacer;

    pos.y += sprite_expr.h();
    // sprite1
    pos.x = box.GetArea().x + box.GetArea().w / 2 - sprite_gold.w() - 30;
    sprite_gold.Blit(pos.x, pos.y - sprite_gold.h());
    // text
    text.Blit(pos.x + (sprite_gold.w() - text.w()) / 2, pos.y + 2);

    // sprite2
    pos.x = box.GetArea().x + box.GetArea().w / 2 + 30;
    sprite_expr.Blit(pos.x, pos.y - sprite_expr.h());
    // text
    text.Set(GetString(expr) + " " + "(" + "need: " + GetString(Heroes::GetExperienceFromLevel(hero.GetLevel()) - hero.GetExperience()) + ")", Font::SMALL);
    text.Blit(pos.x + (sprite_expr.w() - text.w()) / 2, pos.y + 2);

    button_yes.Draw();
    button_no.Draw();

    cursor.Show();
    display.Flip();
    LocalEvent & le = LocalEvent::Get();
    bool result = false;

    // message loop
    while(le.HandleEvents())
    {
	le.MousePressLeft(button_yes) ? button_yes.PressDraw() : button_yes.ReleaseDraw();
	le.MousePressLeft(button_no) ? button_no.PressDraw() : button_no.ReleaseDraw();

        if(Game::HotKeyPressEvent(Game::EVENT_DEFAULT_READY) || le.MouseClickLeft(button_yes)){ result = true; break; }
        if(Game::HotKeyPressEvent(Game::EVENT_DEFAULT_EXIT) || le.MouseClickLeft(button_no)){ result = false; break; }
    }

    cursor.Hide();

    return result;
}
示例#4
0
//==============================================================================
void GameServer::tick()
{
  /*float dt = (time_.elapsed() - lastTime_) * 0.001f;*/
  lastTime_ = time_.elapsed();

  /*if (actors_.size() < 100 && !testingStageActive_)
  {
    GenMonsters_();
  }*/

  auto collideWithGrid = [=](Actor* actor, EActorDirection direction)
  {
    auto& p = *actor;

    float x = p.GetPosition().x;
    float y = p.GetPosition().y;

    bool collided = false;

    if ((levelMap_.GetCell(x + 0.49f, y - 0.51f) != '.'
        || levelMap_.GetCell(x + 0.49f, y + 0.49f) != '.')
        && levelMap_.GetCell(x - slideThreshold_+ 0.5f, y) == '.'
        && (direction == EActorDirection::NORTH
        || direction == EActorDirection::SOUTH))
    {
      p.SetPosition(Vector2(x - slideThreshold_+ 0.0001f, p.GetPosition().y));
    }

    if (levelMap_.GetCell(x + slideThreshold_- 0.5f, y) == '.'
        &&((levelMap_.GetCell(x - 0.5f, y - 0.51f) != '.'
        || levelMap_.GetCell(x - 0.5f, y + 0.49f) != '.')
        && (direction == EActorDirection::NORTH
        || direction == EActorDirection::SOUTH)))
    {
      p.SetPosition(Vector2(x + slideThreshold_- 0.0001f, p.GetPosition().y));
    }

    if (levelMap_.GetCell(x, y - slideThreshold_ + 0.5f) == '.'
        && (levelMap_.GetCell(x - 0.51f, y + 0.49f) != '.'
        || levelMap_.GetCell(x + 0.49f, y + 0.49f) != '.')
        && (direction == EActorDirection::EAST
        || direction == EActorDirection::WEST))
    {
      p.SetPosition(Vector2(p.GetPosition().x, y - slideThreshold_+ 0.0001f));
    }

    if ((levelMap_.GetCell(x + 0.49f, y - 0.5f) != '.'
        || levelMap_.GetCell(x - 0.51f, y - 0.5f) != '.')
        && levelMap_.GetCell(x, y + slideThreshold_- 0.5f) == '.'
        && (direction == EActorDirection::EAST
        || direction == EActorDirection::WEST))
    {
      p.SetPosition(Vector2(p.GetPosition().x, y + slideThreshold_ - 0.001f));
    }

    if (levelMap_.GetCell(x + 0.5f, y) != '.')
    {
      p.SetPosition(Vector2(round(x + 0.5f) - 0.5f, p.GetPosition().y));
      collided = true;
    }

    if (levelMap_.GetCell(x - 0.51f, y) != '.')
    {
      p.SetPosition(Vector2(round(x - 0.5f) + 0.5f, p.GetPosition().y));
      collided = true;
    }

    if (levelMap_.GetCell(x, y + 0.5f) != '.')
    {
      p.SetPosition(Vector2(p.GetPosition().x, round(y + 0.5f) - 0.5f));
      collided = true;
    }

    if (levelMap_.GetCell(x, y - 0.51f) != '.')
    {
      p.SetPosition(Vector2(p.GetPosition().x, round(y - 0.5f) + 0.5f));
      collided = true;
    }

    if (collided)
    {
      actor->OnCollideWorld();
    }
  };

  for (Actor* actor: actors_)
  {
    if (actor->GetType() == EActorType::MONSTER)
    {
      Monster* monster = dynamic_cast<Monster*>(actor);
      Creature* target = monster->target;
      float distance2;
      Vector2 m_pos = actor->GetPosition();
      if (target && target != nullptr)
      {
        Vector2 t_pos = target->GetPosition();
        distance2 = Sqr(m_pos.x - t_pos.x)
                    + Sqr(m_pos.y - t_pos.y);
        if (distance2 < 25)
        {
          if (abs(m_pos.x - t_pos.x - 1.0f) < playerVelocity_
              && m_pos.x - t_pos.x - 1.0f != 0)
          {
            monster->SetPosition(Vector2(t_pos.x + 1.0f, m_pos.y));
            monster->SetDirection(EActorDirection::NONE);
          }

          if (abs(m_pos.y - t_pos.y + 1.0f) < playerVelocity_
              && m_pos.y - t_pos.y + 1.0f != 0)
          {
            monster->SetPosition(Vector2(m_pos.x, t_pos.y - 1.0f));
            monster->SetDirection(EActorDirection::NONE);
          }

          if (m_pos.x < t_pos.x - 1.0f)
          {
            monster->SetDirection(EActorDirection::EAST);
          }
          else if (m_pos.x > t_pos.x + 1.0f)
          {
            monster->SetDirection(EActorDirection::WEST);
          }
          else if (m_pos.y < t_pos.y - 1.0f)
          {
            monster->SetDirection(EActorDirection::SOUTH);
          }
          else if (m_pos.y > t_pos.y + 1.0f)
          {
            monster->SetDirection(EActorDirection::NORTH);
          }
        }
      }

      if (!target
          || target == nullptr
          || distance2 >= 5)
      {
        for (Actor* tar : actors_)
        {
          if (tar != monster)
          {
            bool b = false;
            if (tar->GetType() != EActorType::ITEM
                && tar->GetType () != EActorType::PROJECTILE)
            {
              Creature* m = dynamic_cast<Creature*>(tar);

              QStringList str = monster->Flags.filter("HATE");
              for (QString hate: str)
              {
                if (Hates[hate] == m->GetRace())
                {
                  b = true;
                  break;
                }
              }

              if (b)
              {
                Vector2 t_pos = tar->GetPosition();
                distance2 = Sqr(m_pos.x - t_pos.x) + Sqr(m_pos.y - t_pos.y);
                // Dasha told 5^2 is a protocol defined const
                if (distance2 < 25)
                {
                  monster->target = m;
                  break;
                }
              }
            }
          }
        }
      }
    }

    if (actor->GetType() == EActorType::MONSTER
        || actor->GetType() == EActorType::PLAYER)
    {
      Creature* monster = dynamic_cast<Creature*>(actor);
      if (monster->GetHealth() <= 0)
      {
        KillActor_(actor);
        break;
      }
    }
  }

  for (Actor* actor: actors_)
  {
    if (!actor
        || actor == nullptr)
    {
      break;
    }

    auto v = directionToVector[static_cast<unsigned>(actor->GetDirection())] ;
    actor->SetVelocity(v);
    float dt = playerVelocity_;
    Vector2 old_pos = actor->GetPosition();
    Vector2 new_pos = old_pos + v * (dt + 0.001);
    Vector2 old_pos2 = old_pos + v * 0.51;
    levelMap_.RemoveActor(actor);
    EActorDirection d = actor->GetDirection();
    float x = new_pos.x;
    float y = new_pos.y;
    if (levelMap_.GetCell(old_pos2.x, old_pos2.y) != '#'
        && d != EActorDirection::NONE
        && (((levelMap_.GetCell(x - slideThreshold_+ 0.5f, y) == '.'
              && levelMap_.GetCell(x + slideThreshold_- 0.5f, y) == '.')
             && (d == EActorDirection::NORTH
                 || d == EActorDirection::SOUTH))
            || ((levelMap_.GetCell(x, y - slideThreshold_+ 0.5f) == '.'
                 && levelMap_.GetCell(x, y + slideThreshold_- 0.5f) == '.')
                && (d == EActorDirection::EAST
                    || d == EActorDirection::WEST))))
    {
      if (levelMap_.GetCell(new_pos.x, new_pos.y) == '.')
      {
        if (!actor->Update(dt)
            && actor->GetType () == EActorType::PROJECTILE)
        {
          static_cast<Projectile*>(actor)->death = true;
        }
        collideWithGrid(actor, d);
      }
      else if (levelMap_.GetCell(x , y) != '.'
               && playerVelocity_ >= 1)
      {
        bool b = false;
        for (float i = 0.01; i <= dt; i += 0.01)
        {
          new_pos = old_pos + v * i + v * 0.5f;
          if (levelMap_.GetCell(new_pos.x, new_pos.y) == '#' && !b)
          {
            actor->Update(i - 0.01);
            b = true;
          }
        }
      }
      else
      {
        if (actor->GetType () == EActorType::PROJECTILE)
        {
          static_cast<Projectile*>(actor)->death = true;
        }
      }
    }
    else
    {
      if (actor
          && actor != nullptr)
      {
        if (actor->GetType () == EActorType::PROJECTILE)
        {
          static_cast<Projectile*>(actor)->death = true;
        }
        else
        {
          actor->OnCollideWorld();
        }
      }
    }

    if (actor->GetType() == EActorType::PLAYER)
    {
      Player* player = dynamic_cast<Player*>(actor);
      if (player->GetHealth() < player->GetMaxHealth())
      {
        player->SetHealth(player->GetHealth() + 1);
      }
    }

    if (actor->GetType() == EActorType::MONSTER)
    {
      Monster* monster = dynamic_cast<Monster*>(actor);
      Creature* target = monster->target;
      if (target && target->GetHealth() > 0)
      {
        Vector2 m_pos = actor->GetPosition();
        Vector2 t_pos = target->GetPosition();
        float distance2 = Sqr(m_pos.x - t_pos.x)
                          + Sqr(m_pos.y - t_pos.y);

        if (distance2 <= Sqr(pickUpRadius_))
        {
          events_ << monster->atack(target);
          events_ << target->atack(monster);
        }
      }
    }

    for (Actor* neighbour : actors_)
    {
      if (actor == nullptr
          || neighbour == nullptr
          || actor == neighbour
          || neighbour->GetType() == EActorType::ITEM
          || (actor->GetType() == EActorType::PROJECTILE
              && neighbour->GetType() == EActorType::PROJECTILE))
      {
        break;
      }

      Box box0(neighbour->GetPosition(), 0.9f, 0.9f);
      Box box1(actor->GetPosition(), 0.9f, 0.9f);

      if (box0.Intersect(box1))
      {
        actor->OnCollideActor(neighbour);
        neighbour->OnCollideActor(actor);
        if (actor->GetType() == EActorType::PROJECTILE)
        {
          static_cast<Projectile*>(actor)->death = true;
          if (neighbour->GetType () == EActorType::MONSTER)
          {
            Monster* monster = dynamic_cast<Monster*>(neighbour);
            if (monster->GetHealth () <= 0)
            {
              GetItems(monster);
            }
          }
        }
        else if (neighbour->GetType() == EActorType::PROJECTILE)
        {
          static_cast<Projectile*>(neighbour)->death = true;

          if (actor->GetType() == EActorType::MONSTER)
          {
            Monster* monster = dynamic_cast<Monster*>(actor);
            if (monster->GetHealth () <= 0)
            {
              GetItems(monster);
            }
          }
        }
        else if (neighbour->GetType() != EActorType::ITEM)
        {
          actor->SetPosition(old_pos);
        }
      }
    }
    if (actor->GetType() == EActorType::PROJECTILE
        && static_cast<Projectile*>(actor)->death)
    {
      QVariantMap ans1;
      ans1["radius"] = 1.0f;
      ans1["x"] = actor->GetPosition ().x;
      ans1["y"] = actor->GetPosition ().y;
      QVariantMap ans;
      ans["explode"] = ans1;
      events_  << ans;
      idToActor_.erase(actor->GetId());
      actors_.erase(std::remove(actors_.begin(), actors_.end(), actor), actors_.end());
      delete actor;
      actor = nullptr;
    }
    else
    {
      levelMap_.IndexActor(actor);
    }
  }

  QVariantMap tickMessage;
  tickMessage["tick"] = tick_;
  tickMessage["events"] = events_;
  events_.clear();
  emit broadcastMessage(QString(QJsonDocument::fromVariant(tickMessage).toJson()));
  tick_++;
}
示例#5
0
void CCal3DSceneNode::render()
{
    //----------------------------------------------------------//
    if ( calModel == 0 )
        return;                              // Make sure there is a model to render
        
    //----------------------------------------------------------//
    video::IVideoDriver* driver = SceneManager->getVideoDriver(); // Get the video driver
    CalRenderer* renderer = calModel->getRenderer();            // Get the CalRenderer

    
    
    //----------------------------------------------------------//
    // All we're doing here is form a bridge between the CalRenderer and the IVideoDriver
    // The CalRenderer gives us data (doesn't draw anything) and IVideoDriver needs that data
    // Only problem is that we need to convert it to Irrlicht Compatible data
    // To explain what's going on, this simple diagram should help:
    //  CalRenderer >--GET--> Data >--CONVERT--> Irrlicht Format >--SEND--> IVideoDriver >--DRAW--> ..
    
    //----------------------------------------------------------//
    calModel->getSkeleton()->calculateBoundingBoxes();        // Calculate the bounding box of the skeleton
    
    //----------------------------------------------------------//
    if ( renderer == 0  )
        return;                               // Bail out if no renderer was received
    if ( !renderer->beginRendering() )
        return;                  // Bail out if renderer encountered an error
        
    //----------------------------------------------------------// Move to our position (and rotate/scale)
    driver->setTransform( video::ETS_WORLD, AbsoluteTransformation );
    
    
    //----------------------------------------------------------//
    s32 numMeshes = renderer->getMeshCount();                   // Get the number of meshes we need to draw
    for ( s32 meshId = 0; meshId < numMeshes; meshId++ )        // Loop for every mesh
    {
        //--------------------------------------------------------//
        s32 numSubMeshes = renderer->getSubmeshCount(meshId);     // Get the number of submeshes
        for ( s32 subId = 0; subId < numSubMeshes; subId++ )      // Loop for every submesh
        {
            if ( !renderer->selectMeshSubmesh(meshId, subId) )      // Select the current mesh and submesh
            {
                continue;                                             // Skip this submesh if it failed
            }
            
            //------------------------------------------------------//
            if ( !OverrideMaterial )                              // Should we use Cal3D's material?
            {
                u8 meshColor [4];                                     // Color stored in RGBA format
                // Irrlicht wants it in ARGB format
                renderer->getAmbientColor( meshColor );               // Get the ambient color
                Material.AmbientColor.setRed( meshColor[0] );       // Set the red component
                Material.AmbientColor.setGreen( meshColor[1] );     // Set the green component
                Material.AmbientColor.setBlue( meshColor[2] );      // Set the blue component
                Material.AmbientColor.setAlpha( meshColor[3] );     // Set the alpha component
                
                renderer->getDiffuseColor( meshColor );               // Get the diffuse color
                Material.DiffuseColor.setRed( meshColor[0] );       // Set the red component
                Material.DiffuseColor.setGreen( meshColor[1] );     // Set the green component
                Material.DiffuseColor.setBlue( meshColor[2] );      // Set the blue component
                Material.DiffuseColor.setAlpha( meshColor[3] );     // Set the alpha component
                
                renderer->getSpecularColor( meshColor );              // Get the specular color
                Material.SpecularColor.setRed( meshColor[0] );      // Set the red component
                Material.SpecularColor.setGreen( meshColor[1] );    // Set the green component
                Material.SpecularColor.setBlue( meshColor[2] );     // Set the blue component
                Material.SpecularColor.setAlpha( meshColor[3] );    // Set the alpha component
                
                Material.Shininess = renderer->getShininess();      // Set the shininess factor
                
                if ( renderer->getMapCount() >= 1 )
                {                                                     // Get the irrlicht texture from user data
                    Material.setTexture(0, (video::ITexture*)renderer->getMapUserData(0));
                }
            }
            
            //------------------------------------------------------//
            s32 vertexCount = renderer->getVertexCount();           // Get the number of vertices
            if (vertexCount == 0)
                continue;                         // Skip if the mesh is empty
                
            static core::array<core::vector3df> vertexBuffer;    // Use a core::array to support msvc
            vertexBuffer.set_used( vertexCount );          // Make room for the vertex coordinates
            renderer->getVertices( &vertexBuffer[0].X );              // Copy the vertices into the buffer
            
            //------------------------------------------------------//
            static core::array<core::vector3df> normalBuffer;
            normalBuffer.set_used( vertexCount );       // Buffer for the vertex normals
            renderer->getNormals( &normalBuffer[0].X );               // Copy the normals to the buffer
            
            //------------------------------------------------------//
            static core::array<core::vector2df> texCoordBuffer;
            texCoordBuffer.set_used( vertexCount );                 // Buffer for the vertex texture coordinates
            renderer->getTextureCoordinates( 0, &texCoordBuffer[0].X );// Copy the texture coordinates to the buffer
            
            //------------------------------------------------------//
            s32 faceCount = renderer->getFaceCount();               // Get the number of faces
            static CalIndex cal_indices[30000000];
            renderer->getFaces(  cal_indices );                   // Copy the face indices to the buffer
            static core::array<u16> faceBuffer;
            faceBuffer.set_used( faceCount * 3 );                   // Buffer for the face v1,v2,v3 indices
            for(int i = 0; i < faceCount * 3; ++i)
            {
              faceBuffer[i] = cal_indices[i];
            }
            
            //------------------------------------------------------//
            static core::array<video::S3DVertex> irrVertexBuffer;
            irrVertexBuffer.set_used( vertexCount );                // Buffer for the irrlicht vertices
            for (s32 vert=0; vert<vertexCount; vert++)              // Convert all vertices to irrlicht format
            { // Irrlicht and Cal3D uses different coordinates. Irrlicht's Y points up, where Cal3D's Z points up
                irrVertexBuffer[vert].Pos.X = vertexBuffer[vert].X;  // Set the X coordinate
                irrVertexBuffer[vert].Pos.Y = vertexBuffer[vert].Y;  // Set the Y coordinate (Cal3D's Z coord)
                irrVertexBuffer[vert].Pos.Z = vertexBuffer[vert].Z;  // Set the Z coordinate (Cal3D's Y coord)
                
                irrVertexBuffer[vert].Color.set(255,128,128,128);     // Vertex colors aren't supported by Cal3D
                
                irrVertexBuffer[vert].Normal.X = normalBuffer[vert].X;// Set the X coordinate
                irrVertexBuffer[vert].Normal.Y = normalBuffer[vert].Y;// Set the Y coordinate (Cal3D's Z coord)
                irrVertexBuffer[vert].Normal.Z = normalBuffer[vert].Z;// Set the Z coordinate (Cal3D's Y coord)
                
                irrVertexBuffer[vert].TCoords.X = texCoordBuffer[vert].X;// Set the X texture coordinate (U)
                irrVertexBuffer[vert].TCoords.Y = texCoordBuffer[vert].Y;// Set the Y texture coordinate (V)
            }
            
            //------------------------------------------------------// Invert triangle direction
            for (s32 face=0; face<faceCount; face++)                // Irrlicht wants indices in the opposite order
            {
                u16 faceA = faceBuffer[face*3];                      // Swap first and last vertex index
                faceBuffer[face*3]   = faceBuffer[face*3+2];         // Set the first to the last
                faceBuffer[face*3+2] = faceA;                        // And the last to the first
            }
            
            //------------------------------------------------------// Finally! Time to draw everthing

           Material.BackfaceCulling = false;

           float k;

           if(draw_mode != DM_DEFAULT)
           {
               video::SMaterial debug_material;
               debug_material.Wireframe = true;
               debug_material.BackfaceCulling = false;
               debug_material.Lighting = false;
               driver->setMaterial(debug_material);
              
               /* so that debug looks good for all sizes of models*/
               k = EXTENT_K * BoundingBox.getExtent().getLength();
           }
           else
           {
               driver->setMaterial( Material );
           }

           if(draw_mode == DM_DEFAULT)
           {
               driver->drawIndexedTriangleList(irrVertexBuffer.const_pointer(),
                                               vertexCount,
                                               faceBuffer.const_pointer(),
                                               faceCount);
           }
           else if(draw_mode == DM_WIREFRAME || 
                   draw_mode == DM_WIREFRAME_AND_SKELETON)
           {
               /* draw faces */
               for (s32 face=0; face<faceCount; ++face)
               {
                 u16 i1, i2, i3;
                 i1 = faceBuffer[face*3+0];
                 i2 = faceBuffer[face*3+1];
                 i3 = faceBuffer[face*3+2];

                 driver->draw3DLine(core::vector3df(vertexBuffer[i1].X,
                                                    vertexBuffer[i1].Y,
                                                    vertexBuffer[i1].Z),
                                    core::vector3df(vertexBuffer[i2].X,
                                                    vertexBuffer[i2].Y,
                                                    vertexBuffer[i2].Z),
                                    video::SColor(255,0,0,255));
                 driver->draw3DLine(core::vector3df(vertexBuffer[i2].X,
                                                    vertexBuffer[i2].Y,
                                                    vertexBuffer[i2].Z),
                                    core::vector3df(vertexBuffer[i3].X,
                                                    vertexBuffer[i3].Y,
                                                    vertexBuffer[i3].Z),
                                    video::SColor(255,0,0,255));
                 driver->draw3DLine(core::vector3df(vertexBuffer[i3].X,
                                                    vertexBuffer[i3].Y,
                                                    vertexBuffer[i3].Z),
                                    core::vector3df(vertexBuffer[i1].X,
                                                    vertexBuffer[i1].Y,
                                                    vertexBuffer[i1].Z),
                                    video::SColor(255,0,0,255));
               }

           }

           if(draw_mode == DM_SKELETON || 
              draw_mode == DM_WIREFRAME_AND_SKELETON)
           {
              float lines[1024][2][3];
              int num_lines;
              num_lines =  calModel->getSkeleton()->getBoneLines(&lines[0][0][0]);
              video::S3DVertex vertex;

              for(int line = 0; line < num_lines; ++line)
              {
                  driver->draw3DLine(core::vector3df(lines[line][0][0], 
                                                     lines[line][0][1],
                                                     lines[line][0][2]),
                                     core::vector3df(lines[line][1][0], 
                                                     lines[line][1][1],
                                                     lines[line][1][2]),
                                     video::SColor(255,255,0,0));
                 
                  core::aabbox3df box1(lines[line][0][0]-SKELETON_K*k,
                                       lines[line][0][1]-SKELETON_K*k, 
                                       lines[line][0][2]-SKELETON_K*k,

                                       lines[line][0][0]+SKELETON_K*k, 
                                       lines[line][0][1]+SKELETON_K*k, 
                                       lines[line][0][2]+SKELETON_K*k);

                  core::aabbox3df box2(lines[line][1][0]-SKELETON_K*k,
                                       lines[line][1][1]-SKELETON_K*k, 
                                       lines[line][1][2]-SKELETON_K*k,

                                       lines[line][1][0]+SKELETON_K*k, 
                                       lines[line][1][1]+SKELETON_K*k, 
                                       lines[line][1][2]+SKELETON_K*k);
                 
                  driver->draw3DBox(box1, video::SColor(255,0,255,0));
                  driver->draw3DBox(box2, video::SColor(255,0,255,0));
              }
           }

           if(draw_bbox)
           {
             video::SMaterial debug_material;
             debug_material.Wireframe = true;
             debug_material.BackfaceCulling = false;
             debug_material.Lighting = false;
             driver->setMaterial(debug_material);

             driver->draw3DBox(BoundingBox, video::SColor(255,255,0,255));
           }

           if(draw_normals)
           {
             k = EXTENT_K * BoundingBox.getExtent().getLength();

             video::SMaterial debug_material;
             debug_material.Wireframe = true;
             debug_material.BackfaceCulling = false;
             debug_material.Lighting = false;
             driver->setMaterial(debug_material);

             /* draw normals */
             for (s32 vert=0; vert<vertexCount; ++vert)
             {
                 driver->draw3DLine(core::vector3df(vertexBuffer[vert].X, 
                                                    vertexBuffer[vert].Y,
                                                    vertexBuffer[vert].Z),
                                    core::vector3df(vertexBuffer[vert].X + NORMAL_K*k*normalBuffer[vert].X,
                                                    vertexBuffer[vert].Y + NORMAL_K*k*normalBuffer[vert].Y,
                                                    vertexBuffer[vert].Z + NORMAL_K*k*normalBuffer[vert].Z),
                                    video::SColor(255,0,255,0));
             }
           }
        } // for subId
        
    } // for meshId
    
    //----------------------------------------------------------//
    renderer->endRendering();                                   // Tell the renderer we are finished now
}
示例#6
0
	void VolumeRender::generate()
	{
		double start_time, end_time, dt;

		start_time = glfwGetTime();

		// Load tree
		int32_t tree_size = 0;
		tree_data = 0;
		
		// Load from file
		if (_scene == 0)
		{
			tree_size = rendering::read_full_file_binary(_treeFilename, &tree_data);

			if (tree_size == 0)
			{
				fprintf(stderr, "Invalid tree file: %s\n", _treeFilename);
				exit(1);
			}
		}
		else
		{
			char filename_buffer[1024];
			sprintf(filename_buffer, "scene%d.tree.%d", _scene, _depth);

			FILE* file = fopen(filename_buffer, "rb");

			if (file != nullptr)
			{
				// Load tree
				printf("Loading file %s\n", filename_buffer);
				fclose(file);

				tree_size = rendering::read_full_file_binary(filename_buffer, &tree_data);

				if (tree_size == 0)
				{
					fprintf(stderr, "Invalid tree file: %s\n", filename_buffer);
					exit(1);
				}
			}
			else
			{
				// Generate
				printf("Generating scene for the first time, please wait..\n");

				// Generate from sphere
				if (_scene == 1)
				{
					tree_size =
						rendering::genOctreeSphere((int32_t**)&tree_data, _depth,
						glm::vec3(0.5f, 0.5f, 0.5f), 0.4f);
				}

				// Generate from miku mesh
				if (_scene == 2)
				{
					if (_mesh.load("miku.md2"))
					{
						// Rotate mesh to right rotation (md2s are messed up like that..)
						glm::mat4 rotation = glm::rotate(180.0f, glm::vec3(0, 0, 1.0f));
						rotation = glm::rotate(rotation, 90.0f, glm::vec3(0, 1.0f, 0));
						_mesh.transform(rotation);

						tree_size = genOctreeMesh((int32_t**)&tree_data, _depth, &_mesh);
					}
				}

				// r = 1.5 sphere with embedded r = 1 sphere
				if (_scene == 3)
				{
					if (_mesh.load("miku.md2"))
					{
						// Rotate mesh to right rotation (md2s are messed up like that..)
						glm::mat4 rotation = glm::rotate(180.0f, glm::vec3(0, 0, 1.0f));
						rotation = glm::rotate(rotation, 90.0f, glm::vec3(0, 1.0f, 0));
						_mesh.transform(rotation);
			
						// Get min, max and func for octree generation
						glm::vec3 overall_min = *_mesh.getMin();
						glm::vec3 overall_max = *_mesh.getMax();
						overall_max += (overall_max - overall_min);

						// Make cube around bounds
						glm::vec3 extents = (overall_max - overall_min) * 0.5f;
						glm::vec3 centre = overall_min + extents;

						float greatest_extent = std::max(std::max(extents.x, extents.y), extents.z);
			
						extents.x = greatest_extent;
						extents.y = greatest_extent;
						extents.z = greatest_extent;
			
						overall_min = centre - extents;
						overall_max = centre + extents;

						// Sphere position
						glm::vec3 sphere_pos = centre;
						sphere_pos.x += extents.x * 0.5f;
						float sphere_radius = 10.0f;

						// Test function
						auto test_func = [&] (glm::vec3 min, glm::vec3 max, raw_attachment_uncompressed& shading_attributes)
						{
							glm::vec3 half_size = 0.5f * (max - min);
							glm::vec3 centre = min + half_size;
							float half_size_one_axis = half_size.x;

							//bool sphere_intersect = cubeSphereSurfaceIntersection(centre, half_size_one_axis, sphere_pos, sphere_radius);
							bool sphere_intersect = boxSphereIntersection(min, max, sphere_pos, sphere_radius);

							if (sphere_intersect)
							{
								// This is not normalised to save generation time
								// it is normalised later in the GPU anyway after being unpacked
								shading_attributes.normal = sphere_pos - centre;
								shading_attributes.colour = glm::vec4(1.0f, 1.0f, 1.0f, 0.5f);
								shading_attributes.reflectivity = 1.0f;

								shading_attributes.refractive_index = 1.5f;

								float distFromCentre = glm::length(shading_attributes.normal);

								if (distFromCentre < 0.5f * sphere_radius)
									shading_attributes.refractive_index = 1.0f;

								return true;
							}
							else
							{
								bool mesh_intersect = meshAABBIntersect(&_mesh, min, max, shading_attributes);

								if (mesh_intersect)
								{
									shading_attributes.colour.a = 1.0f;
									shading_attributes.reflectivity = 0.0f;
									return true;
								}
							}

							return false;
						};

						point_test_func func(test_func);

						// Generate octree
						tree_size = genOctree((int32_t**)&tree_data, _depth, func, overall_min, overall_max);
					}
				}

				// r = 1.5 sphere with hollow sphere (should be the same as above)
				if (_scene == 4)
				{
					if (_mesh.load("miku.md2"))
					{
						// Rotate mesh to right rotation (md2s are messed up like that..)
						glm::mat4 rotation = glm::rotate(180.0f, glm::vec3(0, 0, 1.0f));
						rotation = glm::rotate(rotation, 90.0f, glm::vec3(0, 1.0f, 0));
						_mesh.transform(rotation);
			
						// Get min, max and func for octree generation
						glm::vec3 overall_min = *_mesh.getMin();
						glm::vec3 overall_max = *_mesh.getMax();
						overall_max += (overall_max - overall_min);

						// Make cube around bounds
						glm::vec3 extents = (overall_max - overall_min) * 0.5f;
						glm::vec3 centre = overall_min + extents;

						float greatest_extent = std::max(std::max(extents.x, extents.y), extents.z);
			
						extents.x = greatest_extent;
						extents.y = greatest_extent;
						extents.z = greatest_extent;
			
						overall_min = centre - extents;
						overall_max = centre + extents;

						// Sphere position
						glm::vec3 sphere_pos = centre;
						sphere_pos.x += extents.x * 0.5f;
						float sphere_radius = 10.0f;

						// Test function
						auto test_func = [&] (glm::vec3 min, glm::vec3 max, raw_attachment_uncompressed& shading_attributes)
						{
							glm::vec3 half_size = 0.5f * (max - min);
							glm::vec3 centre = min + half_size;
							float half_size_one_axis = half_size.x;

							//bool sphere_intersect = cubeSphereSurfaceIntersection(centre, half_size_one_axis, sphere_pos, sphere_radius);
							bool sphere_intersect = boxSphereIntersection(min, max, sphere_pos, sphere_radius);

							if (sphere_intersect)
							{
								// This is not normalised to save generation time
								// it is normalised later in the GPU anyway after being unpacked
								shading_attributes.normal = sphere_pos - centre;
								shading_attributes.colour = glm::vec4(1.0f, 1.0f, 1.0f, 0.5f);
								shading_attributes.reflectivity = 1.0f;

								shading_attributes.refractive_index = 1.5f;

								float distFromCentre = glm::length(shading_attributes.normal);

								if (distFromCentre < 0.5f * sphere_radius)
									return false;


								return true;
							}
							else
							{
								bool mesh_intersect = meshAABBIntersect(&_mesh, min, max, shading_attributes);

								if (mesh_intersect)
								{
									shading_attributes.colour.a = 1.0f;
									shading_attributes.reflectivity = 0.0f;
									return true;
								}
							}

							return false;
						};

						point_test_func func(test_func);

						// Generate octree
						tree_size = genOctree((int32_t**)&tree_data, _depth, func, overall_min, overall_max);
					}
				}

				// Generate from mesh
				if (_scene == 5)
				{
					Mesh teapot("teapot.obj", true);
					Mesh checkerboard("checkerboard.obj", true);
					
					// Lift teapot off checkerboard a bit so they don't intersect
					glm::mat4 translation = glm::translate(glm::vec3(0.0f, 0.1f, 0.0f));
					glm::mat4 rotation = glm::rotate(180.0f, glm::vec3(0, 0, 1.0f));
					checkerboard.transform(translation * rotation);

					teapot.transform(rotation);
			
					// Get min, max and func for octree generation
					glm::vec3 overall_min = *teapot.getMin();
					glm::vec3 overall_max = *teapot.getMax();
					overall_max += (overall_max - overall_min);

					// Make cube around bounds
					glm::vec3 extents = (overall_max - overall_min) * 0.5f;
					glm::vec3 centre = overall_min + extents;

					float greatest_extent = std::max(std::max(extents.x, extents.y), extents.z);
			
					extents.x = greatest_extent;
					extents.y = greatest_extent;
					extents.z = greatest_extent;
			
					overall_min = centre - extents;
					overall_max = centre + extents;

					// Test function
					auto test_func = [&] (glm::vec3 min, glm::vec3 max, raw_attachment_uncompressed& shading_attributes)
					{
						if (meshAABBIntersect(&checkerboard, min, max, shading_attributes))
						{
							shading_attributes.colour.a = 1.0f;
							shading_attributes.reflectivity = 0.0f;

							return true;
						}

						if (meshAABBIntersect(&teapot, min, max, shading_attributes))
						{
							shading_attributes.colour.a = 0.3f;
							shading_attributes.reflectivity = 0.5f;

							return true;
						}

						return false;
					};

					point_test_func func(test_func);

					// Generate octree
					tree_size = genOctree((int32_t**)&tree_data, _depth, func, overall_min, overall_max);
				}

				// transparent and reflective boxes on checkerboard
				if (_scene == 6)
				{
					Mesh checkerboard("checkerboard.obj", true);

					// The cube should have flat normals instead of smooth
					Mesh box1("cube.obj", true, aiProcess_GenNormals);
					Mesh box2("cube.obj", true, aiProcess_GenNormals);

					// Rotate checkerboard
					glm::mat4 rotation = glm::rotate(180.0f, glm::vec3(0, 0, 1.0f));
					checkerboard.transform(rotation);

					// Scale and position box
					glm::mat4 translation = glm::translate(glm::vec3(0, 1.0f, 0));
					glm::mat4 scale = glm::scale(glm::vec3(0.25f));
					glm::mat4 box_transform = scale * translation;
					box1.transform(scale);
					box2.transform(scale);
			
					// Get min, max and func for octree generation
					glm::vec3 overall_min = *checkerboard.getMin();
					glm::vec3 overall_max = *checkerboard.getMax();
					overall_max += (overall_max - overall_min);

					// Make cube around bounds
					glm::vec3 extents = (overall_max - overall_min) * 0.5f;
					glm::vec3 centre = overall_min + extents;

					float greatest_extent = std::max(std::max(extents.x, extents.y), extents.z);
			
					extents.x = greatest_extent;
					extents.y = greatest_extent;
					extents.z = greatest_extent;
			
					overall_min = centre - extents;
					overall_max = centre + extents;

					// Test function
					auto test_func = [&] (glm::vec3 min, glm::vec3 max, raw_attachment_uncompressed& shading_attributes)
					{
						if (meshAABBIntersect(&checkerboard, min, max, shading_attributes))
						{
							shading_attributes.colour.a = 1.0f;
							shading_attributes.reflectivity = 0.0f;

							return true;
						}

						if (meshAABBIntersect(&box1, min, max, shading_attributes))
						{
							shading_attributes.colour.a = 1.0f;
							shading_attributes.reflectivity = 1.0f;

							return true;
						}

						return false;
					};

					point_test_func func(test_func);

					// Generate octree
					tree_size = genOctree((int32_t**)&tree_data, _depth, func, overall_min, overall_max);
				}

				// Reflective inverted box with teapot inside
				if (_scene == 7)
				{
					// The cube should have flat normals instead of smooth
					Mesh teapot("teapot.obj", true);
					Mesh box1("inverted_cube.obj", true, aiProcess_GenNormals);

					teapot.transform(glm::scale(glm::vec3(0.2f)) * glm::rotate(180.0f, glm::vec3(0.0f, 0.0f, 1.0f)));
			
					// Get min, max and func for octree generation
					glm::vec3 overall_min = *box1.getMin();
					glm::vec3 overall_max = *box1.getMax();
					overall_max += (overall_max - overall_min);

					// Make cube around bounds
					glm::vec3 extents = (overall_max - overall_min) * 0.5f;
					glm::vec3 centre = overall_min + extents;

					float greatest_extent = std::max(std::max(extents.x, extents.y), extents.z);
			
					extents.x = greatest_extent;
					extents.y = greatest_extent;
					extents.z = greatest_extent;
			
					overall_min = centre - extents;
					overall_max = centre + extents;

					// Test function
					auto test_func = [&] (glm::vec3 min, glm::vec3 max, raw_attachment_uncompressed& shading_attributes)
					{
						glm::vec3 aabb_extents = (max - min) * 0.5f;
						glm::vec3 aabb_centre = aabb_centre + min;

						if (meshAABBIntersect(&box1, min, max, shading_attributes))
						{
							shading_attributes.colour.a = 1.0f;
							shading_attributes.reflectivity = 1.0f;

							return true;
						}

						if (meshAABBIntersect(&teapot, min, max, shading_attributes))
						{
							shading_attributes.colour = glm::vec4(1.0f, 0.0f, 0.0f, 1.0f);
							shading_attributes.reflectivity = 0.0f;

							return true;
						}

						return false;
					};

					point_test_func func(test_func);

					// Generate octree
					tree_size = genOctree((int32_t**)&tree_data, _depth, func, overall_min, overall_max);
				}

				// Write custom generation to file
				if (_saveTrees)
				{
					printf("Writing %s...\n", filename_buffer);

					file = fopen(filename_buffer, "wb");

					if (file == nullptr)
					{
						fprintf(stderr, "Failed to open file for writing: %s\n", filename_buffer);
					}
					else
					{
						fwrite(tree_data, tree_size, sizeof(char), file);
						fclose(file);
					}
				}
			}
		}
		
		// Calculate time to load/generate
		end_time = glfwGetTime();
		dt = end_time - start_time;

		printf("Time to load/generate tree: %f\n", dt);
		printf("%.2fMB\n", tree_size / (1024.0f * 1024.0f));

		// Reset timer
		start_time = glfwGetTime();

		// Upload sphere to GPU
		gpuErrchk(cudaMalloc((void**)&_gpuTree, tree_size));
		gpuErrchk(cudaMemcpy(_gpuTree, tree_data, tree_size, cudaMemcpyHostToDevice));

		// Calculate time to upload
		end_time = glfwGetTime();
		dt = end_time - start_time;

		printf("Time to upload tree: %f\n", dt);
		printf("%.2fMB\n", tree_size / (1024.0f * 1024.0f));

		// Free CPU memory
		//free(tree_data);
	}
示例#7
0
bool		Triangle::isInBoundingBox(BoundingBox& box) const
{
  Point		maxBox = box.getMaxPoint();
  Point		minBox = box.getMinPoint();
  double	maxX = MAX(MAX(_vertex1._x, _vertex2._x),
			   _absolutePosition._x);
  double        maxY = MAX(MAX(_vertex1._y, _vertex2._y),
                           _absolutePosition._y);
  double        maxZ = MAX(MAX(_vertex1._z, _vertex2._z),
                           _absolutePosition._z);
  double        minX = MIN(MIN(_vertex1._x, _vertex2._x),
                           _absolutePosition._x);
  double        minY = MIN(MIN(_vertex1._y, _vertex2._y),
                           _absolutePosition._y);
  double        minZ = MIN(MIN(_vertex1._z, _vertex2._z),
                           _absolutePosition._z);

  Point		box1(minX, minY, minZ);
  Point		box2(maxX, maxY, maxZ);

  // Point		boxVertexes[8] =
  //   {
  //     Point(minBox._x, minBox._y, minBox._z),
  //     Point(minBox._x, minBox._y, maxBox._z),
  //     Point(minBox._x, maxBox._y, minBox._z),
  //     Point(minBox._x, maxBox._y, maxBox._z),
  //     Point(maxBox._x, minBox._y, minBox._z),
  //     Point(maxBox._x, minBox._y, maxBox._z),
  //     Point(maxBox._x, maxBox._y, minBox._z),
  //     Point(maxBox._x, maxBox._y, maxBox._z),
  //   };
  // Point	c((minBox._x + maxBox._x) / 2,
  // 	  (minBox._y + maxBox._y) / 2,
  // 	  (minBox._z + maxBox._z) / 2);
  // Point v0 = _absolutePosition - c,
  //   v1 = _vertex1 - c,
  //   v2 = _vertex2 - c;
  // Vector u = v1 - v0;
  // Vector v = v2 - v0;
  // c = Point();
  // Vector e[3] =
  //   {
  //     Vector(1, 0, 0),
  //     Vector(0, 1, 0),
  //     Vector(0, 0, 1),
  //   };
  // Vector f[3] =
  //   {
  //     v1 - v0,
  //     v2 - v1,
  //     v0 - v2,
  //   };
  // Vector axes[13] =
  //   {
  //     e[0],
  //     e[1],
  //     e[2],
  //     u^v,
  //     Vector(),
  //     Vector(),
  //     Vector(),
  //     Vector(),
  //     Vector(),
  //     Vector(),
  //     Vector(),
  //     Vector(),
  //     Vector(),
  //   };
  
  // for (int i = 0; i < 3; ++i)
  //   for (int j = 0; j < 3; ++j)
  //     axes[4 + i * 3 + j] = e[i]^f[j];
  // for (int i = 0; i < 13; ++i)
  //   {
  //     Vector	axe = axes[i];
  //     axe.normalize();
  //     double	min1 = axe * boxVertexes[0],
  // 	max1 = min1,
  // 	min2 = axe * v0,
  // 	max2 = min2;
  //     for (int j = 1; j < 8; ++j)
  // 	{
  // 	  double p = axe * boxVertexes[j];

  // 	  if (p < min1)
  // 	    min1 = p;
  // 	  else if (p > max1)
  // 	    max1 = p;
  // 	}
  //     double p = axe * v1;
  //     if (p < min2)
  // 	min2 = p;
  //     else if (p > max2)
  // 	max2 = p;
  //     p = axe * v2;
  //     if (p < min2)
  // 	min2 = p;
  //     else if (p > max2)
  // 	max2 = p;
  //     if (min1 > max2 || max1 < min2)
  // 	return (false);
  //   }
  // return (true);

  if(box1._x <= maxBox._x && box2._x >= minBox._x &&
     box1._y <= maxBox._y && box2._y >= minBox._y &&
     box1._z <= maxBox._z && box2._z >= minBox._z)
    return (true);
  return (false);
}
示例#8
0
int main ()
{
  printf ("Results of axis_aligned_box_test:\n");

  aaboxf box, box1 (vec3f (-10, -20, -30), vec3f (30, 20, 10)), box2 (1, 2, 3, 4, 5, 6);

  printf ("default constructor\n");
  dump (box);
  printf ("\nvector constructor\n");
  dump (box1);
  printf ("\nscalar constructor\n");
  dump (box2);
  printf ("\n");

  printf ("set_extents\n");
  box.set_extents (-1, -2, -3, 3, 2, 1);
  dump (box);
  printf ("\n");

  printf ("reset\n");
  box.reset ();
  dump (box);
  printf ("\n");

  printf (box.empty () ? "box is empty\n" : "box is not empty\n");

  printf ("set_minimum\n");
  box.set_minimum (-2, -4, -6);
  dump (box);
  printf ("\n");

  printf ("set_maximum\n");
  box.set_maximum (6, 8, 10);
  dump (box);
  printf ("\n");

  printf (box.empty () ? "box is empty\n" : "box is not empty\n");

  printf ("statistics\n");
  printf ("  center: ");
  dump (box.center ());
  printf ("\n  size: ");
  dump (box.size ());
  printf ("\n  radius: %.2f\n", box.radius ());
  printf ("  volume: %g\n", volume (box));

  printf ("corners:\n");

  static const char* corner_name [] = {
    "(Xmin, Ymin, Zmin)",
    "(Xmax, Ymin, Zmin)",
    "(Xmin, Ymax, Zmin)",
    "(Xmax, Ymax, Zmin)",
    "(Xmin, Ymin, Zmax)",
    "(Xmax, Ymin, Zmax)",
    "(Xmin, Ymax, Zmax)",
    "(Xmax, Ymax, Zmax)",
  };

  vec3f corners [8];

  box.get_corners (corners);

  for (int i=0; i<8; i++)
  {
    vec3f corner = box.corner ((box_corner)i);

    printf ("  %s=", corner_name [i]);
    dump   (corner);
    printf ("\n");

    if (corners [i] != corner)
    {
      printf ("  fuctions corner and get_corners has different results at compute corner %s:\n", corner_name [i]);
      printf ("    corner function result: ");
      dump   (corner);
      printf ("\n    get_corners result: ");
      dump   (corners [i]);
      printf ("\n");
    }
  }

  vec3f test_point (-20, 30, 0);

  printf ("add test point\n");

  box += test_point;

  dump (box);
  printf ("\n");

  printf ("add box\n");

  box += box1;

  dump (box);
  printf ("\n");

  printf ("multiply on quaternion\n");
  box *= to_quat (degree (90.0f), vec3f (1, 0, 0));
  dump (box);
  printf ("\n");

  printf ("muliply on matrix\n");
  box *= translate (vec3f (10, 20, 30));
  dump (box);
  printf ("\n");

  printf ("intersects:\n");
  printf ("  box with box1: %d, intersection: ", intersects (box, box1));
  dump   (intersection (box, box1));
  printf ("\n");
  printf ("  box1 with box: %d, intersection: ", intersects (box1, box));
  dump   (intersection (box1, box));
  printf ("\n");

  printf ("intersects:\n");
  printf ("  box with box2: %d, intersection: ", intersects (box, box2));
  dump   (intersection (box, box2));
  printf ("\n");
  printf ("  box2 with box: %d, intersection: ", intersects (box2, box));
  dump   (intersection (box2, box));
  printf ("\n");

  printf ("contains point: %d\n", contains (box, vec3f (10.0f)));
  printf ("contains box1: %d\n", contains (box, box1));
//  printf ("contains intersection (box, box1): %d\n", contains (box, intersection (box, box1)));  //В результате пересечения получается пустой box, из-за дрожания результат проверки зависит от компилятора

  printf ("box == box: %d\n", box == box);
  printf ("box != box: %d\n", box != box);
  printf ("box == box1: %d\n", box == box1);
  printf ("box != box1: %d\n", box != box1);

  return 0;
}
示例#9
0
文件: maze.cpp 项目: sudogem/cpp-maze
/* ---------------------- MAZE MAIN CONTROLLER -----------------------------*/
void playMaze(){
int c;
int x = 10;
int y = 21;
int readytomove = 0;
int startmove = 1;
int direction;
  box1(3,3,78,48,GOINGDOWN,BLACK,5);

  textcolor(WHITE);
  gotoxy(41,9); cprintf(" this is Dencie");
  gotoxy(39,30); cprintf(" this is Mark");
  gotoxy(30,45); textcolor(RED); cprintf("Press ESC to back to Main...");
  initWall();
  char s;

 // zergslocation();

  gotoxy(12,1); textcolor(YELLOW|BLINK); cprintf("");
  gotoxy(x,y-1); textcolor(WHITE); cprintf("");

  while((c=getch())!=27 && startmove!=0) {
  map();

     gotoxy(12,1); textcolor(YELLOW|BLINK); cprintf("");
     switch(c){
	  case 80:  // down
		y++;
		direction = fromDown;
		break;
	  case 75:  // left
		x--;
		direction = fromLeft;
		break;
	  case 72:  // up
		y--;
		direction = fromUp;
		break;
	  case 77:  // right
		x++;
		direction = fromRight;
		break;
	  case 115:
		zergslocation();
		break;
     }
     if ((matrix[x][y])==1 || (matrix[x][y])== -1 ||
	   (matrix[x][y]) == -2 ){
	  gotoxy(x,y); textcolor(15); cprintf("");
	  readytomove = 1;
	  if ((matrix[x][y])== -1) { // REACH ITS MAZE ENDING PT.
	      window(1,1,80,50);
	      box1(30,18,49,22,GOINGLEFT,BROWN,10);
	      drawbox(30,18,49,22,YELLOW);
	      gotoxy(32,19); textcolor(WHITE|BLINK); cprintf("CONGRATULATIONS!");
	      gotoxy(33,20); textcolor(YELLOW); cprintf("ÄÄÄÄÄÄÄÄÄÄÄÄÄÄ");
	      gotoxy(34,21); textcolor(GREEN); cprintf("Youve made it!");
	      startmove = 0;
	  }
	  if ((matrix[x][y])== -2) { // ZERGLINGS ATTACKED
	      window(1,1,80,50);
	      box1(30,18,49,22,GOINGLEFT,BROWN,10);
	      drawbox(30,18,49,22,YELLOW);
	      gotoxy(32,19); textcolor(WHITE|BLINK); cprintf("ZERGLINGS ATTACK");
	      gotoxy(33,20); textcolor(YELLOW); cprintf("ÄÄÄÄÄÄÄÄÄÄÄÄÄÄ");
	      gotoxy(34,21); textcolor(GREEN); cprintf("You failed!");
	      startmove = 0;
	  }

     }
     else {
       if(readytomove){
	 switch(direction){
	    case fromDown:
			y--;
			break;
	    case fromUp  :
			y++;
			break;
	    case fromLeft :
			x++;
			break;
	    case fromRight :
			x--;
			break;
	 }
	 gotoxy(x,y); textcolor(RED); cprintf("");
       }
     }


     //gotoxy(20,22); printf("x:%d, y:%d  ",x,y);
     //gotoxy(20,23); printf("px:%d, py:%d  ",prevx,prevy);
     //gotoxy(20,24); printf("matrix[%d][%d] : %d  ",x,y,matrix[x][y]);

   }//endwhile
   while(1){
     c=getch();
     if (c==ESC) break;
   }
   window(1,1,80,50);
   box1(3,3,78,48,GOINGDOWN,BLACK,5);
}
示例#10
0
文件: maze.cpp 项目: sudogem/cpp-maze
/* ----------------------- DISPLAY PROGRAM NAME ---------------------------*/
void progname(){

//char p[8] = { 0xAA, 0x55, 0xAA, 0x34, 0xAA, 0x55, 0xAA, 0x55 };
//char p[8] =    { 0x33, 0x33, 0xCC, 0xCC, 0x33, 0x33, 0xCC, 0xCC };
//char p[8] =    { 0xF0, 0xF0, 0xF0, 0xF0, 0x0F, 0x0F, 0x0F, 0x0F };
//char p[8] =    { 0x00, 0x10, 0x28, 0x44, 0x28, 0x10, 0x00, 0x00 };
//char p[8] =    { 0x00, 0x70, 0x20, 0x27, 0x24, 0x24, 0x07, 0x00 };
//char p[8] =    { 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00 };
//char p[8] =    { 0x00, 0x00, 0x3C, 0x3C, 0x3C, 0x3C, 0x00, 0x00 };
//char p[8] =    { 0x00, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x00 };
//char p[8] =    { 0x00, 0x00, 0x22, 0x08, 0x00, 0x22, 0x1C, 0x00 };
//char p[8] =    { 0xFF, 0x7E, 0x3C, 0x18, 0x18, 0x3C, 0x7E, 0xFF };
//char p[8] =    { 0x00, 0x10, 0x10, 0x7C, 0x10, 0x10, 0x00, 0x00 };
//char p[8] =    { 0x00, 0x42, 0x24, 0x18, 0x18, 0x24, 0x42, 0x00 };


  initgraphix();
  setbkcolor(BLACK);
  setfillstyle(SOLID_FILL,GREEN);
  //setfillpattern(p,BROWN);
  bar(193,170,462,240);

  setfillstyle(SOLID_FILL,BROWN);
  bar(193,223,462,240);

  setcolor(DARKGRAY);
  rectangle(193,223,462,240); // MIDDLE RECT

  setcolor(DARKGRAY);
  rectangle(191,168,464,242);   // TOP RECT


  setfillstyle(SOLID_FILL,RED);
  settextstyle(0,HORIZ_DIR,2);
  setcolor(BLACK);
  outtextxy(190,225,"in da Lost Temple");

  setcolor(WHITE);
  outtextxy(191,226,"in da Lost Temple");

  settextstyle(3,HORIZ_DIR,4);

  setcolor(LIGHTGREEN);
  outtextxy(215,177,"Mark & Dencie");

  settextstyle(0,HORIZ_DIR,1);
  //outtextxy(335,257,"TMNT");

  while(1){
	if (kbhit()){
	int c;
	   c = getch();
	   if (c == ESC ) exit(0);
	   else break;
	}
	settextstyle(2,HORIZ_DIR,4);
	setcolor(LIGHTBLUE);

	outtextxy(getmaxx()/2-66,410,"® press key to continue ¯");
	delay(90);

	setcolor(BLACK);
	outtextxy(getmaxx()/2-66,410,"® press key to continue ¯");
	delay(50);
  }
  //getch();
  destroygraphix();
  //exit(0);
  restorecrtmode();
  _setcursortype(_NOCURSOR);
  delay(400);
  box1(1,1,80,50,GOINGDOWN,RED,0);
  box1(2,2,79,49,GOINGDOWN,BROWN,0);
  box1(3,3,78,48,GOINGDOWN,BLACK,0);
}
void Dialog::SpellInfo(const std::string &header, const std::string &message, const Spell & spell, bool ok_button)
{
    Display & display = Display::Get();
    const int system = Settings::Get().ExtGameEvilInterface() ? ICN::SYSTEME : ICN::SYSTEM;

    // cursor
    Cursor & cursor = Cursor::Get();

    cursor.Hide();
    cursor.SetThemes(cursor.POINTER);

    TextBox box1(header, Font::YELLOW_BIG, BOXAREA_WIDTH);
    TextBox box2(message, Font::BIG, BOXAREA_WIDTH);
    Text text(spell.GetName(), Font::SMALL);

    const Sprite & sprite = AGG::GetICN(ICN::SPELLS, spell.IndexSprite());
    const int spacer = Settings::Get().QVGA() ? 5 : 10;

    FrameBox box(box1.h() + spacer + box2.h() + spacer + sprite.h() + 2 + text.h(), ok_button);
    Rect pos = box.GetArea();

    if(header.size()) box1.Blit(pos);
    pos.y += box1.h() + spacer;

    if(message.size()) box2.Blit(pos);
    pos.y += box2.h() + spacer;

    // blit sprite
    pos.x = box.GetArea().x + (pos.w - sprite.w()) / 2;
    sprite.Blit(pos.x, pos.y);

    // small text
    pos.x = box.GetArea().x + (pos.w - text.w()) / 2;
    pos.y = pos.y + sprite.h() + 2;
    text.Blit(pos);

    LocalEvent & le = LocalEvent::Get();

    Button* button = NULL;
    Point pt;

    if(ok_button)
    {
        pt.x = box.GetArea().x + (box.GetArea().w - AGG::GetICN(system, 1).w()) / 2;
        pt.y = box.GetArea().y + box.GetArea().h - AGG::GetICN(system, 1).h();
	button = new Button(pt.x, pt.y, system, 1, 2);
    }

    if(button) (*button).Draw();

    cursor.Show();
    display.Flip();

    // message loop
    while(le.HandleEvents())
    {
        if(!ok_button && !le.MousePressRight()) break;
	if(button) le.MousePressLeft(*button) ? button->PressDraw() : button->ReleaseDraw();
        if(button && le.MouseClickLeft(*button)){ break; }
	if(HotKeyCloseWindow){ break; }
    }

    cursor.Hide();
    if(button) delete button;
}
示例#12
0
int main()
{

  // User-defined main parameters
  double t0 = 0;                   // initial computation time
  double T = 20.0;                 // end of computation time
  double h = 0.005;                // time step
  double position_init = 10.0;     // initial position
  double velocity_init = 0.0;      // initial velocity

  double g = 9.81;
  double theta = 0.5;              // theta for MoreauJeanOSI integrator

  // -----------------------------------------
  // --- Dynamical systems && interactions ---
  // -----------------------------------------

  try
  {

    // ------------
    // --- Init ---
    // ------------

    std::cout << "====> Model loading ..." << std::endl << std::endl;


    // -- OneStepIntegrators --
    SP::OneStepIntegrator osi;
    osi.reset(new MoreauJeanOSI(theta));

    // -- Model --
    SP::Model model(new Model(t0, T));

    std::vector<SP::BulletWeightedShape> shapes;

    // note: no rebound with a simple Bullet Box, why ?
    // the distance after the broadphase contact detection is negative
    // and then stay negative.
    // SP::btCollisionShape box(new btBoxShape(btVector3(1,1,1)));
    // SP::BulletWeightedShape box1(new BulletWeightedShape(box,1.0));
    // This is ok if we build one with btConveHullShape
    SP::btCollisionShape box(new btConvexHullShape());
    {
      std11::static_pointer_cast<btConvexHullShape>(box)->addPoint(btVector3(-1.0, 1.0, -1.0));
      std11::static_pointer_cast<btConvexHullShape>(box)->addPoint(btVector3(-1.0, -1.0, -1.0));
      std11::static_pointer_cast<btConvexHullShape>(box)->addPoint(btVector3(-1.0, -1.0, 1.0));
      std11::static_pointer_cast<btConvexHullShape>(box)->addPoint(btVector3(-1.0, 1.0, 1.0));
      std11::static_pointer_cast<btConvexHullShape>(box)->addPoint(btVector3(1.0, 1.0, 1.0));
      std11::static_pointer_cast<btConvexHullShape>(box)->addPoint(btVector3(1.0, 1.0, -1.0));
      std11::static_pointer_cast<btConvexHullShape>(box)->addPoint(btVector3(1.0, -1.0, -1.0));
      std11::static_pointer_cast<btConvexHullShape>(box)->addPoint(btVector3(1.0, -1.0, 1.0));
    }
    SP::BulletWeightedShape box1(new BulletWeightedShape(box, 1.0));
    shapes.push_back(box1);

    SP::SiconosVector q0(new SiconosVector(7));
    SP::SiconosVector v0(new SiconosVector(6));
    v0->zero();
    q0->zero();

    (*q0)(2) = position_init;
    (*q0)(3) = 1.0;
    (*v0)(2) = velocity_init;

    // -- The dynamical system --
    // -- the default contactor is the shape given in the constructor
    // -- the contactor id is 0
    SP::BulletDS body(new BulletDS(box1, q0, v0));

    // -- Set external forces (weight) --
    SP::SiconosVector FExt;
    FExt.reset(new SiconosVector(3)); //
    FExt->zero();
    FExt->setValue(2, - g * box1->mass());
    body->setFExtPtr(FExt);

    // -- Add the dynamical system in the non smooth dynamical system
    model->nonSmoothDynamicalSystem()->insertDynamicalSystem(body);

    SP::btCollisionObject ground(new btCollisionObject());
    ground->setCollisionFlags(btCollisionObject::CF_STATIC_OBJECT);
    SP::btCollisionShape groundShape(new btBoxShape(btVector3(30, 30, .5)));
    btMatrix3x3 basis;
    basis.setIdentity();
    ground->getWorldTransform().setBasis(basis);
    ground->setCollisionShape(&*groundShape);
    ground->getWorldTransform().getOrigin().setZ(-.50);

    // ------------------
    // --- Simulation ---
    // ------------------

    // -- Time discretisation --
    SP::TimeDiscretisation timedisc(new TimeDiscretisation(t0, h));

    // -- OneStepNsProblem --
    SP::FrictionContact osnspb(new FrictionContact(3));

    // -- Some configuration

    osnspb->numericsSolverOptions()->iparam[0] = 1000; // Max number of
    // iterations
    osnspb->numericsSolverOptions()->dparam[0] = 1e-5; // Tolerance


    osnspb->setMaxSize(16384);                        // max number of
    // interactions

    osnspb->setMStorageType(1);                      // Sparse storage

    osnspb->setNumericsVerboseMode(0);               // 0 silent, 1
    // verbose

    osnspb->setKeepLambdaAndYState(true);            // inject
    // previous
    // solution

    // --- Simulation initialization ---

    std::cout << "====> Simulation initialisation ..." << std::endl << std::endl;

    int N = ceil((T - t0) / h); // Number of time steps


    SP::NonSmoothLaw nslaw(new NewtonImpactFrictionNSL(0.8, 0., 0.0, 3));

    // -- The space filter performs broadphase collision detection
    SP::BulletSpaceFilter space_filter(new BulletSpaceFilter(model));

    // -- insert a non smooth law for contactors id 0
    space_filter->insert(nslaw, 0, 0);

    // -- add multipoint iterations, this is needed to gather at least
    // -- 3 contact points and avoid objects penetration, see Bullet
    // -- documentation
    space_filter->collisionConfiguration()->setConvexConvexMultipointIterations();
    space_filter->collisionConfiguration()->setPlaneConvexMultipointIterations();

    // -- The ground is a static object
    // -- we give it a group contactor id : 0
    space_filter->addStaticObject(ground, 0);

    // -- MoreauJeanOSI Time Stepping with Bullet Dynamical Systems
    SP::BulletTimeStepping simulation(new BulletTimeStepping(timedisc));

    simulation->insertIntegrator(osi);
    simulation->insertNonSmoothProblem(osnspb);
    model->setSimulation(simulation);

    model->initialize();

    std::cout << "====> End of initialisation ..." << std::endl << std::endl;

    // --- Get the values to be plotted ---
    // -> saved in a matrix dataPlot
    unsigned int outputSize = 4;
    SimpleMatrix dataPlot(N + 1, outputSize);
    dataPlot.zero();

    SP::SiconosVector q = body->q();
    SP::SiconosVector v = body->velocity();

    dataPlot(0, 0) = model->t0();
    dataPlot(0, 1) = (*q)(2);
    dataPlot(0, 2) = (*v)(2);

    // --- Time loop ---

    std::cout << "====> Start computation ... " << std::endl << std::endl;
    // ==== Simulation loop - Writing without explicit event handling =====
    int k = 1;
    boost::progress_display show_progress(N);

    boost::timer time;
    time.restart();

    while (simulation->hasNextEvent())
    {
      space_filter->buildInteractions(model->currentTime());

      simulation->computeOneStep();

      // --- Get values to be plotted ---
      dataPlot(k, 0) =  simulation->nextTime();
      dataPlot(k, 1) = (*q)(2);
      dataPlot(k, 2) = (*v)(2);

      // If broadphase collision detection shows some contacts then we may
      // display contact forces.
      if (space_filter->collisionWorld()->getDispatcher()->getNumManifolds() > 0)
      {

        // we *must* have an indexSet0, filled by Bullet broadphase
        // collision detection and an indexSet1, filled by
        // TimeStepping::updateIndexSet with the help of Bullet
        // getDistance() function
        if (model->nonSmoothDynamicalSystem()->topology()->numberOfIndexSet() == 2)
        {
          SP::InteractionsGraph index1 = simulation->indexSet(1);

          // This is the narrow phase contact detection : if
          // TimeStepping::updateIndexSet has filled indexSet1 then we
          // have some contact forces to display
          if (index1->size() > 0)
          {

            // Four contact points for a cube with a side facing the
            // ground. Note : changing Bullet margin for collision
            // detection may lead this assertion to be false.
            if (index1->size() == 4)
            {
              InteractionsGraph::VIterator iur = index1->begin();

              // different version of bullet may not gives the same
              // contact points! So we only keep the summation.
              dataPlot(k, 3) =
                index1->bundle(*iur)-> lambda(1)->norm2() +
                index1->bundle(*++iur)->lambda(1)->norm2() +
                index1->bundle(*++iur)->lambda(1)->norm2() +
                index1->bundle(*++iur)->lambda(1)->norm2();
            }
          }
        }
      }

      simulation->nextStep();
      ++show_progress;
      k++;
    }


    std::cout << std::endl << "End of computation - Number of iterations done: " << k - 1 << std::endl;
    std::cout << "Computation Time " << time.elapsed()  << std::endl;

    // --- Output files ---
    std::cout << "====> Output file writing ..." << std::endl;
    dataPlot.resize(k, outputSize);
    ioMatrix::write("result.dat", "ascii", dataPlot, "noDim");

    // Comparison with a reference file
    SimpleMatrix dataPlotRef(dataPlot);
    dataPlotRef.zero();
    ioMatrix::read("result.ref", "ascii", dataPlotRef);

    if ((dataPlot - dataPlotRef).normInf() > 1e-12)
    {
      std::cout << "Warning. The result is rather different from the reference file : "
                << (dataPlot - dataPlotRef).normInf() << std::endl;
      return 1;
    }



  }

  catch (SiconosException e)
  {
    std::cout << e.report() << std::endl;
    exit(1);
  }
  catch (...)
  {
    std::cout << "Exception caught in BulletBouncingBox" << std::endl;
    exit(1);
  }

  return 0;
}
void RoiManager::execute() {
	LOG(INFO) << "RoiManager: Adding a new ROI.";
	if (inputDataIds.size() < 1) {
		LOG(WARNING) << "RoiManager: Not enough input IDs.";
		return;
	}

	brics_3d::rsg::Id rootId = inputDataIds[0];

	Eigen::AngleAxis<double> rotation(roiPitch, Eigen::Vector3d(1,0,0));
	Transform3d transformation;
	transformation = Eigen::Affine3d::Identity();
	transformation.translate(Eigen::Vector3d(roiCenterX,roiCenterY,roiCenterZ));
	transformation.rotate(rotation);
	brics_3d::HomogeneousMatrix44::IHomogeneousMatrix44Ptr transform(new brics_3d::HomogeneousMatrix44(&transformation));

	brics_3d::rsg::Id tfBox1Id = 0;
	brics_3d::rsg::Id Box1Id = 0;
	vector<brics_3d::rsg::Attribute> tmpAttributes;
	tmpAttributes.clear();
	tmpAttributes.push_back(Attribute("name","roi_box_tf"));
	wm->scene.addTransformNode(rootId, tfBox1Id, tmpAttributes, transform, brics_3d::rsg::TimeStamp(timer.getCurrentTime()));


	brics_3d::rsg::Box::BoxPtr box1(new brics_3d::rsg::Box(roiBoxSizeX, roiBoxSizeY, roiBoxSizeZ));
	tmpAttributes.clear();
	tmpAttributes.push_back(Attribute("name","roi_box"));
//	tmpAttributes.push_back(Attribute("debugInfo","no_visualization"));
	tmpAttributes.push_back(Attribute("rsgInfo","non_shared"));
	wm->scene.addGeometricNode(tfBox1Id, Box1Id, tmpAttributes, box1, brics_3d::rsg::TimeStamp(timer.getCurrentTime()));
	LOG(DEBUG) << "ROI Box added with ID " << Box1Id;

	/* Here comes a basic robot skeleton */
	brics_3d::rsg::Id tfWorldToRobotId = 0;
	tmpAttributes.clear();
	tmpAttributes.push_back(Attribute("name","world_to_robot_tf"));
	brics_3d::HomogeneousMatrix44::IHomogeneousMatrix44Ptr initialWorldToRobotTransform(new brics_3d::HomogeneousMatrix44());
	wm->scene.addTransformNode(wm->scene.getRootId(), tfWorldToRobotId, tmpAttributes, initialWorldToRobotTransform, brics_3d::rsg::TimeStamp(timer.getCurrentTime()));

	brics_3d::rsg::Id tfRobotToSensorId = 0;
	tmpAttributes.clear();
	tmpAttributes.push_back(Attribute("name","robot_to_sensor_tf"));
	brics_3d::HomogeneousMatrix44::IHomogeneousMatrix44Ptr initialRobotToSensorTransform(new brics_3d::HomogeneousMatrix44());
	LOG(DEBUG) << "current times stamp for frame = "<< timer.getCurrentTime();
	wm->scene.addTransformNode(tfWorldToRobotId, tfRobotToSensorId, tmpAttributes, initialRobotToSensorTransform, brics_3d::rsg::TimeStamp(timer.getCurrentTime()));



	/* We will add a hook for the processing data */
	brics_3d::rsg::Id sensorGroupId;
	tmpAttributes.clear();
	tmpAttributes.push_back(Attribute("name","sensor"));
	wm->scene.addGroup(tfRobotToSensorId, sensorGroupId, tmpAttributes);
	LOG(DEBUG) << "Sensor group added with ID " << sensorGroupId;

	/* We will add a hook for the scene objects */
	brics_3d::rsg::Id sceneObjectsGroupId;
	tmpAttributes.clear();
	tmpAttributes.push_back(Attribute("name","sceneObjects"));
	wm->scene.addGroup(wm->scene.getRootId(), sceneObjectsGroupId, tmpAttributes);
	LOG(DEBUG) << "Scene objects group  added with ID " << sensorGroupId;

}
示例#14
0
void LevelMap::Initialize()
{
	Objects.resize(20);
	ObjectsM.resize(21);

	//Objects Loading
	Objects[0].LoadFromFile("data/models/Level_1/Working texture/Mountain2/MountnN14_3ds.3ds");
	Objects[1].LoadFromFile("data/models/Level_1/Working texture/Stable/Stable.3ds");
	Objects[2].LoadFromFile("data/models/Level_1/Working texture/House3/polHouse1.3ds");
	Objects[3].LoadFromFile("data/models/Level_1/Working texture/House8/3ds file.3ds");
	Objects[4].LoadFromFile("data/models/Level_1/Working texture/House4/fachwerk40T.3ds");
	Objects[5].LoadFromFile("data/models/Level_1/Working texture/Jeep/Jeep.3ds");
	Objects[6].LoadFromFile("data/models/Level_1/Working texture/Tent/Tent yurt N231013.3ds");
	Objects[7].LoadFromFile("data/models/Level_1/Working texture/Wagen/wagen1_Lp_End.3ds");
	Objects[8].LoadFromFile("data/models/Level_1/Working texture/Tree4/dead_trees.3ds");

	for (int i = 0; i < 9; i++){
		Objects[i].Initialize();
	}

	//setting bounding Boxes
	for (int i = 1; i < 9; i++)
	{
		Objects[i].SetBoundingBox(CollidableModel::CalculateBoundingBox(Objects[i].GetVertices()));
	}

	ObjectsM[0] = glm::mat4(1);
	ObjectsM[1] = glm::translate(5.5f, -0.2f, -4.3f) *glm::rotate(270.0f, 0.0f, 1.0f, 0.0f) *glm::scale(0.003f, 0.003f, 0.003f);
	auto tempBox = Objects[1].GetBoundingBox();
	tempBox.Scale(0.003f, 0.003f, 0.003f);
	tempBox.Rotate(270.0f, 0.0f, 1.0f, 0.0f);
	tempBox.Translate(5.5f, -0.2f, -4.3f);
	Objects[1].SetBoundingBox(tempBox);

	ObjectsM[2] = glm::translate(5.5f, -0.2f, 0.0f) *glm::rotate(270.0f, 0.0f, 1.0f, 0.0f) *glm::scale(0.03f, 0.03f, 0.03f);
	tempBox = Objects[2].GetBoundingBox();
	tempBox.Scale(0.03f, 0.03f, 0.03f);
	tempBox.Rotate(270.0f, 0.0f, 1.0f, 0.0f);
	tempBox.Translate(5.5f, -0.2f, 0.0f);
	Objects[2].SetBoundingBox(tempBox);

	ObjectsM[3] = glm::translate(-2.9f, -0.2f, -3.4f) *glm::rotate(90.0f, 0.0f, 1.0f, 0.0f) *glm::scale(0.06f, 0.06f, 0.06f);
	tempBox = Objects[3].GetBoundingBox();
	tempBox.Scale(0.06f, 0.06f, 0.06f);
	tempBox.Rotate(90.0f, 0.0f, 1.0f, 0.0f);
	tempBox.Translate(-2.9f, -0.2f, -3.4f);
	Objects[3].SetBoundingBox(tempBox);

	ObjectsM[4] = glm::translate(1.7f, -0.2f, 5.0f) *glm::rotate(270.0f, 0.0f, 1.0f, 0.0f) *glm::scale(0.18f, 0.18f, 0.18f);
	tempBox = Objects[4].GetBoundingBox();
	tempBox.Scale(0.18f, 0.18f, 0.18f);
	tempBox.Rotate(270.0f, 0.0f, 1.0f, 0.0f);
	tempBox.Translate(1.7f, -0.2f, 5.0f);
	Objects[4].SetBoundingBox(tempBox);

	ObjectsM[5] = glm::translate(5.5f, -0.2f, 5.0f) *glm::rotate(180.0f, 0.0f, 1.0f, 0.0f) *glm::scale(0.004f, 0.004f, 0.004f);
	tempBox = Objects[5].GetBoundingBox();
	tempBox.Scale(0.004f, 0.004f, 0.004f);
	tempBox.Rotate(180.0f, 0.0f, 1.0f, 0.0f);
	tempBox.Translate(5.5f, -0.2f, 5.0f);
	Objects[5].SetBoundingBox(tempBox);

	ObjectsM[6] = glm::translate(-5.5f, -0.2f, 1.4f) *glm::scale(0.001f, 0.001f, 0.001f);
	tempBox = Objects[6].GetBoundingBox();
	tempBox.Scale(0.001f, 0.001f, 0.001f);
	tempBox.Translate(-5.5f, -0.2f, 1.4f);
	Objects[6].SetBoundingBox(tempBox);

	ObjectsM[7] = glm::translate(-4.7f, -0.2f, 3.4f) *glm::rotate(270.0f, 0.0f, 1.0f, 0.0f) *glm::scale(0.002f, 0.002f, 0.002f);
	tempBox = Objects[7].GetBoundingBox();
	tempBox.Scale(0.002f, 0.002f, 0.002f);
	tempBox.Rotate(270.0f, 0.0f, 1.0f, 0.0f);
	tempBox.Translate(-4.7f, -0.2f, 3.4f);
	Objects[7].SetBoundingBox(tempBox);

	ObjectsM[8] = glm::translate(-2.4f, -0.2f, 7.0f) * glm::scale(0.06f, 0.06f, 0.06f);
	tempBox = Objects[8].GetBoundingBox();
	tempBox.Scale(0.06f, 0.06f, 0.06f);
	tempBox.Translate(-2.4f, -0.2f, 7.0f);
	Objects[8].SetBoundingBox(tempBox);

	//right
	ObjectsM[9] = glm::translate(12.0f, -0.4f, 0.0f) * glm::scale(0.002f, 0.002f, 0.002f);
	AABoundingBox box(glm::vec3(8.0f, -0.2f, 0.0f), glm::vec3(1.0f, 10.0f, 30.0f));
	Objects[0].SetBoundingBox(box);
	ObjectsM[10] = glm::translate(12.0f, -0.4f, 8.0f) * glm::scale(0.002f, 0.002f, 0.002f);
	ObjectsM[11] = glm::translate(12.0f, -0.4f, -8.0f) * glm::scale(0.002f, 0.002f, 0.002f);
	
	//Left 
	ObjectsM[12] = glm::translate(-12.0f, -0.4f, 0.0f) * glm::scale(0.002f, 0.002f, 0.002f);
	AABoundingBox box1(glm::vec3(-8.0f, -0.2f, 0.0f), glm::vec3(1.0f, 10.0f, 30.0f));
	Objects[9].SetBoundingBox(box1);
	ObjectsM[13] = glm::translate(-12.0f, -0.4f, 8.0f) * glm::scale(0.002f, 0.002f, 0.002f);
	ObjectsM[14] = glm::translate(-12.0f, -0.4f, -8.0f) * glm::scale(0.002f, 0.002f, 0.002f);
	
	//Front
	ObjectsM[15] = glm::translate(0.0f, -0.4f, -11.0f) * glm::scale(0.002f, 0.002f, 0.002f);
	AABoundingBox box2(glm::vec3(0.0f, -0.2f, -7.0f), glm::vec3(30.0f, 10.0f, 1.0f));
	Objects[10].SetBoundingBox(box2);
	ObjectsM[16] = glm::translate(7.0f, -0.4f, -11.0f) * glm::scale(0.002f, 0.002f, 0.002f);
	ObjectsM[17] = glm::translate(-7.0f, -0.4f, -11.0f) * glm::scale(0.002f, 0.002f, 0.002f);
	
	////BackMountains
	ObjectsM[18] = glm::translate(0.0f, -0.4f, 11.0f) *glm::rotate(270.0f, 0.0f, 1.0f, 0.0f)* glm::scale(0.002f, 0.002f, 0.002f);
	AABoundingBox box3(glm::vec3(0.0f, -0.2f, 7.0f), glm::vec3(30.0f, 10.0f, 1.0f));
	Objects[11].SetBoundingBox(box3);
	ObjectsM[19] = glm::translate(7.0f, -0.4f, 11.0f) *glm::rotate(270.0f, 0.0f, 1.0f, 0.0f)* glm::scale(0.002f, 0.002f, 0.002f);
	ObjectsM[20] = glm::translate(-7.0f, -0.4f, 11.0f) *glm::rotate(270.0f, 0.0f, 1.0f, 0.0f)* glm::scale(0.002f, 0.002f, 0.002f);
	

}
bool Engine::intersectOBB(const engine::BoundingBox& obb1, const engine::BoundingBox& obb2)
{
    AABB box1( wrap( obb1.inf ), wrap( obb1.sup ) );
    Matrix world1 = wrap( obb1.matrix );
    AABB aabb1;
    aabb1.calculate( &box1, &world1 );

    AABB box2( wrap( obb2.inf ), wrap( obb2.sup ) );
    Matrix world2 = wrap( obb2.matrix );
    AABB aabb2;
    aabb2.calculate( &box2, &world2 );

    // first test : intersect aabbs
    if( !intersectionAABBAABB( &aabb1, &aabb2 ) ) return false;

    // calculate transformation matrices
    Matrix iworld1, iworld2;
    D3DXMatrixInverse( &iworld1, NULL, &world1 );
    D3DXMatrixInverse( &iworld2, NULL, &world2 );
    Matrix t12, t21;
    D3DXMatrixMultiply( &t12, &world1, &iworld2 );
    D3DXMatrixMultiply( &t21, &world2, &iworld1 );

    Vector vertex[8], temp;
    Line edge;

    // retrieve vertices of obb1 in object-space of obb2  
	unsigned int i=0;
    for( i=0; i<8; i++ ) 
    {
        AABBVERTEX( temp, box1, i );
        D3DXVec3TransformCoord( vertex+i, &temp, &t12 );
        // simply, test intersection of aabb & corresponding vertex
        if( box2.isInside( vertex[i] ) ) return true;
    }
    // pass edges of obb1    
    for( i=0; i<12; i++ )
    {
        edge.start = vertex[edgeStartId[i]];
        edge.end = vertex[edgeEndId[i]];
        // intersection test
        if( intersectionLineAABB( &edge, &box2 ) ) return true;
    }

    // retrieve vertices of obb2 in object-space of obb1
    for( i=0; i<8; i++ ) 
    {
        AABBVERTEX( temp, box2, i );
        D3DXVec3TransformCoord( vertex+i, &temp, &t21 );
        // simply, test intersection of aabb & corresponding vertex
        if( box1.isInside( vertex[i] ) ) return true;
    }
    // pass edges of obb1    
    for( i=0; i<12; i++ )
    {
        edge.start = vertex[edgeStartId[i]];
        edge.end = vertex[edgeEndId[i]];
        // intersection test
        if( intersectionLineAABB( &edge, &box1 ) ) return true;
    }

    return false;
}