<commit_before>/* This file is part of the Pangolin Project.
 * http://github.com/stevenlovegrove/Pangolin
 *
 * Copyright (c) 2014 Steven Lovegrove
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include <pangolin/video/drivers/join.h>

namespace pangolin
{
VideoJoiner::VideoJoiner(const std::vector<VideoInterface*>& src)
    : src(src), size_bytes(0), sync_attempts_to_go(-1), sync_continuously(false)
{
    // Add individual streams
    for(size_t s=0; s< src.size(); ++s)
    {
        VideoInterface& vid = *src[s];
        for(size_t i=0; i < vid.Streams().size(); ++i)
        {
            const StreamInfo si = vid.Streams()[i];
            const VideoPixelFormat fmt = si.PixFormat();
            const Image<unsigned char> img_offset = si.StreamImage((unsigned char*)size_bytes);
            streams.push_back(StreamInfo(fmt, img_offset));
        }
        size_bytes += src[s]->SizeBytes();
    }
}

VideoJoiner::~VideoJoiner()
{
    for(size_t s=0; s< src.size(); ++s) {
        src[s]->Stop();
        delete src[s];
    }
}

size_t VideoJoiner::SizeBytes() const
{
    return size_bytes;
}

const std::vector<StreamInfo>& VideoJoiner::Streams() const
{
    return streams;
}

void VideoJoiner::Start()
{
    for(size_t s=0; s< src.size(); ++s) {
        src[s]->Start();
    }
}

void VideoJoiner::Stop()
{
    for(size_t s=0; s< src.size(); ++s) {
        src[s]->Stop();
    }
}

bool VideoJoiner::Sync(int64_t tolerance_us, bool continuous)
{
    for(size_t s=0; s< src.size(); ++s)
    {
       VideoPropertiesInterface* vpi = dynamic_cast<VideoPropertiesInterface*>(src[s]);
       if(!vpi)
         return false;
    }
    sync_attempts_to_go = MAX_SYNC_ATTEMPTS;
    sync_tolerance_us = tolerance_us;
    sync_continuously = continuous;
    return true;
}

bool VideoJoiner::GrabNext( unsigned char* image, bool wait )
{
    size_t offset = 0;
    std::vector<size_t> offsets;
    std::vector<int64_t> reception_times;
    int64_t newest = std::numeric_limits<int64_t>::min();
    int64_t oldest = std::numeric_limits<int64_t>::max();
    bool grabbed_any = false;

    for(size_t s=0; s<src.size(); ++s) {
       VideoInterface& vid = *src[s];
       grabbed_any |= vid.GrabNext(image+offset,wait);
       offsets.push_back(offset);
       offset += vid.SizeBytes();
       if(sync_attempts_to_go >= 0) {
          VideoPropertiesInterface* vidpi = dynamic_cast<VideoPropertiesInterface*>(src[s]);
          if(vidpi->FrameProperties().contains(PANGO_HOST_RECEPTION_TIME_US)) {
             int64_t rt = vidpi->FrameProperties()[PANGO_HOST_RECEPTION_TIME_US].get<int64_t>();
             reception_times.push_back(rt);
             if(newest < rt) newest = rt;
             if(oldest > rt) oldest = rt;
          } else {
             sync_attempts_to_go = -1;
             pango_print_error("Stream %lu in join does not support startup_sync_us option.\n", s);
          }
       }
    }

    if((sync_continuously || (sync_attempts_to_go == 0)) && ((newest - oldest) > sync_tolerance_us) ){
       pango_print_warn("Join error, unable to sync streams within %lu us\n", (unsigned long)sync_tolerance_us);
    }

    if(sync_attempts_to_go >= 0) {
       for(size_t s=0; s<src.size(); ++s) {
          if(reception_times[s] < (newest - sync_tolerance_us)) {
             VideoInterface& vid = *src[s];
             vid.GrabNewest(image+offsets[s],false);
          }
       }
       if(!sync_continuously) --sync_attempts_to_go;
    }

    return grabbed_any;
}

bool AllInterfacesAreBufferAware(std::vector<VideoInterface*>& src){
  for(size_t s=0; s<src.size(); ++s) {
      if(!dynamic_cast<BufferAwareVideoInterface*>(src[s])) return false;
  }
  return true;
}

bool VideoJoiner::GrabNewest( unsigned char* image, bool wait )
{

  if(AllInterfacesAreBufferAware(src)) {
     uint32_t minN = 0;
     //Find smalles number of frames it is safe to drop.
     for(size_t s=0; s<src.size(); ++s) {
         auto bai = dynamic_cast<BufferAwareVideoInterface*>(src[s]);
         minN = std::min(bai->AvailableFrames(), minN);
     }
     //Safely drop minN-1 frames on each interface.
     for(size_t s=0; s<src.size(); ++s) {
         auto bai = dynamic_cast<BufferAwareVideoInterface*>(src[s]);
         if(!bai->DropNFrames(minN - 1)) {
             pango_print_error("Stream %lu did not drop %u frames altough available.\n", s, minN);
             return false;
         }
     }
     //GrabNext on each interface.
     return GrabNext(image, wait);
  } else {
      // Simply calling GrabNewest on the child streams might cause loss of sync,
      // instead we perform as many GrabNext as possible on the first stream and
      // then pull the same number of frames from every other stream.
      size_t offset = 0;
      std::vector<size_t> offsets;
      std::vector<int64_t> reception_times;
      int64_t newest = std::numeric_limits<int64_t>::min();
      int64_t oldest = std::numeric_limits<int64_t>::max();
      bool grabbed_any = false;
      int first_stream_backlog = 0;
      int64_t rt = 0;
      bool got_frame = false;

      do {
          got_frame = src[0]->GrabNext(image+offset,false);
          if(got_frame) {
              if(sync_attempts_to_go >= 0) {
                  VideoPropertiesInterface* vidpi = dynamic_cast<VideoPropertiesInterface*>(src[0]);
                  if(vidpi->FrameProperties().contains(PANGO_HOST_RECEPTION_TIME_US)) {
                      rt = vidpi->FrameProperties()[PANGO_HOST_RECEPTION_TIME_US].get<int64_t>();
                  } else {
                      sync_attempts_to_go = -1;
                      pango_print_error("Stream %u in join does not support startup_sync_us option.\n", 0);
                  }
              }
              first_stream_backlog++;
              grabbed_any = true;
          }
      } while(got_frame);
      offsets.push_back(offset);
      offset += src[0]->SizeBytes();
      if(sync_attempts_to_go >= 0) {
          reception_times.push_back(rt);
          if(newest < rt) newest = rt;
          if(oldest > rt) oldest = rt;
      }

      for(size_t s=1; s<src.size(); ++s) {
          for (int i=0; i<first_stream_backlog; i++){
              grabbed_any |= src[s]->GrabNext(image+offset,true);
              if(sync_attempts_to_go >= 0) {
                  VideoPropertiesInterface* vidpi = dynamic_cast<VideoPropertiesInterface*>(src[s]);
                  if(vidpi->FrameProperties().contains(PANGO_HOST_RECEPTION_TIME_US)) {
                      rt = vidpi->FrameProperties()[PANGO_HOST_RECEPTION_TIME_US].get<int64_t>();
                  } else {
                      sync_attempts_to_go = -1;
                      pango_print_error("Stream %lu in join does not support startup_sync_us option.\n", s);
                  }
              }
          }
          offsets.push_back(offset);
          offset += src[s]->SizeBytes();
          if(sync_attempts_to_go >= 0) {
              reception_times.push_back(rt);
              if(newest < rt) newest = rt;
              if(oldest > rt) oldest = rt;
          }
      }

      if((sync_continuously || (sync_attempts_to_go == 0)) && ((newest - oldest) > sync_tolerance_us) ){
          pango_print_warn("Join error, unable to sync streams within %lu us\n", (unsigned long)sync_tolerance_us);
      }

      if(sync_attempts_to_go >= 0) {
          for(size_t s=0; s<src.size(); ++s) {
              if(reception_times[s] < (newest - sync_tolerance_us)) {
                  VideoInterface& vid = *src[s];
                  vid.GrabNewest(image+offsets[s],false);
              }
          }
          if(!sync_continuously) --sync_attempts_to_go;
      }
      return grabbed_any;
  }

}

std::vector<VideoInterface*>& VideoJoiner::InputStreams()
{
    return src;
}

}
<commit_msg>Fix bug in minN init. Drop frames only if minN > 1.<commit_after>/* This file is part of the Pangolin Project.
 * http://github.com/stevenlovegrove/Pangolin
 *
 * Copyright (c) 2014 Steven Lovegrove
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include <pangolin/video/drivers/join.h>

namespace pangolin
{
VideoJoiner::VideoJoiner(const std::vector<VideoInterface*>& src)
    : src(src), size_bytes(0), sync_attempts_to_go(-1), sync_continuously(false)
{
    // Add individual streams
    for(size_t s=0; s< src.size(); ++s)
    {
        VideoInterface& vid = *src[s];
        for(size_t i=0; i < vid.Streams().size(); ++i)
        {
            const StreamInfo si = vid.Streams()[i];
            const VideoPixelFormat fmt = si.PixFormat();
            const Image<unsigned char> img_offset = si.StreamImage((unsigned char*)size_bytes);
            streams.push_back(StreamInfo(fmt, img_offset));
        }
        size_bytes += src[s]->SizeBytes();
    }
}

VideoJoiner::~VideoJoiner()
{
    for(size_t s=0; s< src.size(); ++s) {
        src[s]->Stop();
        delete src[s];
    }
}

size_t VideoJoiner::SizeBytes() const
{
    return size_bytes;
}

const std::vector<StreamInfo>& VideoJoiner::Streams() const
{
    return streams;
}

void VideoJoiner::Start()
{
    for(size_t s=0; s< src.size(); ++s) {
        src[s]->Start();
    }
}

void VideoJoiner::Stop()
{
    for(size_t s=0; s< src.size(); ++s) {
        src[s]->Stop();
    }
}

bool VideoJoiner::Sync(int64_t tolerance_us, bool continuous)
{
    for(size_t s=0; s< src.size(); ++s)
    {
       VideoPropertiesInterface* vpi = dynamic_cast<VideoPropertiesInterface*>(src[s]);
       if(!vpi)
         return false;
    }
    sync_attempts_to_go = MAX_SYNC_ATTEMPTS;
    sync_tolerance_us = tolerance_us;
    sync_continuously = continuous;
    return true;
}

bool VideoJoiner::GrabNext( unsigned char* image, bool wait )
{
    size_t offset = 0;
    std::vector<size_t> offsets;
    std::vector<int64_t> reception_times;
    int64_t newest = std::numeric_limits<int64_t>::min();
    int64_t oldest = std::numeric_limits<int64_t>::max();
    bool grabbed_any = false;

    for(size_t s=0; s<src.size(); ++s) {
       VideoInterface& vid = *src[s];
       grabbed_any |= vid.GrabNext(image+offset,wait);
       offsets.push_back(offset);
       offset += vid.SizeBytes();
       if(sync_attempts_to_go >= 0) {
          VideoPropertiesInterface* vidpi = dynamic_cast<VideoPropertiesInterface*>(src[s]);
          if(vidpi->FrameProperties().contains(PANGO_HOST_RECEPTION_TIME_US)) {
             int64_t rt = vidpi->FrameProperties()[PANGO_HOST_RECEPTION_TIME_US].get<int64_t>();
             reception_times.push_back(rt);
             if(newest < rt) newest = rt;
             if(oldest > rt) oldest = rt;
          } else {
             sync_attempts_to_go = -1;
             pango_print_error("Stream %lu in join does not support startup_sync_us option.\n", s);
          }
       }
    }

    if((sync_continuously || (sync_attempts_to_go == 0)) && ((newest - oldest) > sync_tolerance_us) ){
       pango_print_warn("Join error, unable to sync streams within %lu us\n", (unsigned long)sync_tolerance_us);
    }

    if(sync_attempts_to_go >= 0) {
       for(size_t s=0; s<src.size(); ++s) {
          if(reception_times[s] < (newest - sync_tolerance_us)) {
             VideoInterface& vid = *src[s];
             vid.GrabNewest(image+offsets[s],false);
          }
       }
       if(!sync_continuously) --sync_attempts_to_go;
    }

    return grabbed_any;
}

bool AllInterfacesAreBufferAware(std::vector<VideoInterface*>& src){
  for(size_t s=0; s<src.size(); ++s) {
      if(!dynamic_cast<BufferAwareVideoInterface*>(src[s])) return false;
  }
  return true;
}

bool VideoJoiner::GrabNewest( unsigned char* image, bool wait )
{

  if(AllInterfacesAreBufferAware(src)) {
     uint32_t minN = std::numeric_limits<uint32_t>::max();
     //Find smalles number of frames it is safe to drop.
     for(size_t s=0; s<src.size(); ++s) {
         auto bai = dynamic_cast<BufferAwareVideoInterface*>(src[s]);
         minN = std::min(bai->AvailableFrames(), minN);
     }
     //Safely drop minN-1 frames on each interface.
     if(minN > 1) {
         for(size_t s=0; s<src.size(); ++s) {
             auto bai = dynamic_cast<BufferAwareVideoInterface*>(src[s]);
             if(!bai->DropNFrames(minN - 1)) {
                 pango_print_error("Stream %lu did not drop %u frames altough available.\n", s, minN);
                 return false;
             }
         }
     }
     //GrabNext on each interface.
     return GrabNext(image, wait);
  } else {
      // Simply calling GrabNewest on the child streams might cause loss of sync,
      // instead we perform as many GrabNext as possible on the first stream and
      // then pull the same number of frames from every other stream.
      size_t offset = 0;
      std::vector<size_t> offsets;
      std::vector<int64_t> reception_times;
      int64_t newest = std::numeric_limits<int64_t>::min();
      int64_t oldest = std::numeric_limits<int64_t>::max();
      bool grabbed_any = false;
      int first_stream_backlog = 0;
      int64_t rt = 0;
      bool got_frame = false;

      do {
          got_frame = src[0]->GrabNext(image+offset,false);
          if(got_frame) {
              if(sync_attempts_to_go >= 0) {
                  VideoPropertiesInterface* vidpi = dynamic_cast<VideoPropertiesInterface*>(src[0]);
                  if(vidpi->FrameProperties().contains(PANGO_HOST_RECEPTION_TIME_US)) {
                      rt = vidpi->FrameProperties()[PANGO_HOST_RECEPTION_TIME_US].get<int64_t>();
                  } else {
                      sync_attempts_to_go = -1;
                      pango_print_error("Stream %u in join does not support startup_sync_us option.\n", 0);
                  }
              }
              first_stream_backlog++;
              grabbed_any = true;
          }
      } while(got_frame);
      offsets.push_back(offset);
      offset += src[0]->SizeBytes();
      if(sync_attempts_to_go >= 0) {
          reception_times.push_back(rt);
          if(newest < rt) newest = rt;
          if(oldest > rt) oldest = rt;
      }

      for(size_t s=1; s<src.size(); ++s) {
          for (int i=0; i<first_stream_backlog; i++){
              grabbed_any |= src[s]->GrabNext(image+offset,true);
              if(sync_attempts_to_go >= 0) {
                  VideoPropertiesInterface* vidpi = dynamic_cast<VideoPropertiesInterface*>(src[s]);
                  if(vidpi->FrameProperties().contains(PANGO_HOST_RECEPTION_TIME_US)) {
                      rt = vidpi->FrameProperties()[PANGO_HOST_RECEPTION_TIME_US].get<int64_t>();
                  } else {
                      sync_attempts_to_go = -1;
                      pango_print_error("Stream %lu in join does not support startup_sync_us option.\n", s);
                  }
              }
          }
          offsets.push_back(offset);
          offset += src[s]->SizeBytes();
          if(sync_attempts_to_go >= 0) {
              reception_times.push_back(rt);
              if(newest < rt) newest = rt;
              if(oldest > rt) oldest = rt;
          }
      }

      if((sync_continuously || (sync_attempts_to_go == 0)) && ((newest - oldest) > sync_tolerance_us) ){
          pango_print_warn("Join error, unable to sync streams within %lu us\n", (unsigned long)sync_tolerance_us);
      }

      if(sync_attempts_to_go >= 0) {
          for(size_t s=0; s<src.size(); ++s) {
              if(reception_times[s] < (newest - sync_tolerance_us)) {
                  VideoInterface& vid = *src[s];
                  vid.GrabNewest(image+offsets[s],false);
              }
          }
          if(!sync_continuously) --sync_attempts_to_go;
      }
      return grabbed_any;
  }

}

std::vector<VideoInterface*>& VideoJoiner::InputStreams()
{
    return src;
}

}
<|endoftext|>


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

#include "../../../external/catch.hpp"
// #include "../../../../kernels/common/scene_line_segments.h"

using namespace embree;

TEST_CASE ("Segment Left/Right exists tests - Issue 726", "[scene_line_segments]")
{
  // embree::Device device ("");
  // LineSegments lines (&device, Geometry::GTY_ROUND_LINEAR_CURVE);
}
<commit_msg>remove test for now need to get proper static libs into test<commit_after>// ======================================================================== //
// Copyright 2009-2020 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

// #include "../../../external/catch.hpp"
// #include "../../../../kernels/common/scene_line_segments.h"

// using namespace embree;

// TEST_CASE ("Segment Left/Right exists tests - Issue 726", "[scene_line_segments]")
// {
//   // embree::Device device ("");
//   // LineSegments lines (&device, Geometry::GTY_ROUND_LINEAR_CURVE);
// }
<|endoftext|>


<commit_before>// $Id$

/*
Copyright (c) 2007-2010, Trustees of The Leland Stanford Junior University
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of the Stanford University nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*buffer_state.cpp
 *
 * This class is the buffere state of the next router down the channel
 * tracks the credit and how much of the buffer is in use
 */

#include <iostream>
#include <sstream>
#include <cstdlib>
#include <cassert>

#include "booksim.hpp"
#include "buffer_state.hpp"
#include "random_utils.hpp"

BufferState::BufferState( const Configuration& config,
			  Module *parent, const string& name ) :
Module( parent, name ), _shared_occupied(0), _active_vcs(0)
{
  _vc_buf_size     = config.GetInt( "vc_buf_size" );
  _shared_buf_size = config.GetInt( "shared_buf_size" );
  _dynamic_sharing = config.GetInt( "dynamic_sharing" );
  _vcs             = config.GetInt( "num_vcs" );

  _wait_for_tail_credit = config.GetInt( "wait_for_tail_credit" );
  _vc_busy_when_full = config.GetInt( "vc_busy_when_full" );

  _in_use.resize(_vcs, false);
  _tail_sent.resize(_vcs, false);
  _cur_occupied.resize(_vcs, 0);
  _last_id.resize(_vcs, -1);
  _last_pid.resize(_vcs, -1);
}

void BufferState::ProcessCredit( Credit const * c )
{
  assert( c );

  set<int>::iterator iter = c->vc.begin();
  while(iter != c->vc.end()) {

    assert( ( *iter >= 0 ) && ( *iter < _vcs ) );

    if ( ( _wait_for_tail_credit ) &&
	 ( !_in_use[*iter] ) ) {
      Error( "Received credit for idle buffer" );
    }

    if ( _cur_occupied[*iter] > 0 ) {
      if(_cur_occupied[*iter] > _vc_buf_size) {
	--_shared_occupied;
      }
      --_cur_occupied[*iter];

      if ( _wait_for_tail_credit &&
	   ( _cur_occupied[*iter] == 0 ) &&
	   ( _tail_sent[*iter] ) ) {
	assert(_in_use[*iter]);
	_in_use[*iter] = false;
	assert(_active_vcs > 0);
	--_active_vcs;
      }
    } else {
      cout << "VC = " << *iter << endl;
      Error( "Buffer occupancy fell below zero" );
    }
    ++iter;
  }
}

void BufferState::SendingFlit( Flit const * f )
{
  assert( f && ( f->vc >= 0 ) && ( f->vc < _vcs ) );

  if ( ( _shared_occupied >= _shared_buf_size ) &&
       ( _cur_occupied[f->vc] >= _vc_buf_size ) ) {
    ostringstream err;
    err << "Flit " << f->id << " sent to full buffer.";
    Error( err.str( ) );
  } else {
    if ( _cur_occupied[f->vc] >= _vc_buf_size ) {
      ++_shared_occupied;
    }
    ++_cur_occupied[f->vc];

    if ( f->tail ) {
      _tail_sent[f->vc] = true;

      if ( !_wait_for_tail_credit ) {
	assert(_in_use[f->vc]);
	_in_use[f->vc] = false;
	assert(_active_vcs > 0);
	--_active_vcs;
      }
    }
    _last_id[f->vc] = f->id;
    _last_pid[f->vc] = f->pid;
  }
}

void BufferState::TakeBuffer( int vc )
{
  assert( ( vc >= 0 ) && ( vc < _vcs ) );

  if ( _in_use[vc] ) {
    cout << "TakeBuffer( " << vc << " )" << endl;
    Display( );
    Error( "Buffer taken while in use" );
  }
  _in_use[vc]    = true;
  _tail_sent[vc] = false;
  assert(_active_vcs < _vcs);
  ++_active_vcs;
}

bool BufferState::IsFullFor( int vc ) const
{
  assert( ( vc >= 0 ) && ( vc < _vcs ) );
  return ( ( _cur_occupied[vc] >= _vc_buf_size ) &&
	   ( _shared_occupied >= _shared_buf_size ) );
}

bool BufferState::IsEmptyFor( int vc  ) const
{
  assert( ( vc >= 0 ) && ( vc < _vcs ) );
  return ( _cur_occupied[vc] == 0 );
}

bool BufferState::IsAvailableFor( int vc ) const
{

  assert( ( vc >= 0 ) && ( vc < _vcs ) );
  return !_in_use[vc] && (!_vc_busy_when_full || !IsFullFor(vc));
}

bool BufferState::HasCreditFor( int vc ) const
{
  assert( ( vc >= 0 ) && ( vc < _vcs ) );
  return ( ( _cur_occupied[vc] >= _vc_buf_size ) &&
	   ( ( _shared_occupied >= _shared_buf_size ) ||
	     ( _dynamic_sharing && ( _active_vcs > 0 ) &&
	       ( ( _cur_occupied[vc] - _vc_buf_size ) >=
		 ( _shared_buf_size / _active_vcs ) ) ) ) );
}

int BufferState::Size(int vc) const{
  assert( ( vc >= 0 ) && ( vc < _vcs ) );

  return  _cur_occupied[vc];
}

void BufferState::Display( ) const
{
  cout << FullName() << " :" << endl;
  cout << " shared_occupied = " << _shared_occupied << endl;
  for ( int v = 0; v < _vcs; ++v ) {
    cout << "  buffer class " << v << endl;
    cout << "    in_use = " << _in_use[v]
	 << " tail_sent = " << _tail_sent[v] << endl;
    cout << "    occupied = " << _cur_occupied[v] << endl;
  }
}
<commit_msg>fix polarity of BufferState::HasCreditFor() method<commit_after>// $Id$

/*
Copyright (c) 2007-2010, Trustees of The Leland Stanford Junior University
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of the Stanford University nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*buffer_state.cpp
 *
 * This class is the buffere state of the next router down the channel
 * tracks the credit and how much of the buffer is in use
 */

#include <iostream>
#include <sstream>
#include <cstdlib>
#include <cassert>

#include "booksim.hpp"
#include "buffer_state.hpp"
#include "random_utils.hpp"

BufferState::BufferState( const Configuration& config,
			  Module *parent, const string& name ) :
Module( parent, name ), _shared_occupied(0), _active_vcs(0)
{
  _vc_buf_size     = config.GetInt( "vc_buf_size" );
  _shared_buf_size = config.GetInt( "shared_buf_size" );
  _dynamic_sharing = config.GetInt( "dynamic_sharing" );
  _vcs             = config.GetInt( "num_vcs" );

  _wait_for_tail_credit = config.GetInt( "wait_for_tail_credit" );
  _vc_busy_when_full = config.GetInt( "vc_busy_when_full" );

  _in_use.resize(_vcs, false);
  _tail_sent.resize(_vcs, false);
  _cur_occupied.resize(_vcs, 0);
  _last_id.resize(_vcs, -1);
  _last_pid.resize(_vcs, -1);
}

void BufferState::ProcessCredit( Credit const * c )
{
  assert( c );

  set<int>::iterator iter = c->vc.begin();
  while(iter != c->vc.end()) {

    assert( ( *iter >= 0 ) && ( *iter < _vcs ) );

    if ( ( _wait_for_tail_credit ) &&
	 ( !_in_use[*iter] ) ) {
      Error( "Received credit for idle buffer" );
    }

    if ( _cur_occupied[*iter] > 0 ) {
      if(_cur_occupied[*iter] > _vc_buf_size) {
	--_shared_occupied;
      }
      --_cur_occupied[*iter];

      if ( _wait_for_tail_credit &&
	   ( _cur_occupied[*iter] == 0 ) &&
	   ( _tail_sent[*iter] ) ) {
	assert(_in_use[*iter]);
	_in_use[*iter] = false;
	assert(_active_vcs > 0);
	--_active_vcs;
      }
    } else {
      cout << "VC = " << *iter << endl;
      Error( "Buffer occupancy fell below zero" );
    }
    ++iter;
  }
}

void BufferState::SendingFlit( Flit const * f )
{
  assert( f && ( f->vc >= 0 ) && ( f->vc < _vcs ) );

  if ( ( _shared_occupied >= _shared_buf_size ) &&
       ( _cur_occupied[f->vc] >= _vc_buf_size ) ) {
    ostringstream err;
    err << "Flit " << f->id << " sent to full buffer.";
    Error( err.str( ) );
  } else {
    if ( _cur_occupied[f->vc] >= _vc_buf_size ) {
      ++_shared_occupied;
    }
    ++_cur_occupied[f->vc];

    if ( f->tail ) {
      _tail_sent[f->vc] = true;

      if ( !_wait_for_tail_credit ) {
	assert(_in_use[f->vc]);
	_in_use[f->vc] = false;
	assert(_active_vcs > 0);
	--_active_vcs;
      }
    }
    _last_id[f->vc] = f->id;
    _last_pid[f->vc] = f->pid;
  }
}

void BufferState::TakeBuffer( int vc )
{
  assert( ( vc >= 0 ) && ( vc < _vcs ) );

  if ( _in_use[vc] ) {
    cout << "TakeBuffer( " << vc << " )" << endl;
    Display( );
    Error( "Buffer taken while in use" );
  }
  _in_use[vc]    = true;
  _tail_sent[vc] = false;
  assert(_active_vcs < _vcs);
  ++_active_vcs;
}

bool BufferState::IsFullFor( int vc ) const
{
  assert( ( vc >= 0 ) && ( vc < _vcs ) );
  return ( ( _cur_occupied[vc] >= _vc_buf_size ) &&
	   ( _shared_occupied >= _shared_buf_size ) );
}

bool BufferState::IsEmptyFor( int vc  ) const
{
  assert( ( vc >= 0 ) && ( vc < _vcs ) );
  return ( _cur_occupied[vc] == 0 );
}

bool BufferState::IsAvailableFor( int vc ) const
{

  assert( ( vc >= 0 ) && ( vc < _vcs ) );
  return !_in_use[vc] && (!_vc_busy_when_full || !IsFullFor(vc));
}

bool BufferState::HasCreditFor( int vc ) const
{
  assert( ( vc >= 0 ) && ( vc < _vcs ) );
  return ( ( _cur_occupied[vc] < _vc_buf_size ) ||
	   ( ( _shared_occupied < _shared_buf_size ) &&
	     ( _dynamic_sharing && ( _active_vcs > 0 ) &&
	       ( ( _cur_occupied[vc] - _vc_buf_size ) <
		 ( _shared_buf_size / _active_vcs ) ) ) ) );
}

int BufferState::Size(int vc) const{
  assert( ( vc >= 0 ) && ( vc < _vcs ) );

  return  _cur_occupied[vc];
}

void BufferState::Display( ) const
{
  cout << FullName() << " :" << endl;
  cout << " shared_occupied = " << _shared_occupied << endl;
  for ( int v = 0; v < _vcs; ++v ) {
    cout << "  buffer class " << v << endl;
    cout << "    in_use = " << _in_use[v]
	 << " tail_sent = " << _tail_sent[v] << endl;
    cout << "    occupied = " << _cur_occupied[v] << endl;
  }
}
<|endoftext|>


<commit_before>#include "optionparser/optionparser.h"

#include "pixelboost/audio/audioManagerSimple.h"
#include "pixelboost/debug/assert.h"
#include "pixelboost/debug/debugDatabaseHandler.h"
#include "pixelboost/debug/debugVariableManager.h"
#include "pixelboost/debug/log.h"
#include "pixelboost/file/fileSystem.h"
#include "pixelboost/framework/engine.h"
#include "pixelboost/framework/screen.h"
#include "pixelboost/graphics/device/device.h"
#include "pixelboost/graphics/renderer/common/renderer.h"
#include "pixelboost/graphics/renderer/buffer/bufferRenderer.h"
#include "pixelboost/graphics/renderer/gui/guiRenderer.h"
#include "pixelboost/graphics/renderer/model/modelRenderer.h"
#include "pixelboost/graphics/renderer/particle/particleRenderer.h"
#include "pixelboost/graphics/renderer/primitive/primitiveRenderer.h"
#include "pixelboost/graphics/renderer/sprite/spriteRenderer.h"
#include "pixelboost/graphics/renderer/text/textRenderer.h"
#include "pixelboost/input/joystickManager.h"
#include "pixelboost/input/keyboardManager.h"
#include "pixelboost/input/mouseManager.h"
#include "pixelboost/input/touchManager.h"
#include "pixelboost/network/gameCenter.h"
#include "pixelboost/network/networkServer.h"
#include "pixelboost/resource/resourceManager.h"
#include "pixelboost/scripting/lua.h"

#include "pixelboost/debug/log.h"

using namespace pb;

Engine* Engine::_Instance = 0;

Engine::Engine(void* platformContext, int argc, const char** argv, bool enableNetworkDebug)
    : _GameTime(0)
    , _PlatformContext(platformContext)
    , _TotalTime(0)
    , _DebugNetwork(0)
    , _ArgC(argc)
    , _ArgV(argv)
{
    PbAssert(!_Instance);

    _NetworkDebugEnabled = enableNetworkDebug;
    _Instance = this;
}

Engine::~Engine()
{
    _Instance = 0;

    delete NetworkManager::Instance();

#ifndef PIXELBOOST_DISABLE_GAMECENTER
    delete _GameCenter;
#endif

    delete GuiRenderer::Instance();
    delete BufferRenderer::Instance();
    delete TextRenderer::Instance();
    delete ModelRenderer::Instance();
    delete ParticleRenderer::Instance();
    delete PrimitiveRenderer::Instance();
	delete SpriteRenderer::Instance();
    delete Renderer::Instance();

    delete _JoystickManager;
    delete _KeyboardManager;
    delete _MouseManager;
    delete _TouchManager;

    delete _FileSystem;
}

void Engine::RegisterLuaClass(lua_State* state)
{
    luabridge::getGlobalNamespace(state)
    .beginNamespace("pb")
        .beginClass<Engine>("Engine")
        .endClass()
    .endNamespace();
}

Engine* Engine::Instance()
{
    return _Instance;
}

void Engine::Initialise()
{
    LogSystem::Instance()->AddSubscriber(new LogSubscriberConsole());

    _FileSystem = new FileSystem(_ArgC > 0 ? _ArgV[0] : "");

    LogSystem::Instance()->AddSubscriber(new LogSubscriberFile("/pb.log"));

    if (_ArgC)
    {
        enum  optionIndex { kOptionUnknown, kOptionProject, kOptionCount };

        const option::Descriptor usage[] =
        {
            {kOptionUnknown,      0, "", "",         option::Arg::None,     ""},
            {kOptionProject,      0, "", "project",  option::Arg::Required, "  --project [location]" },
            {0,0,0,0,0,0}
        };
        option::Option options[kOptionCount], buffer[kOptionCount];
        option::Parser parse(usage, _ArgC-1, &_ArgV[1], options, buffer);

        if (options[kOptionProject])
        {
            _FileSystem->MountReadLocation(std::string(options[kOptionProject].arg) + "data/", "/", true);
        }
    }

    ResourceManager::Instance()->CreatePool("default");

    new Renderer();
    new BufferRenderer();
    new ModelRenderer();
    new ParticleRenderer();
    new SpriteRenderer();
    new PrimitiveRenderer();
    new TextRenderer();
    new GuiRenderer();

#ifndef PIXELBOOST_DISABLE_GAMECENTER
    _GameCenter = new GameCenter();
    _GameCenter->Connect();
#endif

    _JoystickManager = new JoystickManager();
    _KeyboardManager = new KeyboardManager();
    _MouseManager = new MouseManager();
    _TouchManager = new TouchManager();

#if !defined(PIXELBOOST_DISABLE_NETWORKING)
    new NetworkManager();
#endif

#if !defined(PIXELBOOST_DISABLE_NETWORKING) && !defined(PIXELBOOST_DISABLE_DEBUG)
    if (_NetworkDebugEnabled)
    {
        _DebugDiscovery = NetworkManager::Instance()->StartDiscoveryServer(9091);
        _DebugDiscovery->AddService("pb::debugvariable");
        _DebugNetwork = NetworkManager::Instance()->StartServer(9090, 8);
        _DebugDatabaseHandler = new DebugDatabaseHandler();
        _DebugNetwork->RegisterHandler(_DebugDatabaseHandler);
        _DebugNetwork->RegisterHandler(DebugVariableManager::Instance());
    }
#endif
}

GameCenter* Engine::GetGameCenter() const
{
    return _GameCenter;
}

NetworkServer* Engine::GetDebugNetworkServer() const
{
    return _DebugNetwork;
}

JoystickManager* Engine::GetJoystickManager() const
{
    return _JoystickManager;
}

KeyboardManager* Engine::GetKeyboardManager() const
{
    return _KeyboardManager;
}

MouseManager* Engine::GetMouseManager() const
{
    return _MouseManager;
}

TouchManager* Engine::GetTouchManager() const
{
    return _TouchManager;
}

float Engine::GetGameTime()
{
    return _GameTime;
}

float Engine::GetTotalTime()
{
    return _TotalTime;
}

bool Engine::IsLandscape()
{
    return true;
}

bool Engine::AllowFrameskip()
{
    return true;
}

void Engine::OnMemoryWarning()
{

}

void Engine::OnAppLoseFocus()
{

}

void Engine::OnAppGainFocus()
{

}

void Engine::OnAppQuit()
{

}

void Engine::Update(float timeDelta, float gameDelta)
{
    _GameTime += gameDelta;
    _TotalTime += timeDelta;

#ifndef PIXELBOOST_DISABLE_SOUND
    AudioManagerSimple::Instance()->Update(timeDelta);
#endif

    ResourceManager::Instance()->Update(timeDelta);

    if (NetworkManager::Instance())
    {
        NetworkManager::Instance()->Update();
    }
}

void Engine::Render()
{
    Renderer::Instance()->Render();
}

void* Engine::GetPlatformContext()
{
    return _PlatformContext;
}
<commit_msg>Don't create network manager if networking is disabled<commit_after>#include "optionparser/optionparser.h"

#include "pixelboost/audio/audioManagerSimple.h"
#include "pixelboost/debug/assert.h"
#include "pixelboost/debug/debugDatabaseHandler.h"
#include "pixelboost/debug/debugVariableManager.h"
#include "pixelboost/debug/log.h"
#include "pixelboost/file/fileSystem.h"
#include "pixelboost/framework/engine.h"
#include "pixelboost/framework/screen.h"
#include "pixelboost/graphics/device/device.h"
#include "pixelboost/graphics/renderer/common/renderer.h"
#include "pixelboost/graphics/renderer/buffer/bufferRenderer.h"
#include "pixelboost/graphics/renderer/gui/guiRenderer.h"
#include "pixelboost/graphics/renderer/model/modelRenderer.h"
#include "pixelboost/graphics/renderer/particle/particleRenderer.h"
#include "pixelboost/graphics/renderer/primitive/primitiveRenderer.h"
#include "pixelboost/graphics/renderer/sprite/spriteRenderer.h"
#include "pixelboost/graphics/renderer/text/textRenderer.h"
#include "pixelboost/input/joystickManager.h"
#include "pixelboost/input/keyboardManager.h"
#include "pixelboost/input/mouseManager.h"
#include "pixelboost/input/touchManager.h"
#include "pixelboost/network/gameCenter.h"
#include "pixelboost/network/networkServer.h"
#include "pixelboost/resource/resourceManager.h"
#include "pixelboost/scripting/lua.h"

#include "pixelboost/debug/log.h"

using namespace pb;

Engine* Engine::_Instance = 0;

Engine::Engine(void* platformContext, int argc, const char** argv, bool enableNetworkDebug)
    : _GameTime(0)
    , _PlatformContext(platformContext)
    , _TotalTime(0)
    , _DebugNetwork(0)
    , _ArgC(argc)
    , _ArgV(argv)
{
    PbAssert(!_Instance);

    _NetworkDebugEnabled = enableNetworkDebug;
    _Instance = this;
}

Engine::~Engine()
{
    _Instance = 0;

#if !defined(PIXELBOOST_DISABLE_NETWORKING)
    delete NetworkManager::Instance();
#endif

#ifndef PIXELBOOST_DISABLE_GAMECENTER
    delete _GameCenter;
#endif

    delete GuiRenderer::Instance();
    delete BufferRenderer::Instance();
    delete TextRenderer::Instance();
    delete ModelRenderer::Instance();
    delete ParticleRenderer::Instance();
    delete PrimitiveRenderer::Instance();
	delete SpriteRenderer::Instance();
    delete Renderer::Instance();

    delete _JoystickManager;
    delete _KeyboardManager;
    delete _MouseManager;
    delete _TouchManager;

    delete _FileSystem;
}

void Engine::RegisterLuaClass(lua_State* state)
{
    luabridge::getGlobalNamespace(state)
    .beginNamespace("pb")
        .beginClass<Engine>("Engine")
        .endClass()
    .endNamespace();
}

Engine* Engine::Instance()
{
    return _Instance;
}

void Engine::Initialise()
{
    LogSystem::Instance()->AddSubscriber(new LogSubscriberConsole());

    _FileSystem = new FileSystem(_ArgC > 0 ? _ArgV[0] : "");

    LogSystem::Instance()->AddSubscriber(new LogSubscriberFile("/pb.log"));

    if (_ArgC)
    {
        enum  optionIndex { kOptionUnknown, kOptionProject, kOptionCount };

        const option::Descriptor usage[] =
        {
            {kOptionUnknown,      0, "", "",         option::Arg::None,     ""},
            {kOptionProject,      0, "", "project",  option::Arg::Required, "  --project [location]" },
            {0,0,0,0,0,0}
        };
        option::Option options[kOptionCount], buffer[kOptionCount];
        option::Parser parse(usage, _ArgC-1, &_ArgV[1], options, buffer);

        if (options[kOptionProject])
        {
            _FileSystem->MountReadLocation(std::string(options[kOptionProject].arg) + "data/", "/", true);
        }
    }

    ResourceManager::Instance()->CreatePool("default");

    new Renderer();
    new BufferRenderer();
    new ModelRenderer();
    new ParticleRenderer();
    new SpriteRenderer();
    new PrimitiveRenderer();
    new TextRenderer();
    new GuiRenderer();

#ifndef PIXELBOOST_DISABLE_GAMECENTER
    _GameCenter = new GameCenter();
    _GameCenter->Connect();
#endif

    _JoystickManager = new JoystickManager();
    _KeyboardManager = new KeyboardManager();
    _MouseManager = new MouseManager();
    _TouchManager = new TouchManager();

#if !defined(PIXELBOOST_DISABLE_NETWORKING)
    new NetworkManager();
#endif

#if !defined(PIXELBOOST_DISABLE_NETWORKING) && !defined(PIXELBOOST_DISABLE_DEBUG)
    if (_NetworkDebugEnabled)
    {
        _DebugDiscovery = NetworkManager::Instance()->StartDiscoveryServer(9091);
        _DebugDiscovery->AddService("pb::debugvariable");
        _DebugNetwork = NetworkManager::Instance()->StartServer(9090, 8);
        _DebugDatabaseHandler = new DebugDatabaseHandler();
        _DebugNetwork->RegisterHandler(_DebugDatabaseHandler);
        _DebugNetwork->RegisterHandler(DebugVariableManager::Instance());
    }
#endif
}

GameCenter* Engine::GetGameCenter() const
{
    return _GameCenter;
}

NetworkServer* Engine::GetDebugNetworkServer() const
{
    return _DebugNetwork;
}

JoystickManager* Engine::GetJoystickManager() const
{
    return _JoystickManager;
}

KeyboardManager* Engine::GetKeyboardManager() const
{
    return _KeyboardManager;
}

MouseManager* Engine::GetMouseManager() const
{
    return _MouseManager;
}

TouchManager* Engine::GetTouchManager() const
{
    return _TouchManager;
}

float Engine::GetGameTime()
{
    return _GameTime;
}

float Engine::GetTotalTime()
{
    return _TotalTime;
}

bool Engine::IsLandscape()
{
    return true;
}

bool Engine::AllowFrameskip()
{
    return true;
}

void Engine::OnMemoryWarning()
{

}

void Engine::OnAppLoseFocus()
{

}

void Engine::OnAppGainFocus()
{

}

void Engine::OnAppQuit()
{

}

void Engine::Update(float timeDelta, float gameDelta)
{
    _GameTime += gameDelta;
    _TotalTime += timeDelta;

#ifndef PIXELBOOST_DISABLE_SOUND
    AudioManagerSimple::Instance()->Update(timeDelta);
#endif

    ResourceManager::Instance()->Update(timeDelta);

#if !defined(PIXELBOOST_DISABLE_NETWORKING)
    if (NetworkManager::Instance())
    {
        NetworkManager::Instance()->Update();
    }
#endif
}

void Engine::Render()
{
    Renderer::Instance()->Render();
}

void* Engine::GetPlatformContext()
{
    return _PlatformContext;
}
<|endoftext|>


<commit_before>//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

#include "common.h"

extern "C"
{
    void RedirectForThrowControl()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void ErectWriteBarrier_ASM(Object** dst, Object* ref)
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void ExternalMethodFixupPatchLabel()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void ExternalMethodFixupStub()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void GenericPInvokeCalliHelper()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void NakedThrowHelper()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void PInvokeStubForHost()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void PInvokeStubForHostInner(DWORD dwStackSize, LPVOID pStackFrame, LPVOID pTarget)
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void VarargPInvokeStub()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void VarargPInvokeStub_RetBuffArg()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void VirtualMethodFixupPatchLabel()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void VirtualMethodFixupStub()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    DWORD getcpuid(DWORD arg, unsigned char result[16])
    {
        DWORD eax;
        __asm("  xor %%ecx, %%ecx\n" \
              "  cpuid\n" \
              "  mov %%eax, 0(%[result])\n" \
              "  mov %%ebx, 4(%[result])\n" \
              "  mov %%ecx, 8(%[result])\n" \
              "  mov %%edx, 12(%[result])\n" \
            : "=a"(eax) /*output in eax*/\
            : "a"(arg), [result]"r"(result) /*inputs - arg in eax, result in any register*/\
            : "eax", "rbx", "ecx", "edx" /* registers that are clobbered*/
          );
        return eax;
    }

    DWORD getextcpuid(DWORD arg1, DWORD arg2, unsigned char result[16])
    {
        DWORD eax;
        __asm("  cpuid\n" \
              "  mov %%eax, 0(%[result])\n" \
              "  mov %%ebx, 4(%[result])\n" \
              "  mov %%ecx, 8(%[result])\n" \
              "  mov %%edx, 12(%[result])\n" \
            : "=a"(eax) /*output in eax*/\
            : "c"(arg1), "a"(arg2), [result]"r"(result) /*inputs - arg1 in ecx, arg2 in eax, result in any register*/\
            : "eax", "rbx", "ecx", "edx" /* registers that are clobbered*/
          );
        return eax;
    }

    void STDCALL JIT_ProfilerEnterLeaveTailcallStub(UINT_PTR ProfilerHandle)
    {
    }

#ifdef FEATURE_PREJIT
    void StubDispatchFixupStub()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }
#endif

    void StubDispatchFixupPatchLabel()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }
};
<commit_msg>Delete dead code<commit_after>//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

#include "common.h"

extern "C"
{
    void RedirectForThrowControl()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void ExternalMethodFixupPatchLabel()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void ExternalMethodFixupStub()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void GenericPInvokeCalliHelper()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void NakedThrowHelper()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void PInvokeStubForHost()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void PInvokeStubForHostInner(DWORD dwStackSize, LPVOID pStackFrame, LPVOID pTarget)
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void VarargPInvokeStub()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void VarargPInvokeStub_RetBuffArg()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void VirtualMethodFixupPatchLabel()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    void VirtualMethodFixupStub()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }

    DWORD getcpuid(DWORD arg, unsigned char result[16])
    {
        DWORD eax;
        __asm("  xor %%ecx, %%ecx\n" \
              "  cpuid\n" \
              "  mov %%eax, 0(%[result])\n" \
              "  mov %%ebx, 4(%[result])\n" \
              "  mov %%ecx, 8(%[result])\n" \
              "  mov %%edx, 12(%[result])\n" \
            : "=a"(eax) /*output in eax*/\
            : "a"(arg), [result]"r"(result) /*inputs - arg in eax, result in any register*/\
            : "eax", "rbx", "ecx", "edx" /* registers that are clobbered*/
          );
        return eax;
    }

    DWORD getextcpuid(DWORD arg1, DWORD arg2, unsigned char result[16])
    {
        DWORD eax;
        __asm("  cpuid\n" \
              "  mov %%eax, 0(%[result])\n" \
              "  mov %%ebx, 4(%[result])\n" \
              "  mov %%ecx, 8(%[result])\n" \
              "  mov %%edx, 12(%[result])\n" \
            : "=a"(eax) /*output in eax*/\
            : "c"(arg1), "a"(arg2), [result]"r"(result) /*inputs - arg1 in ecx, arg2 in eax, result in any register*/\
            : "eax", "rbx", "ecx", "edx" /* registers that are clobbered*/
          );
        return eax;
    }

    void STDCALL JIT_ProfilerEnterLeaveTailcallStub(UINT_PTR ProfilerHandle)
    {
    }

#ifdef FEATURE_PREJIT
    void StubDispatchFixupStub()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }
#endif

    void StubDispatchFixupPatchLabel()
    {
        PORTABILITY_ASSERT("Implement for PAL");
    }
};
<|endoftext|>


<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2009 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__

#include <vw/Core/ProgressCallback.h>
#include <vw/Plate/PagedIndex.h>
#include <vw/Plate/Exception.h>
#include <vw/Plate/Blob.h>

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/convenience.hpp>
namespace fs = boost::filesystem;

using namespace vw;

// --------------------------------------------------------------------
//                             INDEX LEVEL
// --------------------------------------------------------------------

vw::platefile::IndexLevel::IndexLevel(boost::shared_ptr<PageGeneratorFactory> page_gen_factory,
                                      int level, int page_width, int page_height, int cache_size) :
  m_level(level), m_page_width(page_width), m_page_height(page_height), m_cache(cache_size) {
  int tiles_per_side = pow(2,level);
  m_horizontal_pages = ceil(float(tiles_per_side) / page_width);
  m_vertical_pages = ceil(float(tiles_per_side) / page_height);
  int pages = m_horizontal_pages * m_vertical_pages;

  // Create the cache handles
  m_cache_handles.resize(pages);
  m_cache_generators.resize(pages);
  for (int j = 0; j < m_vertical_pages; ++j) {
    for (int i = 0; i < m_horizontal_pages; ++i) {
      boost::shared_ptr<IndexPageGenerator> generator = page_gen_factory->create(level,
                                                                                i * m_page_width,
                                                                                j * m_page_height,
                                                                                page_width,
                                                                                page_height) ;
      m_cache_generators[j*m_horizontal_pages + i] = generator;
      m_cache_handles[j*m_horizontal_pages + i] = m_cache.insert( *generator );
    }
  }
}

vw::platefile::IndexLevel::~IndexLevel() {

  // We need to free the cache handles first before other things
  // (especially the generators) get unallocated.
  for (int i = 0; i < m_cache_handles.size(); ++i) {
    m_cache_handles[i].reset();
  }

}

void vw::platefile::IndexLevel::sync() {

  // We need to free the cache handles first before the data gets
  // saved.
  for (int i = 0; i < m_cache_handles.size(); ++i) {
    m_cache_handles[i].reset();
  }

}

/// Grab an IndexPage.  Useful if you want to serialize it by hand to disk.
boost::shared_ptr<vw::platefile::IndexPage> vw::platefile::IndexLevel::get_page(int col, int row) const {
  VW_ASSERT( col >= 0 && row >= 0 && col < pow(2,m_level) && row < pow(2,m_level),
             TileNotFoundErr() << "IndexLevel::get_page() failed.  Invalid index [ "
             << col << " " << row << " @ level " << m_level << "]" );

  int32 level_col = col / m_page_width;
  int32 level_row = row / m_page_height;

  // Access the page.  This will load it into memory if necessary.
  boost::shared_ptr<IndexPage> page = m_cache_handles[level_row*m_horizontal_pages + level_col];
  return page;
}

/// Fetch the value of an index node at this level.
vw::platefile::IndexRecord vw::platefile::IndexLevel::get(int32 col,
                                                          int32 row,
                                                          int32 transaction_id,
                                                          bool exact_match) const {

  VW_ASSERT( col >= 0 && row >= 0 && col < pow(2,m_level) && row < pow(2,m_level),
             TileNotFoundErr() << "IndexLevel::get() failed.  Invalid index [ "
             << col << " " << row << " @ level " << m_level << "]" );

  int32 level_col = col / m_page_width;
  int32 level_row = row / m_page_height;

  // Access the page.  This will load it into memory if necessary.
  boost::shared_ptr<IndexPage> page = m_cache_handles[level_row*m_horizontal_pages + level_col];
  return page->get(col, row, transaction_id, exact_match);
}

/// Fetch the value of an index node at this level.
vw::platefile::IndexLevel::multi_value_type
vw::platefile::IndexLevel::multi_get(int32 col,
                                     int32 row,
                                     int32 start_transaction_id,
                                     int32 end_transaction_id) const {

  VW_ASSERT( col >= 0 && row >= 0 && col < pow(2,m_level) && row < pow(2,m_level),
             TileNotFoundErr() << "IndexLevel::multi_get() failed.  Invalid index [ "
             << col << " " << row << " @ level " << m_level << "]" );

  int32 level_col = col / m_page_width;
  int32 level_row = row / m_page_height;

  // Access the page.  This will load it into memory if necessary.
  boost::shared_ptr<IndexPage> page = m_cache_handles[level_row*m_horizontal_pages + level_col];
  return page->multi_get(col, row, start_transaction_id, end_transaction_id);
}

/// Set the value of an index node at this level.
void vw::platefile::IndexLevel::set(vw::platefile::TileHeader const& header,
                                    vw::platefile::IndexRecord const& rec) {

  VW_ASSERT( header.col() >= 0 && header.row() >= 0 &&
             header.col() < pow(2,m_level) && header.row() < pow(2,m_level),
             TileNotFoundErr() << "IndexLevel::set() failed.  Invalid index [ "
             << header.col() << " " << header.row() << " @ level " << m_level << "]" );

  int32 level_col = header.col() / m_page_width;
  int32 level_row = header.row() / m_page_height;

  // Access the page.  This will load it into memory if necessary.
  boost::shared_ptr<IndexPage> page = m_cache_handles[level_row*m_horizontal_pages + level_col];
  page->set(header, rec);
}

/// Returns a list of valid tiles at this level.
std::list<vw::platefile::TileHeader>
vw::platefile::IndexLevel::valid_tiles(BBox2i const& region,
                                       int start_transaction_id,
                                       int end_transaction_id,
                                       int min_num_matches) const {

  // Start by computing the search range in pages based on the requested region.
  int32 min_level_col = region.min().x() / m_page_width;
  int32 min_level_row = region.min().y() / m_page_height;

  int32 max_level_col = ceilf(float(region.max().x()) / m_page_width);
  int32 max_level_row = ceilf(float(region.max().y()) / m_page_height);

  // Iterate over the pages that overlap with the region of interest.
  std::list<TileHeader> result;
  for (int32 level_row = min_level_row; level_row < max_level_row; ++level_row) {
    for (int32 level_col = min_level_col; level_col < max_level_col; ++level_col) {
      boost::shared_ptr<IndexPage> page = m_cache_handles[level_row*m_horizontal_pages + level_col];

      // Accumulate valid tiles that overlap with region from this IndexPage.
      std::list<TileHeader> sub_result = page->valid_tiles(region,
                                                           start_transaction_id,
                                                           end_transaction_id,
                                                           min_num_matches);
      result.splice(result.end(), sub_result);
    }
  }

  return result;
}

// --------------------------------------------------------------------
//                             PAGED INDEX
// --------------------------------------------------------------------

/// Create a new, empty index.
vw::platefile::PagedIndex::PagedIndex(boost::shared_ptr<PageGeneratorFactory> page_gen_factory,
                                      IndexHeader new_index_info,
                                      int page_width, int page_height, int default_cache_size) :
  m_page_gen_factory(page_gen_factory),
  m_page_width(page_width), m_page_height(page_height),
  m_default_cache_size(default_cache_size) {}

/// Open an existing index from a file on disk.
vw::platefile::PagedIndex::PagedIndex(boost::shared_ptr<PageGeneratorFactory> page_gen_factory,
                                      int page_width, int page_height, int default_cache_size) :
  m_page_gen_factory(page_gen_factory),
  m_page_width(page_width), m_page_height(page_height),
  m_default_cache_size(default_cache_size) {}

void vw::platefile::PagedIndex::sync() {

  // We need to free the cache handles first before other things
  // (especially the generators) get unallocated.
  for (int i = 0; i < m_levels.size(); ++i) {
    m_levels[i]->sync();
  }

}

// ----------------------- READ/WRITE REQUESTS  ----------------------

/// Grab an IndexPage.  Useful if you want to serialize it by hand to disk.
boost::shared_ptr<vw::platefile::IndexPage> vw::platefile::PagedIndex::page_request(int col, int row, int level) const {
  if (level < 0 || level >= m_levels.size())
    vw_throw(TileNotFoundErr() << "Requested page at " << level
             << " was greater than the max level (" << m_levels.size() << ").");
  return m_levels[level]->get_page(col, row);
}

vw::platefile::IndexRecord vw::platefile::PagedIndex::read_request(int col, int row, int level,
                                 int transaction_id, bool exact_transaction_match) {
  if (level < 0 || level >= m_levels.size())
    vw_throw(TileNotFoundErr() << "Requested tile at level " << level
             << " was greater than the max level (" << m_levels.size() << ").");

  IndexRecord rec = m_levels[level]->get(col, row,  transaction_id, exact_transaction_match);
  return rec;
}

vw::platefile::PagedIndex::multi_value_type
vw::platefile::PagedIndex::multi_read_request(int col, int row, int level,
                                              int start_transaction_id,
                                              int end_transaction_id) {
  if (level < 0 || level >= m_levels.size())
    vw_throw(TileNotFoundErr() << "Requested tile at level " << level
             << " was greater than the max level (" << m_levels.size() << ").");

  return m_levels[level]->multi_get(col, row,  start_transaction_id, end_transaction_id);
}

void vw::platefile::PagedIndex::write_update(TileHeader const& header, IndexRecord const& record) {
  // First, we check to make sure we have a sufficient number of
  // levels to save the requested data.  If not, we grow the levels
  // vector to the correct size.
  while (m_levels.size() <= header.level()) {
    boost::shared_ptr<IndexLevel> new_level( new IndexLevel(m_page_gen_factory,
                                                            m_levels.size(),
                                                            m_page_width, m_page_height,
                                                            m_default_cache_size) );
    m_levels.push_back(new_level);
  }
  m_levels[header.level()]->set(header, record);
}

// ----------------------- PROPERTIES  ----------------------

/// Returns a list of valid tiles that match this level, region, and
/// range of transaction_id's.  Returns a list of TileHeaders with
/// col/row/level and transaction_id of the most recent tile at each
/// valid location.  Note: there may be other tiles in the transaction
/// range at this col/row/level, but valid_tiles() only returns the
/// first one.
std::list<vw::platefile::TileHeader>
vw::platefile::PagedIndex::valid_tiles(int level, BBox2i const& region,
                                       int start_transaction_id,
                                       int end_transaction_id,
                                       int min_num_matches) const {

  // If the level does not exist, we return an empty list.
  if (level < 0 && level >= m_levels.size())
    return std::list<TileHeader>();

  // Otherwise, we delegate to the valid_tiles() method for that level.
  return m_levels[level]->valid_tiles(region,
                                      start_transaction_id, end_transaction_id,
                                      min_num_matches);
}

<commit_msg>Fixed a small bug in range checking code that would result in a seg fault if a bad level was passed into valid_tiles() for PagedIndex.<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2009 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__

#include <vw/Core/ProgressCallback.h>
#include <vw/Plate/PagedIndex.h>
#include <vw/Plate/Exception.h>
#include <vw/Plate/Blob.h>

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/convenience.hpp>
namespace fs = boost::filesystem;

using namespace vw;

// --------------------------------------------------------------------
//                             INDEX LEVEL
// --------------------------------------------------------------------

vw::platefile::IndexLevel::IndexLevel(boost::shared_ptr<PageGeneratorFactory> page_gen_factory,
                                      int level, int page_width, int page_height, int cache_size) :
  m_level(level), m_page_width(page_width), m_page_height(page_height), m_cache(cache_size) {
  int tiles_per_side = pow(2,level);
  m_horizontal_pages = ceil(float(tiles_per_side) / page_width);
  m_vertical_pages = ceil(float(tiles_per_side) / page_height);
  int pages = m_horizontal_pages * m_vertical_pages;

  // Create the cache handles
  m_cache_handles.resize(pages);
  m_cache_generators.resize(pages);
  for (int j = 0; j < m_vertical_pages; ++j) {
    for (int i = 0; i < m_horizontal_pages; ++i) {
      boost::shared_ptr<IndexPageGenerator> generator = page_gen_factory->create(level,
                                                                                i * m_page_width,
                                                                                j * m_page_height,
                                                                                page_width,
                                                                                page_height) ;
      m_cache_generators[j*m_horizontal_pages + i] = generator;
      m_cache_handles[j*m_horizontal_pages + i] = m_cache.insert( *generator );
    }
  }
}

vw::platefile::IndexLevel::~IndexLevel() {

  // We need to free the cache handles first before other things
  // (especially the generators) get unallocated.
  for (int i = 0; i < m_cache_handles.size(); ++i) {
    m_cache_handles[i].reset();
  }

}

void vw::platefile::IndexLevel::sync() {

  // We need to free the cache handles first before the data gets
  // saved.
  for (int i = 0; i < m_cache_handles.size(); ++i) {
    m_cache_handles[i].reset();
  }

}

/// Grab an IndexPage.  Useful if you want to serialize it by hand to disk.
boost::shared_ptr<vw::platefile::IndexPage> vw::platefile::IndexLevel::get_page(int col, int row) const {
  VW_ASSERT( col >= 0 && row >= 0 && col < pow(2,m_level) && row < pow(2,m_level),
             TileNotFoundErr() << "IndexLevel::get_page() failed.  Invalid index [ "
             << col << " " << row << " @ level " << m_level << "]" );

  int32 level_col = col / m_page_width;
  int32 level_row = row / m_page_height;

  // Access the page.  This will load it into memory if necessary.
  boost::shared_ptr<IndexPage> page = m_cache_handles[level_row*m_horizontal_pages + level_col];
  return page;
}

/// Fetch the value of an index node at this level.
vw::platefile::IndexRecord vw::platefile::IndexLevel::get(int32 col,
                                                          int32 row,
                                                          int32 transaction_id,
                                                          bool exact_match) const {

  VW_ASSERT( col >= 0 && row >= 0 && col < pow(2,m_level) && row < pow(2,m_level),
             TileNotFoundErr() << "IndexLevel::get() failed.  Invalid index [ "
             << col << " " << row << " @ level " << m_level << "]" );

  int32 level_col = col / m_page_width;
  int32 level_row = row / m_page_height;

  // Access the page.  This will load it into memory if necessary.
  boost::shared_ptr<IndexPage> page = m_cache_handles[level_row*m_horizontal_pages + level_col];
  return page->get(col, row, transaction_id, exact_match);
}

/// Fetch the value of an index node at this level.
vw::platefile::IndexLevel::multi_value_type
vw::platefile::IndexLevel::multi_get(int32 col,
                                     int32 row,
                                     int32 start_transaction_id,
                                     int32 end_transaction_id) const {

  VW_ASSERT( col >= 0 && row >= 0 && col < pow(2,m_level) && row < pow(2,m_level),
             TileNotFoundErr() << "IndexLevel::multi_get() failed.  Invalid index [ "
             << col << " " << row << " @ level " << m_level << "]" );

  int32 level_col = col / m_page_width;
  int32 level_row = row / m_page_height;

  // Access the page.  This will load it into memory if necessary.
  boost::shared_ptr<IndexPage> page = m_cache_handles[level_row*m_horizontal_pages + level_col];
  return page->multi_get(col, row, start_transaction_id, end_transaction_id);
}

/// Set the value of an index node at this level.
void vw::platefile::IndexLevel::set(vw::platefile::TileHeader const& header,
                                    vw::platefile::IndexRecord const& rec) {

  VW_ASSERT( header.col() >= 0 && header.row() >= 0 &&
             header.col() < pow(2,m_level) && header.row() < pow(2,m_level),
             TileNotFoundErr() << "IndexLevel::set() failed.  Invalid index [ "
             << header.col() << " " << header.row() << " @ level " << m_level << "]" );

  int32 level_col = header.col() / m_page_width;
  int32 level_row = header.row() / m_page_height;

  // Access the page.  This will load it into memory if necessary.
  boost::shared_ptr<IndexPage> page = m_cache_handles[level_row*m_horizontal_pages + level_col];
  page->set(header, rec);
}

/// Returns a list of valid tiles at this level.
std::list<vw::platefile::TileHeader>
vw::platefile::IndexLevel::valid_tiles(BBox2i const& region,
                                       int start_transaction_id,
                                       int end_transaction_id,
                                       int min_num_matches) const {

  // Start by computing the search range in pages based on the requested region.
  int32 min_level_col = region.min().x() / m_page_width;
  int32 min_level_row = region.min().y() / m_page_height;

  int32 max_level_col = ceilf(float(region.max().x()) / m_page_width);
  int32 max_level_row = ceilf(float(region.max().y()) / m_page_height);

  // Iterate over the pages that overlap with the region of interest.
  std::list<TileHeader> result;
  for (int32 level_row = min_level_row; level_row < max_level_row; ++level_row) {
    for (int32 level_col = min_level_col; level_col < max_level_col; ++level_col) {
      boost::shared_ptr<IndexPage> page = m_cache_handles[level_row*m_horizontal_pages + level_col];

      // Accumulate valid tiles that overlap with region from this IndexPage.
      std::list<TileHeader> sub_result = page->valid_tiles(region,
                                                           start_transaction_id,
                                                           end_transaction_id,
                                                           min_num_matches);
      result.splice(result.end(), sub_result);
    }
  }

  return result;
}

// --------------------------------------------------------------------
//                             PAGED INDEX
// --------------------------------------------------------------------

/// Create a new, empty index.
vw::platefile::PagedIndex::PagedIndex(boost::shared_ptr<PageGeneratorFactory> page_gen_factory,
                                      IndexHeader new_index_info,
                                      int page_width, int page_height, int default_cache_size) :
  m_page_gen_factory(page_gen_factory),
  m_page_width(page_width), m_page_height(page_height),
  m_default_cache_size(default_cache_size) {}

/// Open an existing index from a file on disk.
vw::platefile::PagedIndex::PagedIndex(boost::shared_ptr<PageGeneratorFactory> page_gen_factory,
                                      int page_width, int page_height, int default_cache_size) :
  m_page_gen_factory(page_gen_factory),
  m_page_width(page_width), m_page_height(page_height),
  m_default_cache_size(default_cache_size) {}

void vw::platefile::PagedIndex::sync() {

  // We need to free the cache handles first before other things
  // (especially the generators) get unallocated.
  for (int i = 0; i < m_levels.size(); ++i) {
    m_levels[i]->sync();
  }

}

// ----------------------- READ/WRITE REQUESTS  ----------------------

/// Grab an IndexPage.  Useful if you want to serialize it by hand to disk.
boost::shared_ptr<vw::platefile::IndexPage> vw::platefile::PagedIndex::page_request(int col, int row, int level) const {
  if (level < 0 || level >= m_levels.size())
    vw_throw(TileNotFoundErr() << "Requested page at " << level
             << " was greater than the max level (" << m_levels.size() << ").");
  return m_levels[level]->get_page(col, row);
}

vw::platefile::IndexRecord vw::platefile::PagedIndex::read_request(int col, int row, int level,
                                 int transaction_id, bool exact_transaction_match) {
  if (level < 0 || level >= m_levels.size())
    vw_throw(TileNotFoundErr() << "Requested tile at level " << level
             << " was greater than the max level (" << m_levels.size() << ").");

  IndexRecord rec = m_levels[level]->get(col, row,  transaction_id, exact_transaction_match);
  return rec;
}

vw::platefile::PagedIndex::multi_value_type
vw::platefile::PagedIndex::multi_read_request(int col, int row, int level,
                                              int start_transaction_id,
                                              int end_transaction_id) {
  if (level < 0 || level >= m_levels.size())
    vw_throw(TileNotFoundErr() << "Requested tile at level " << level
             << " was greater than the max level (" << m_levels.size() << ").");

  return m_levels[level]->multi_get(col, row,  start_transaction_id, end_transaction_id);
}

void vw::platefile::PagedIndex::write_update(TileHeader const& header, IndexRecord const& record) {
  // First, we check to make sure we have a sufficient number of
  // levels to save the requested data.  If not, we grow the levels
  // vector to the correct size.
  while (m_levels.size() <= header.level()) {
    boost::shared_ptr<IndexLevel> new_level( new IndexLevel(m_page_gen_factory,
                                                            m_levels.size(),
                                                            m_page_width, m_page_height,
                                                            m_default_cache_size) );
    m_levels.push_back(new_level);
  }
  m_levels[header.level()]->set(header, record);
}

// ----------------------- PROPERTIES  ----------------------

/// Returns a list of valid tiles that match this level, region, and
/// range of transaction_id's.  Returns a list of TileHeaders with
/// col/row/level and transaction_id of the most recent tile at each
/// valid location.  Note: there may be other tiles in the transaction
/// range at this col/row/level, but valid_tiles() only returns the
/// first one.
std::list<vw::platefile::TileHeader>
vw::platefile::PagedIndex::valid_tiles(int level, BBox2i const& region,
                                       int start_transaction_id,
                                       int end_transaction_id,
                                       int min_num_matches) const {

  // If the level does not exist, we return an empty list.
  if (level < 0 || level >= m_levels.size())
    return std::list<TileHeader>();

  // Otherwise, we delegate to the valid_tiles() method for that level.
  return m_levels[level]->valid_tiles(region,
                                      start_transaction_id, end_transaction_id,
                                      min_num_matches);
}

<|endoftext|>


<commit_before>//
//  MCCertificateUtils.cc
//  mailcore2
//
//  Created by DINH Viêt Hoà on 7/25/13.
//  Copyright (c) 2013 MailCore. All rights reserved.
//

#include "MCCertificateUtils.h"

#if __APPLE__
#include <CoreFoundation/CoreFoundation.h>
#include <Security/Security.h>
#endif

#include "MCLog.h"

bool mailcore::checkCertificate(mailstream * stream, String * hostname)
{
#if __APPLE__
    bool result = false;
    CFStringRef hostnameCFString = CFStringCreateWithCharacters(NULL, (const UniChar *) hostname->unicodeCharacters(),
                                                                hostname->length());
    SecPolicyRef policy = SecPolicyCreateSSL(true, hostnameCFString);

    CFMutableArrayRef certificates;
    SecTrustRef trust;
    certificates = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);

    carray * cCerts = mailstream_get_certificate_chain(stream);
    if (cCerts == NULL) {
        fprintf(stderr, "warning: No certificate chain retrieved");
        return false;
    }
    for(unsigned int i = 0 ; i < carray_count(cCerts) ; i ++) {
        MMAPString * str;
        str = (MMAPString *) carray_get(cCerts, i);
        CFDataRef data = CFDataCreate(NULL, (const UInt8 *) str->str, (CFIndex) str->len);
        SecCertificateRef cert = SecCertificateCreateWithData(NULL, data);
        CFArrayAppendValue(certificates, cert);
        CFRelease(data);

        OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &trust);
        SecTrustResultType trustResult;
        status = SecTrustEvaluate(trust, &trustResult);
        switch (trustResult) {
            case kSecTrustResultUnspecified:
            case kSecTrustResultProceed:
                // certificate chain is ok
                result = true;
                break;

            default:
                // certificate chain is invalid
                break;
        }

        CFRelease(cert);
    }

    CFRelease(trust);
    CFRelease(certificates);
    CFRelease(policy);
    CFRelease(hostnameCFString);
    mailstream_certificate_chain_free(cCerts);

    return result;
#else
    //TODO check certificate
    // for other platforms too.
    return true;
#endif
}
<commit_msg>Fixed certificate check code (Fixed #263).<commit_after>//
//  MCCertificateUtils.cc
//  mailcore2
//
//  Created by DINH Viêt Hoà on 7/25/13.
//  Copyright (c) 2013 MailCore. All rights reserved.
//

#include "MCCertificateUtils.h"

#if __APPLE__
#include <CoreFoundation/CoreFoundation.h>
#include <Security/Security.h>
#endif

#include "MCLog.h"

bool mailcore::checkCertificate(mailstream * stream, String * hostname)
{
#if __APPLE__
    bool result = false;
    CFStringRef hostnameCFString;
    SecPolicyRef policy;
    CFMutableArrayRef certificates;
    SecTrustRef trust = NULL;
    SecTrustResultType trustResult;
    OSStatus status;

    carray * cCerts = mailstream_get_certificate_chain(stream);
    if (cCerts == NULL) {
        fprintf(stderr, "warning: No certificate chain retrieved");
        goto err;
    }

    hostnameCFString = CFStringCreateWithCharacters(NULL, (const UniChar *) hostname->unicodeCharacters(),
                                                                hostname->length());
    policy = SecPolicyCreateSSL(true, hostnameCFString);
    certificates = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);

    for(unsigned int i = 0 ; i < carray_count(cCerts) ; i ++) {
        MMAPString * str;
        str = (MMAPString *) carray_get(cCerts, i);
        CFDataRef data = CFDataCreate(NULL, (const UInt8 *) str->str, (CFIndex) str->len);
        SecCertificateRef cert = SecCertificateCreateWithData(NULL, data);
        CFArrayAppendValue(certificates, cert);
        CFRelease(data);
        CFRelease(cert);
    }

    status = SecTrustCreateWithCertificates(certificates, policy, &trust);
    if (status != noErr) {
        goto free_certs;
    }

    status = SecTrustEvaluate(trust, &trustResult);
    switch (trustResult) {
        case kSecTrustResultUnspecified:
        case kSecTrustResultProceed:
            // certificate chain is ok
            result = true;
            break;

        default:
            // certificate chain is invalid
            break;
    }

    CFRelease(trust);
free_certs:
    CFRelease(certificates);
    mailstream_certificate_chain_free(cCerts);
    CFRelease(policy);
    CFRelease(hostnameCFString);
err:
    return result;
#else
    //TODO check certificate
    // for other platforms too.
    return true;
#endif
}
<|endoftext|>


<commit_before>// Generally always include these
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkActor.h>

// For reading in images
#include <vtkSmartPointer.h>
#include <vtkPNGReader.h>

#include <vtkImageDataGeometryFilter.h>

#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkTransform.h>
#include <vtkTransformPolyDataFilter.h>

#include <vtkCleanPolyData.h>
#include <vtkAppendPolyData.h>
//#include <vtkUnstructuredGrid.h>
#include <vtkDataSetMapper.h>

int main(int argc, char* argv[])
{
  // Verify input arguments
  if (argc < 3)
  {
    std::cout << "Usage: ./PNGReader.exe"
              << " IMAGE_ONE(.png) IMAGE_TWO(.png)" << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << argv[1] << " " << argv[2];

  // Read in two PNG images (maybe doesn't have to be done for ARFI images).
  vtkSmartPointer<vtkPNGReader> reader =
    vtkSmartPointer<vtkPNGReader>::New();
  reader->SetFileName(argv[1]);

  vtkSmartPointer<vtkPNGReader> reader2 =
    vtkSmartPointer<vtkPNGReader>::New();
  reader2->SetFileName(argv[2]);

  // Convert the PNG image to polydata
  vtkSmartPointer<vtkImageDataGeometryFilter> imageDataGeometryFilter =
    vtkSmartPointer<vtkImageDataGeometryFilter>::New();
  imageDataGeometryFilter->SetInputConnection(reader->GetOutputPort());
  imageDataGeometryFilter->Update();

  vtkSmartPointer<vtkImageDataGeometryFilter> imageDataGeometryFilter2 =
    vtkSmartPointer<vtkImageDataGeometryFilter>::New();
  imageDataGeometryFilter2->SetInputConnection(reader2->GetOutputPort());
  imageDataGeometryFilter2->Update();

  // Rotate the second image by 45 degrees.
  vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();
  //transform->RotateWXYZ(double angle, double x, double y, double z);
  transform->RotateWXYZ(45, 0, 1, 0);
  vtkSmartPointer<vtkTransformPolyDataFilter> transformFilter =
      vtkSmartPointer<vtkTransformPolyDataFilter>::New();
  transformFilter->SetTransform(transform);
  transformFilter->SetInputConnection(imageDataGeometryFilter2->GetOutputPort());
  transformFilter->Update();

  //Append the two meshes
  vtkSmartPointer<vtkPolyData> input1 =
    vtkSmartPointer<vtkPolyData>::New();
  input1->ShallowCopy(imageDataGeometryFilter->GetOutput());

  vtkSmartPointer<vtkPolyData> input2 =
    vtkSmartPointer<vtkPolyData>::New();
  input2->ShallowCopy(transformFilter->GetOutput());

  vtkSmartPointer<vtkAppendPolyData> appendFilter =
    vtkSmartPointer<vtkAppendPolyData>::New();
  #if VTK_MAJOR_VERSION <= 5
    appendFilter->AddInputConnection(input1->GetProducerPort());
    appendFilter->AddInputConnection(input2->GetProducerPort());
  #else
    appendFilter->AddInputData(input1);
    appendFilter->AddInputData(input2);
  #endif
  appendFilter->Update();

  // Remove any duplicate points.
  vtkSmartPointer<vtkCleanPolyData> cleanFilter =
    vtkSmartPointer<vtkCleanPolyData>::New();
  cleanFilter->SetInputConnection(appendFilter->GetOutputPort());
  cleanFilter->Update();

  // Create a mapper and actor
  vtkSmartPointer<vtkPolyDataMapper> mapper =
    vtkSmartPointer<vtkPolyDataMapper>::New();
  mapper->SetInputConnection(cleanFilter->GetOutputPort());

  vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
  actor->SetMapper(mapper);

  // Rotate actor
  // actor->RotateY(45);

   // Visualization
  vtkSmartPointer<vtkRenderer> renderer =
    vtkSmartPointer<vtkRenderer>::New();

  vtkSmartPointer<vtkRenderWindow> renderWindow =
    vtkSmartPointer<vtkRenderWindow>::New();
  renderWindow->AddRenderer(renderer);

  vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
    vtkSmartPointer<vtkRenderWindowInteractor>::New();
  renderWindowInteractor->SetRenderWindow(renderWindow);

  renderer->AddActor(actor);
  renderer->SetBackground(1, 1, 1); // Background color white

  renderWindow->Render();

  // Start interactive window.
  renderWindowInteractor->Start();

  return EXIT_SUCCESS;
}
<commit_msg>Changed from PNGReader to JPEGReader because there are more JPG images of dogs to choose from.<commit_after>// Generally always include these
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkActor.h>

// For reading in images
#include <vtkSmartPointer.h>
#include <vtkJPEGReader.h>

#include <vtkImageDataGeometryFilter.h>

#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkTransform.h>
#include <vtkTransformPolyDataFilter.h>

#include <vtkCleanPolyData.h>
#include <vtkAppendPolyData.h>
//#include <vtkUnstructuredGrid.h>
#include <vtkDataSetMapper.h>

int main(int argc, char* argv[])
{
  // Verify input arguments
  if (argc < 3)
  {
    std::cout << "Usage: " << argv[0]
              << " IMAGE_ONE(.png) IMAGE_TWO(.png)" << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << argv[1] << " " << argv[2];

  // Read in two PNG images (maybe doesn't have to be done for ARFI images).
  vtkSmartPointer<vtkJPEGReader> reader =
    vtkSmartPointer<vtkJPEGReader>::New();
  reader->SetFileName(argv[1]);

  vtkSmartPointer<vtkJPEGReader> reader2 =
    vtkSmartPointer<vtkJPEGReader>::New();
  reader2->SetFileName(argv[2]);

  // Convert the PNG image to polydata
  vtkSmartPointer<vtkImageDataGeometryFilter> imageDataGeometryFilter =
    vtkSmartPointer<vtkImageDataGeometryFilter>::New();
  imageDataGeometryFilter->SetInputConnection(reader->GetOutputPort());
  imageDataGeometryFilter->Update();

  vtkSmartPointer<vtkImageDataGeometryFilter> imageDataGeometryFilter2 =
    vtkSmartPointer<vtkImageDataGeometryFilter>::New();
  imageDataGeometryFilter2->SetInputConnection(reader2->GetOutputPort());
  imageDataGeometryFilter2->Update();

  // Rotate the second image by 45 degrees.
  vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New();
  //transform->RotateWXYZ(double angle, double x, double y, double z);
  transform->RotateWXYZ(45, 0, 1, 0);
  vtkSmartPointer<vtkTransformPolyDataFilter> transformFilter =
      vtkSmartPointer<vtkTransformPolyDataFilter>::New();
  transformFilter->SetTransform(transform);
  transformFilter->SetInputConnection(imageDataGeometryFilter2->GetOutputPort());
  transformFilter->Update();

  //Append the two meshes
  vtkSmartPointer<vtkPolyData> input1 =
    vtkSmartPointer<vtkPolyData>::New();
  input1->ShallowCopy(imageDataGeometryFilter->GetOutput());

  vtkSmartPointer<vtkPolyData> input2 =
    vtkSmartPointer<vtkPolyData>::New();
  input2->ShallowCopy(transformFilter->GetOutput());

  vtkSmartPointer<vtkAppendPolyData> appendFilter =
    vtkSmartPointer<vtkAppendPolyData>::New();
  #if VTK_MAJOR_VERSION <= 5
    appendFilter->AddInputConnection(input1->GetProducerPort());
    appendFilter->AddInputConnection(input2->GetProducerPort());
  #else
    appendFilter->AddInputData(input1);
    appendFilter->AddInputData(input2);
  #endif
  appendFilter->Update();

  // Remove any duplicate points.
  vtkSmartPointer<vtkCleanPolyData> cleanFilter =
    vtkSmartPointer<vtkCleanPolyData>::New();
  cleanFilter->SetInputConnection(appendFilter->GetOutputPort());
  cleanFilter->Update();

  // Create a mapper and actor
  vtkSmartPointer<vtkPolyDataMapper> mapper =
    vtkSmartPointer<vtkPolyDataMapper>::New();
  mapper->SetInputConnection(cleanFilter->GetOutputPort());

  vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
  actor->SetMapper(mapper);

  // Rotate actor
  // actor->RotateY(45);

   // Visualization
  vtkSmartPointer<vtkRenderer> renderer =
    vtkSmartPointer<vtkRenderer>::New();

  vtkSmartPointer<vtkRenderWindow> renderWindow =
    vtkSmartPointer<vtkRenderWindow>::New();
  renderWindow->AddRenderer(renderer);

  vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
    vtkSmartPointer<vtkRenderWindowInteractor>::New();
  renderWindowInteractor->SetRenderWindow(renderWindow);

  renderer->AddActor(actor);
  renderer->SetBackground(1, 1, 1); // Background color white

  renderWindow->Render();

  // Start interactive window.
  renderWindowInteractor->Start();

  return EXIT_SUCCESS;
}
<|endoftext|>